| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
""" |
| 4 |
HeaderID Extension for Python-Markdown |
| 5 |
====================================== |
| 6 |
|
| 7 |
Adds ability to set HTML IDs for headers. |
| 8 |
|
| 9 |
Basic usage: |
| 10 |
|
| 11 |
>>> import markdown |
| 12 |
>>> text = "# Some Header # {#some_id}" |
| 13 |
>>> md = markdown.markdown(text, ['headerid']) |
| 14 |
>>> md |
| 15 |
u'<h1 id="some_id">Some Header</h1>' |
| 16 |
|
| 17 |
All header IDs are unique: |
| 18 |
|
| 19 |
>>> text = ''' |
| 20 |
... #Header |
| 21 |
... #Another Header {#header} |
| 22 |
... #Third Header {#header}''' |
| 23 |
>>> md = markdown.markdown(text, ['headerid']) |
| 24 |
>>> md |
| 25 |
u'<h1 id="header">Header</h1>\\n<h1 id="header_1">Another Header</h1>\\n<h1 id="header_2">Third Header</h1>' |
| 26 |
|
| 27 |
To fit within a html template's hierarchy, set the header base level: |
| 28 |
|
| 29 |
>>> text = ''' |
| 30 |
... #Some Header |
| 31 |
... ## Next Level''' |
| 32 |
>>> md = markdown.markdown(text, ['headerid(level=3)']) |
| 33 |
>>> md |
| 34 |
u'<h3 id="some_header">Some Header</h3>\\n<h4 id="next_level">Next Level</h4>' |
| 35 |
|
| 36 |
Turn off auto generated IDs: |
| 37 |
|
| 38 |
>>> text = ''' |
| 39 |
... # Some Header |
| 40 |
... # Header with ID # { #foo }''' |
| 41 |
>>> md = markdown.markdown(text, ['headerid(forceid=False)']) |
| 42 |
>>> md |
| 43 |
u'<h1>Some Header</h1>\\n<h1 id="foo">Header with ID</h1>' |
| 44 |
|
| 45 |
Use with MetaData extension: |
| 46 |
|
| 47 |
>>> text = '''header_level: 2 |
| 48 |
... header_forceid: Off |
| 49 |
... |
| 50 |
... # A Header''' |
| 51 |
>>> md = markdown.markdown(text, ['headerid', 'meta']) |
| 52 |
>>> md |
| 53 |
u'<h2>A Header</h2>' |
| 54 |
|
| 55 |
Copyright 2007-2008 [Waylan Limberg](http://achinghead.com/). |
| 56 |
|
| 57 |
Project website: <http://www.freewisdom.org/project/python-markdown/HeaderId> |
| 58 |
Contact: markdown@freewisdom.org |
| 59 |
|
| 60 |
License: BSD (see ../docs/LICENSE for details) |
| 61 |
|
| 62 |
Dependencies: |
| 63 |
* [Python 2.3+](http://python.org) |
| 64 |
* [Markdown 2.0+](http://www.freewisdom.org/projects/python-markdown/) |
| 65 |
|
| 66 |
""" |
| 67 |
|
| 68 |
import markdown |
| 69 |
from markdown.util import etree |
| 70 |
import re |
| 71 |
from string import ascii_lowercase, digits, punctuation |
| 72 |
import logging |
| 73 |
|
| 74 |
logger = logging.getLogger('MARKDOWN') |
| 75 |
|
| 76 |
ID_CHARS = ascii_lowercase + digits + '-_' |
| 77 |
IDCOUNT_RE = re.compile(r'^(.*)_([0-9]+)$') |
| 78 |
|
| 79 |
|
| 80 |
class HeaderIdProcessor(markdown.blockprocessors.BlockProcessor): |
| 81 |
""" Replacement BlockProcessor for Header IDs. """ |
| 82 |
|
| 83 |
# Detect a header at start of any line in block |
| 84 |
RE = re.compile(r"""(^|\n) |
| 85 |
(?P<level>\#{1,6}) # group('level') = string of hashes |
| 86 |
(?P<header>.*?) # group('header') = Header text |
| 87 |
\#* # optional closing hashes |
| 88 |
(?:[ \t]*\{[ \t]*\#(?P<id>[-_.:a-zA-Z0-9]+)[ \t]*\})? |
| 89 |
(\n|$) # ^^ group('id') = id attribute |
| 90 |
""", |
| 91 |
re.VERBOSE) |
| 92 |
|
| 93 |
IDs = [] |
| 94 |
|
| 95 |
def test(self, parent, block): |
| 96 |
return bool(self.RE.search(block)) |
| 97 |
|
| 98 |
def run(self, parent, blocks): |
| 99 |
block = blocks.pop(0) |
| 100 |
m = self.RE.search(block) |
| 101 |
if m: |
| 102 |
before = block[:m.start()] # All lines before header |
| 103 |
after = block[m.end():] # All lines after header |
| 104 |
if before: |
| 105 |
# As the header was not the first line of the block and the |
| 106 |
# lines before the header must be parsed first, |
| 107 |
# recursively parse this lines as a block. |
| 108 |
self.parser.parseBlocks(parent, [before]) |
| 109 |
# Create header using named groups from RE |
| 110 |
start_level, force_id = self._get_meta() |
| 111 |
level = len(m.group('level')) + start_level |
| 112 |
if level > 6: |
| 113 |
level = 6 |
| 114 |
h = etree.SubElement(parent, 'h%d' % level) |
| 115 |
h.text = m.group('header').strip() |
| 116 |
if m.group('id'): |
| 117 |
h.set('id', self._unique_id(m.group('id'))) |
| 118 |
elif force_id: |
| 119 |
h.set('id', self._create_id(m.group('header').strip())) |
| 120 |
if after: |
| 121 |
# Insert remaining lines as first block for future parsing. |
| 122 |
blocks.insert(0, after) |
| 123 |
else: |
| 124 |
# This should never happen, but just in case... |
| 125 |
logger.warn("We've got a problem header: %r" % block) |
| 126 |
|
| 127 |
def _get_meta(self): |
| 128 |
""" Return meta data suported by this ext as a tuple """ |
| 129 |
level = int(self.config['level'][0]) - 1 |
| 130 |
force = self._str2bool(self.config['forceid'][0]) |
| 131 |
if hasattr(self.md, 'Meta'): |
| 132 |
if self.md.Meta.has_key('header_level'): |
| 133 |
level = int(self.md.Meta['header_level'][0]) - 1 |
| 134 |
if self.md.Meta.has_key('header_forceid'): |
| 135 |
force = self._str2bool(self.md.Meta['header_forceid'][0]) |
| 136 |
return level, force |
| 137 |
|
| 138 |
def _str2bool(self, s, default=False): |
| 139 |
""" Convert a string to a booleen value. """ |
| 140 |
s = str(s) |
| 141 |
if s.lower() in ['0', 'f', 'false', 'off', 'no', 'n']: |
| 142 |
return False |
| 143 |
elif s.lower() in ['1', 't', 'true', 'on', 'yes', 'y']: |
| 144 |
return True |
| 145 |
return default |
| 146 |
|
| 147 |
def _unique_id(self, id): |
| 148 |
""" Ensure ID is unique. Append '_1', '_2'... if not """ |
| 149 |
while id in self.IDs: |
| 150 |
m = IDCOUNT_RE.match(id) |
| 151 |
if m: |
| 152 |
id = '%s_%d'% (m.group(1), int(m.group(2))+1) |
| 153 |
else: |
| 154 |
id = '%s_%d'% (id, 1) |
| 155 |
self.IDs.append(id) |
| 156 |
return id |
| 157 |
|
| 158 |
def _create_id(self, header): |
| 159 |
""" Return ID from Header text. """ |
| 160 |
h = '' |
| 161 |
for c in header.lower().replace(' ', self.config['separator'][0]): |
| 162 |
if c in ID_CHARS: |
| 163 |
h += c |
| 164 |
elif c not in punctuation: |
| 165 |
h += '+' |
| 166 |
return self._unique_id(h) |
| 167 |
|
| 168 |
|
| 169 |
class HeaderIdExtension (markdown.Extension): |
| 170 |
def __init__(self, configs): |
| 171 |
# set defaults |
| 172 |
self.config = { |
| 173 |
'level' : ['1', 'Base level for headers.'], |
| 174 |
'forceid' : ['True', 'Force all headers to have an id.'], |
| 175 |
'separator' : ['_', 'Word separator.'], |
| 176 |
} |
| 177 |
|
| 178 |
for key, value in configs: |
| 179 |
self.setConfig(key, value) |
| 180 |
|
| 181 |
def extendMarkdown(self, md, md_globals): |
| 182 |
md.registerExtension(self) |
| 183 |
self.processor = HeaderIdProcessor(md.parser) |
| 184 |
self.processor.md = md |
| 185 |
self.processor.config = self.config |
| 186 |
# Replace existing hasheader in place. |
| 187 |
md.parser.blockprocessors['hashheader'] = self.processor |
| 188 |
|
| 189 |
def reset(self): |
| 190 |
self.processor.IDs = [] |
| 191 |
|
| 192 |
|
| 193 |
def makeExtension(configs=None): |
| 194 |
return HeaderIdExtension(configs=configs) |
| 195 |
|
| 196 |
if __name__ == "__main__": |
| 197 |
import doctest |
| 198 |
doctest.testmod() |