/Quicksilver/Tools/python-support/markdown/extensions/toc.py

https://github.com/lgarron/Quicksilver · Python · 154 lines · 104 code · 22 blank · 28 comment · 30 complexity · 2b0f9d8bceb26833f3ea411e1577b0d5 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://packages.python.org/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. try:
  55. tag_level = int(c.tag[-1])
  56. while tag_level < level:
  57. list_stack.pop()
  58. level -= 1
  59. if tag_level > level:
  60. newlist = etree.Element("ul")
  61. if last_li:
  62. last_li.append(newlist)
  63. else:
  64. list_stack[-1].append(newlist)
  65. list_stack.append(newlist)
  66. if level == 0:
  67. level = tag_level
  68. else:
  69. level += 1
  70. # Do not override pre-existing ids
  71. if not "id" in c.attrib:
  72. id = unique(self.config["slugify"](text, '-'), used_ids)
  73. c.attrib["id"] = id
  74. else:
  75. id = c.attrib["id"]
  76. # List item link, to be inserted into the toc div
  77. last_li = etree.Element("li")
  78. link = etree.SubElement(last_li, "a")
  79. link.text = text
  80. link.attrib["href"] = '#' + id
  81. if self.config["anchorlink"] in [1, '1', True, 'True', 'true']:
  82. anchor = etree.Element("a")
  83. anchor.text = c.text
  84. anchor.attrib["href"] = "#" + id
  85. anchor.attrib["class"] = "toclink"
  86. c.text = ""
  87. for elem in c.getchildren():
  88. anchor.append(elem)
  89. c.remove(elem)
  90. c.append(anchor)
  91. list_stack[-1].append(last_li)
  92. except IndexError:
  93. # We have bad ordering of headers. Just move on.
  94. pass
  95. if not marker_found:
  96. # searialize and attach to markdown instance.
  97. prettify = self.markdown.treeprocessors.get('prettify')
  98. if prettify: prettify.run(div)
  99. toc = self.markdown.serializer(div)
  100. for pp in self.markdown.postprocessors.values():
  101. toc = pp.run(toc)
  102. self.markdown.toc = toc
  103. class TocExtension(markdown.Extension):
  104. def __init__(self, configs):
  105. self.config = { "marker" : ["[TOC]",
  106. "Text to find and replace with Table of Contents -"
  107. "Defaults to \"[TOC]\""],
  108. "slugify" : [slugify,
  109. "Function to generate anchors based on header text-"
  110. "Defaults to the headerid ext's slugify function."],
  111. "title" : [None,
  112. "Title to insert into TOC <div> - "
  113. "Defaults to None"],
  114. "anchorlink" : [0,
  115. "1 if header should be a self link"
  116. "Defaults to 0"]}
  117. for key, value in configs:
  118. self.setConfig(key, value)
  119. def extendMarkdown(self, md, md_globals):
  120. tocext = TocTreeprocessor(md)
  121. tocext.config = self.getConfigs()
  122. # Headerid ext is set to '>inline'. With this set to '<prettify',
  123. # it should always come after headerid ext (and honor ids assinged
  124. # by the header id extension) if both are used. Same goes for
  125. # attr_list extension. This must come last because we don't want
  126. # to redefine ids after toc is created. But we do want toc prettified.
  127. md.treeprocessors.add("toc", tocext, "<prettify")
  128. def makeExtension(configs={}):
  129. return TocExtension(configs=configs)