/markdown/extensions/toc.py

https://github.com/Wilfred/Python-Markdown · Python · 157 lines · 107 code · 23 blank · 27 comment · 30 complexity · e6cfd855369aebc98de504ea0afa1a2f MD5 · raw file

  1. """
  2. Table of Contents Extension for Python-Markdown
  3. * * *
  4. (c) 2008 [Jack Miller](http://codezen.org)
  5. Dependencies:
  6. * [Markdown 2.1+](http://www.freewisdom.org/projects/python-markdown/)
  7. """
  8. import markdown
  9. from markdown.util import etree
  10. from markdown.extensions.headerid import slugify, unique, itertext
  11. import re
  12. class TocTreeprocessor(markdown.treeprocessors.Treeprocessor):
  13. # Iterator wrapper to get parent and child all at once
  14. def iterparent(self, root):
  15. for parent in root.getiterator():
  16. for child in parent:
  17. yield parent, child
  18. def run(self, doc):
  19. marker_found = False
  20. div = etree.Element("div")
  21. div.attrib["class"] = "toc"
  22. last_li = None
  23. # Add title to the div
  24. if self.config["title"]:
  25. header = etree.SubElement(div, "span")
  26. header.attrib["class"] = "toctitle"
  27. header.text = self.config["title"]
  28. level = 0
  29. list_stack=[div]
  30. header_rgx = re.compile("[Hh][123456]")
  31. # Get a list of id attributes
  32. used_ids = []
  33. for c in doc.getiterator():
  34. if "id" in c.attrib:
  35. used_ids.append(c.attrib["id"])
  36. for (p, c) in self.iterparent(doc):
  37. text = ''.join(itertext(c)).strip()
  38. if not text:
  39. continue
  40. # To keep the output from screwing up the
  41. # validation by putting a <div> inside of a <p>
  42. # we actually replace the <p> in its entirety.
  43. # We do not allow the marker inside a header as that
  44. # would causes an enless loop of placing a new TOC
  45. # inside previously generated TOC.
  46. if c.text and c.text.strip() == self.config["marker"] and \
  47. not header_rgx.match(c.tag) and c.tag not in ['pre', 'code']:
  48. for i in range(len(p)):
  49. if p[i] == c:
  50. p[i] = div
  51. break
  52. marker_found = True
  53. if header_rgx.match(c.tag):
  54. tag_level = int(c.tag[-1])
  55. while tag_level < level:
  56. list_stack.pop()
  57. level -= 1
  58. if tag_level > level:
  59. if self.config['ordered']:
  60. newlist = etree.Element("ol")
  61. else:
  62. newlist = etree.Element("ul")
  63. if last_li:
  64. last_li.append(newlist)
  65. else:
  66. list_stack[-1].append(newlist)
  67. list_stack.append(newlist)
  68. if level == 0:
  69. level = tag_level
  70. else:
  71. level += 1
  72. # Do not override pre-existing ids
  73. if not "id" in c.attrib:
  74. id = unique(self.config["slugify"](text, '-'), used_ids)
  75. c.attrib["id"] = id
  76. else:
  77. id = c.attrib["id"]
  78. # List item link, to be inserted into the toc div
  79. last_li = etree.Element("li")
  80. link = etree.SubElement(last_li, "a")
  81. link.text = text
  82. link.attrib["href"] = '#' + id
  83. if int(self.config["anchorlink"]):
  84. anchor = etree.Element("a")
  85. anchor.text = c.text
  86. anchor.attrib["href"] = "#" + id
  87. anchor.attrib["class"] = "toclink"
  88. c.text = ""
  89. for elem in c.getchildren():
  90. anchor.append(elem)
  91. c.remove(elem)
  92. c.append(anchor)
  93. list_stack[-1].append(last_li)
  94. if not marker_found:
  95. # searialize and attach to markdown instance.
  96. prettify = self.markdown.treeprocessors.get('prettify')
  97. if prettify: prettify.run(div)
  98. toc = self.markdown.serializer(div)
  99. for pp in self.markdown.postprocessors.values():
  100. toc = pp.run(toc)
  101. self.markdown.toc = toc
  102. class TocExtension(markdown.Extension):
  103. def __init__(self, configs):
  104. self.config = { "marker" : ["[TOC]",
  105. "Text to find and replace with Table of Contents -"
  106. "Defaults to \"[TOC]\""],
  107. "slugify" : [slugify,
  108. "Function to generate anchors based on header text-"
  109. "Defaults to the headerid ext's slugify function."],
  110. "title" : [None,
  111. "Title to insert into TOC <div> - "
  112. "Defaults to None"],
  113. "anchorlink" : [0,
  114. "1 if header should be a self link"
  115. "Defaults to 0"],
  116. "ordered" : [False,
  117. "If true, <ol> tags are used instead of <ul> tags"
  118. "Defaults to False"]}
  119. for key, value in configs:
  120. self.setConfig(key, value)
  121. def extendMarkdown(self, md, md_globals):
  122. tocext = TocTreeprocessor(md)
  123. tocext.config = self.getConfigs()
  124. # Headerid ext is set to '>inline'. With this set to '<prettify',
  125. # it should always come after headerid ext (and honor ids assinged
  126. # by the header id extension) if both are used. Same goes for
  127. # attr_list extension. This must come last because we don't want
  128. # to redefine ids after toc is created. But we do want toc prettified.
  129. md.treeprocessors.add("toc", tocext, "<prettify")
  130. def makeExtension(configs={}):
  131. return TocExtension(configs=configs)