From e5fcf1bf127567d585f75525a37b0dc852911104 Mon Sep 17 00:00:00 2001 From: Jack Miller Date: Tue, 28 Oct 2008 22:33:16 -0400 Subject: Updated toc extension to ensure unique header ids and only set the id on the header, not the anchor. Thanks Jack Miller. --- markdown_extensions/toc.py | 22 ++++++++++++++++------ 1 file 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) -- cgit v1.2.3