aboutsummaryrefslogtreecommitdiffstats
path: root/markdown_extensions/toc.py
diff options
context:
space:
mode:
authorJack Miller <jack@codezen.org>2008-10-28 22:33:16 -0400
committerWaylan Limberg <waylan@gmail.com>2008-10-28 22:33:16 -0400
commite5fcf1bf127567d585f75525a37b0dc852911104 (patch)
tree338639a00046a340ec1550b8a5e507f4c22e377b /markdown_extensions/toc.py
parent83efb118c1bdcb7d44a1fa6b187eb33bf86f72dd (diff)
downloadmarkdown-e5fcf1bf127567d585f75525a37b0dc852911104.tar.gz
markdown-e5fcf1bf127567d585f75525a37b0dc852911104.tar.bz2
markdown-e5fcf1bf127567d585f75525a37b0dc852911104.zip
Updated toc extension to ensure unique header ids and only set the id on the header, not the anchor. Thanks Jack Miller.
Diffstat (limited to 'markdown_extensions/toc.py')
-rw-r--r--markdown_extensions/toc.py22
1 files changed, 16 insertions, 6 deletions
diff --git a/markdown_extensions/toc.py b/markdown_extensions/toc.py
index 00cf537..cc8c93b 100644
--- a/markdown_extensions/toc.py
+++ b/markdown_extensions/toc.py
@@ -34,6 +34,12 @@ class TocTreeprocessor (markdown.Treeprocessor):
list_stack=[div]
header_rgx = re.compile("[Hh][123456]")
+ # Get a list of id attributes
+ used_ids = []
+ for c in doc.getiterator():
+ if c.attrib.has_key("id"):
+ used_ids.append(c.attrib["id"])
+
for (p, c) in self.iterparent(doc):
if not c.text:
continue
@@ -69,10 +75,17 @@ class TocTreeprocessor (markdown.Treeprocessor):
level = tag_level
# Do not override pre-existing ids
- if c.attrib.has_key("id"):
- id = c.attrib["id"]
- else:
+ if not c.attrib.has_key("id"):
id = self.config["slugify"][0](c.text)
+ if id in used_ids:
+ ctr = 1
+ while "%s_%d" % (id, ctr) in used_ids:
+ ctr += 1
+ id = "%s_%d" % (id, ctr)
+ used_ids.append(id)
+ c.attrib["id"] = id
+ else:
+ id = c.attrib["id"]
# List item link, to be inserted into the toc div
last_li = etree.Element("li")
@@ -83,12 +96,9 @@ class TocTreeprocessor (markdown.Treeprocessor):
if int(self.config["anchorlink"][0]):
anchor = etree.SubElement(c, "a")
anchor.text = c.text
- anchor.attrib["id"] = id
anchor.attrib["href"] = "#" + id
anchor.attrib["class"] = "toclink"
c.text = ""
- else:
- c.attrib["id"] = id
list_stack[-1].append(last_li)