1 # markdown is released under the BSD license
2 # Copyright 2007, 2008 The Python Markdown Project (v. 1.7 and later)
3 # Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
4 # Copyright 2004 Manfred Stienstra (the original version)
8 # Redistribution and use in source and binary forms, with or without
9 # modification, are permitted provided that the following conditions are met:
11 # * Redistributions of source code must retain the above copyright
12 # notice, this list of conditions and the following disclaimer.
13 # * Redistributions in binary form must reproduce the above copyright
14 # notice, this list of conditions and the following disclaimer in the
15 # documentation and/or other materials provided with the distribution.
16 # * Neither the name of the <organization> nor the
17 # names of its contributors may be used to endorse or promote products
18 # derived from this software without specific prior written permission.
20 # THIS SOFTWARE IS PROVIDED BY THE PYTHON MARKDOWN PROJECT ''AS IS'' AND ANY
21 # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
22 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23 # DISCLAIMED. IN NO EVENT SHALL ANY CONTRIBUTORS TO THE PYTHON MARKDOWN PROJECT
24 # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 # POSSIBILITY OF SUCH DAMAGE.
34 HeaderID Extension for Python-Markdown
35 ======================================
37 Auto-generate id attributes for HTML headers.
42 >>> text = "# Some Header #"
43 >>> md = markdown.markdown(text, ['headerid'])
45 <h1 id="some-header">Some Header</h1>
47 All header IDs are unique:
53 >>> md = markdown.markdown(text, ['headerid'])
55 <h1 id="header">Header</h1>
56 <h1 id="header_1">Header</h1>
57 <h1 id="header_2">Header</h1>
59 To fit within a html template's hierarchy, set the header base level:
64 >>> md = markdown.markdown(text, ['headerid(level=3)'])
66 <h3 id="some-header">Some Header</h3>
67 <h4 id="next-level">Next Level</h4>
69 Works with inline markup.
71 >>> text = '#Some *Header* with [markup](http://example.com).'
72 >>> md = markdown.markdown(text, ['headerid'])
74 <h1 id="some-header-with-markup">Some <em>Header</em> with <a href="http://example.com">markup</a>.</h1>
76 Turn off auto generated IDs:
80 ... # Another Header'''
81 >>> md = markdown.markdown(text, ['headerid(forceid=False)'])
84 <h1>Another Header</h1>
86 Use with MetaData extension:
88 >>> text = '''header_level: 2
89 ... header_forceid: Off
92 >>> md = markdown.markdown(text, ['headerid', 'meta'])
96 Copyright 2007-2011 [Waylan Limberg](http://achinghead.com/).
98 Project website: <http://packages.python.org/Markdown/extensions/header_id.html>
99 Contact: markdown@freewisdom.org
101 License: BSD (see ../docs/LICENSE for details)
104 * [Python 2.3+](http://python.org)
105 * [Markdown 2.0+](http://packages.python.org/Markdown/)
109 from __future__
import absolute_import
110 from __future__
import unicode_literals
111 from . import Extension
112 from ..treeprocessors
import Treeprocessor
117 logger
= logging
.getLogger('MARKDOWN')
119 IDCOUNT_RE
= re
.compile(r
'^(.*)_([0-9]+)$')
122 def slugify(value
, separator
):
123 """ Slugify a string, to make it URL friendly. """
124 value
= unicodedata
.normalize('NFKD', value
).encode('ascii', 'ignore')
125 value
= re
.sub('[^\w\s-]', '', value
.decode('ascii')).strip().lower()
126 return re
.sub('[%s\s]+' % separator
, separator
, value
)
130 """ Ensure id is unique in set of ids. Append '_1', '_2'... if not """
131 while id in ids
or not id:
132 m
= IDCOUNT_RE
.match(id)
134 id = '%s_%d'% (m
.group(1), int(m
.group(2))+1)
136 id = '%s_%d'% (id, 1)
142 """ Loop through all children and return text only.
144 Reimplements method of same name added to ElementTree in Python 2.7
150 for s
in itertext(e
):
156 class HeaderIdTreeprocessor(Treeprocessor
):
157 """ Assign IDs to headers. """
162 start_level
, force_id
= self
._get
_meta
()
163 slugify
= self
.config
['slugify']
164 sep
= self
.config
['separator']
165 for elem
in doc
.getiterator():
166 if elem
.tag
in ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']:
168 if "id" in elem
.attrib
:
171 id = slugify(''.join(itertext(elem
)), sep
)
172 elem
.set('id', unique(id, self
.IDs
))
174 level
= int(elem
.tag
[-1]) + start_level
177 elem
.tag
= 'h%d' % level
181 """ Return meta data suported by this ext as a tuple """
182 level
= int(self
.config
['level']) - 1
183 force
= self
._str
2bool
(self
.config
['forceid'])
184 if hasattr(self
.md
, 'Meta'):
185 if 'header_level' in self
.md
.Meta
:
186 level
= int(self
.md
.Meta
['header_level'][0]) - 1
187 if 'header_forceid' in self
.md
.Meta
:
188 force
= self
._str
2bool
(self
.md
.Meta
['header_forceid'][0])
191 def _str2bool(self
, s
, default
=False):
192 """ Convert a string to a booleen value. """
194 if s
.lower() in ['0', 'f', 'false', 'off', 'no', 'n']:
196 elif s
.lower() in ['1', 't', 'true', 'on', 'yes', 'y']:
201 class HeaderIdExtension(Extension
):
202 def __init__(self
, configs
):
205 'level' : ['1', 'Base level for headers.'],
206 'forceid' : ['True', 'Force all headers to have an id.'],
207 'separator' : ['-', 'Word separator.'],
208 'slugify' : [slugify
, 'Callable to generate anchors'],
211 for key
, value
in configs
:
212 self
.setConfig(key
, value
)
214 def extendMarkdown(self
, md
, md_globals
):
215 md
.registerExtension(self
)
216 self
.processor
= HeaderIdTreeprocessor()
217 self
.processor
.md
= md
218 self
.processor
.config
= self
.getConfigs()
219 if 'attr_list' in md
.treeprocessors
.keys():
220 # insert after attr_list treeprocessor
221 md
.treeprocessors
.add('headerid', self
.processor
, '>attr_list')
223 # insert after 'prettify' treeprocessor.
224 md
.treeprocessors
.add('headerid', self
.processor
, '>prettify')
227 self
.processor
.IDs
= set()
230 def makeExtension(configs
=None):
231 return HeaderIdExtension(configs
=configs
)