toc.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. """
  2. Table of Contents Extension for Python-Markdown
  3. ===============================================
  4. See <https://Python-Markdown.github.io/extensions/toc>
  5. for documentation.
  6. Oringinal code Copyright 2008 [Jack Miller](https://codezen.org/)
  7. All changes Copyright 2008-2014 The Python Markdown Project
  8. License: [BSD](https://opensource.org/licenses/bsd-license.php)
  9. """
  10. from . import Extension
  11. from ..treeprocessors import Treeprocessor
  12. from ..util import code_escape, parseBoolValue, AMP_SUBSTITUTE, HTML_PLACEHOLDER_RE, AtomicString
  13. from ..postprocessors import UnescapePostprocessor
  14. import re
  15. import html
  16. import unicodedata
  17. import xml.etree.ElementTree as etree
  18. def slugify(value, separator):
  19. """ Slugify a string, to make it URL friendly. """
  20. value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')
  21. value = re.sub(r'[^\w\s-]', '', value.decode('ascii')).strip().lower()
  22. return re.sub(r'[%s\s]+' % separator, separator, value)
  23. IDCOUNT_RE = re.compile(r'^(.*)_([0-9]+)$')
  24. def unique(id, ids):
  25. """ Ensure id is unique in set of ids. Append '_1', '_2'... if not """
  26. while id in ids or not id:
  27. m = IDCOUNT_RE.match(id)
  28. if m:
  29. id = '%s_%d' % (m.group(1), int(m.group(2))+1)
  30. else:
  31. id = '%s_%d' % (id, 1)
  32. ids.add(id)
  33. return id
  34. def get_name(el):
  35. """Get title name."""
  36. text = []
  37. for c in el.itertext():
  38. if isinstance(c, AtomicString):
  39. text.append(html.unescape(c))
  40. else:
  41. text.append(c)
  42. return ''.join(text).strip()
  43. def stashedHTML2text(text, md, strip_entities=True):
  44. """ Extract raw HTML from stash, reduce to plain text and swap with placeholder. """
  45. def _html_sub(m):
  46. """ Substitute raw html with plain text. """
  47. try:
  48. raw = md.htmlStash.rawHtmlBlocks[int(m.group(1))]
  49. except (IndexError, TypeError): # pragma: no cover
  50. return m.group(0)
  51. # Strip out tags and/or entities - leaving text
  52. res = re.sub(r'(<[^>]+>)', '', raw)
  53. if strip_entities:
  54. res = re.sub(r'(&[\#a-zA-Z0-9]+;)', '', res)
  55. return res
  56. return HTML_PLACEHOLDER_RE.sub(_html_sub, text)
  57. def unescape(text):
  58. """ Unescape escaped text. """
  59. c = UnescapePostprocessor()
  60. return c.run(text)
  61. def nest_toc_tokens(toc_list):
  62. """Given an unsorted list with errors and skips, return a nested one.
  63. [{'level': 1}, {'level': 2}]
  64. =>
  65. [{'level': 1, 'children': [{'level': 2, 'children': []}]}]
  66. A wrong list is also converted:
  67. [{'level': 2}, {'level': 1}]
  68. =>
  69. [{'level': 2, 'children': []}, {'level': 1, 'children': []}]
  70. """
  71. ordered_list = []
  72. if len(toc_list):
  73. # Initialize everything by processing the first entry
  74. last = toc_list.pop(0)
  75. last['children'] = []
  76. levels = [last['level']]
  77. ordered_list.append(last)
  78. parents = []
  79. # Walk the rest nesting the entries properly
  80. while toc_list:
  81. t = toc_list.pop(0)
  82. current_level = t['level']
  83. t['children'] = []
  84. # Reduce depth if current level < last item's level
  85. if current_level < levels[-1]:
  86. # Pop last level since we know we are less than it
  87. levels.pop()
  88. # Pop parents and levels we are less than or equal to
  89. to_pop = 0
  90. for p in reversed(parents):
  91. if current_level <= p['level']:
  92. to_pop += 1
  93. else: # pragma: no cover
  94. break
  95. if to_pop:
  96. levels = levels[:-to_pop]
  97. parents = parents[:-to_pop]
  98. # Note current level as last
  99. levels.append(current_level)
  100. # Level is the same, so append to
  101. # the current parent (if available)
  102. if current_level == levels[-1]:
  103. (parents[-1]['children'] if parents
  104. else ordered_list).append(t)
  105. # Current level is > last item's level,
  106. # So make last item a parent and append current as child
  107. else:
  108. last['children'].append(t)
  109. parents.append(last)
  110. levels.append(current_level)
  111. last = t
  112. return ordered_list
  113. class TocTreeprocessor(Treeprocessor):
  114. def __init__(self, md, config):
  115. super().__init__(md)
  116. self.marker = config["marker"]
  117. self.title = config["title"]
  118. self.base_level = int(config["baselevel"]) - 1
  119. self.slugify = config["slugify"]
  120. self.sep = config["separator"]
  121. self.use_anchors = parseBoolValue(config["anchorlink"])
  122. self.anchorlink_class = config["anchorlink_class"]
  123. self.use_permalinks = parseBoolValue(config["permalink"], False)
  124. if self.use_permalinks is None:
  125. self.use_permalinks = config["permalink"]
  126. self.permalink_class = config["permalink_class"]
  127. self.permalink_title = config["permalink_title"]
  128. self.header_rgx = re.compile("[Hh][123456]")
  129. if isinstance(config["toc_depth"], str) and '-' in config["toc_depth"]:
  130. self.toc_top, self.toc_bottom = [int(x) for x in config["toc_depth"].split('-')]
  131. else:
  132. self.toc_top = 1
  133. self.toc_bottom = int(config["toc_depth"])
  134. def iterparent(self, node):
  135. ''' Iterator wrapper to get allowed parent and child all at once. '''
  136. # We do not allow the marker inside a header as that
  137. # would causes an enless loop of placing a new TOC
  138. # inside previously generated TOC.
  139. for child in node:
  140. if not self.header_rgx.match(child.tag) and child.tag not in ['pre', 'code']:
  141. yield node, child
  142. yield from self.iterparent(child)
  143. def replace_marker(self, root, elem):
  144. ''' Replace marker with elem. '''
  145. for (p, c) in self.iterparent(root):
  146. text = ''.join(c.itertext()).strip()
  147. if not text:
  148. continue
  149. # To keep the output from screwing up the
  150. # validation by putting a <div> inside of a <p>
  151. # we actually replace the <p> in its entirety.
  152. if c.text and c.text.strip() == self.marker:
  153. for i in range(len(p)):
  154. if p[i] == c:
  155. p[i] = elem
  156. break
  157. def set_level(self, elem):
  158. ''' Adjust header level according to base level. '''
  159. level = int(elem.tag[-1]) + self.base_level
  160. if level > 6:
  161. level = 6
  162. elem.tag = 'h%d' % level
  163. def add_anchor(self, c, elem_id): # @ReservedAssignment
  164. anchor = etree.Element("a")
  165. anchor.text = c.text
  166. anchor.attrib["href"] = "#" + elem_id
  167. anchor.attrib["class"] = self.anchorlink_class
  168. c.text = ""
  169. for elem in c:
  170. anchor.append(elem)
  171. while len(c):
  172. c.remove(c[0])
  173. c.append(anchor)
  174. def add_permalink(self, c, elem_id):
  175. permalink = etree.Element("a")
  176. permalink.text = ("%spara;" % AMP_SUBSTITUTE
  177. if self.use_permalinks is True
  178. else self.use_permalinks)
  179. permalink.attrib["href"] = "#" + elem_id
  180. permalink.attrib["class"] = self.permalink_class
  181. if self.permalink_title:
  182. permalink.attrib["title"] = self.permalink_title
  183. c.append(permalink)
  184. def build_toc_div(self, toc_list):
  185. """ Return a string div given a toc list. """
  186. div = etree.Element("div")
  187. div.attrib["class"] = "toc"
  188. # Add title to the div
  189. if self.title:
  190. header = etree.SubElement(div, "span")
  191. header.attrib["class"] = "toctitle"
  192. header.text = self.title
  193. def build_etree_ul(toc_list, parent):
  194. ul = etree.SubElement(parent, "ul")
  195. for item in toc_list:
  196. # List item link, to be inserted into the toc div
  197. li = etree.SubElement(ul, "li")
  198. link = etree.SubElement(li, "a")
  199. link.text = item.get('name', '')
  200. link.attrib["href"] = '#' + item.get('id', '')
  201. if item['children']:
  202. build_etree_ul(item['children'], li)
  203. return ul
  204. build_etree_ul(toc_list, div)
  205. if 'prettify' in self.md.treeprocessors:
  206. self.md.treeprocessors['prettify'].run(div)
  207. return div
  208. def run(self, doc):
  209. # Get a list of id attributes
  210. used_ids = set()
  211. for el in doc.iter():
  212. if "id" in el.attrib:
  213. used_ids.add(el.attrib["id"])
  214. toc_tokens = []
  215. for el in doc.iter():
  216. if isinstance(el.tag, str) and self.header_rgx.match(el.tag):
  217. self.set_level(el)
  218. if int(el.tag[-1]) < self.toc_top or int(el.tag[-1]) > self.toc_bottom:
  219. continue
  220. text = get_name(el)
  221. # Do not override pre-existing ids
  222. if "id" not in el.attrib:
  223. innertext = unescape(stashedHTML2text(text, self.md))
  224. el.attrib["id"] = unique(self.slugify(innertext, self.sep), used_ids)
  225. toc_tokens.append({
  226. 'level': int(el.tag[-1]),
  227. 'id': el.attrib["id"],
  228. 'name': unescape(stashedHTML2text(
  229. code_escape(el.attrib.get('data-toc-label', text)),
  230. self.md, strip_entities=False
  231. ))
  232. })
  233. # Remove the data-toc-label attribute as it is no longer needed
  234. if 'data-toc-label' in el.attrib:
  235. del el.attrib['data-toc-label']
  236. if self.use_anchors:
  237. self.add_anchor(el, el.attrib["id"])
  238. if self.use_permalinks not in [False, None]:
  239. self.add_permalink(el, el.attrib["id"])
  240. toc_tokens = nest_toc_tokens(toc_tokens)
  241. div = self.build_toc_div(toc_tokens)
  242. if self.marker:
  243. self.replace_marker(doc, div)
  244. # serialize and attach to markdown instance.
  245. toc = self.md.serializer(div)
  246. for pp in self.md.postprocessors:
  247. toc = pp.run(toc)
  248. self.md.toc_tokens = toc_tokens
  249. self.md.toc = toc
  250. class TocExtension(Extension):
  251. TreeProcessorClass = TocTreeprocessor
  252. def __init__(self, **kwargs):
  253. self.config = {
  254. "marker": ['[TOC]',
  255. 'Text to find and replace with Table of Contents - '
  256. 'Set to an empty string to disable. Defaults to "[TOC]"'],
  257. "title": ["",
  258. "Title to insert into TOC <div> - "
  259. "Defaults to an empty string"],
  260. "anchorlink": [False,
  261. "True if header should be a self link - "
  262. "Defaults to False"],
  263. "anchorlink_class": ['toclink',
  264. 'CSS class(es) used for the link. '
  265. 'Defaults to "toclink"'],
  266. "permalink": [0,
  267. "True or link text if a Sphinx-style permalink should "
  268. "be added - Defaults to False"],
  269. "permalink_class": ['headerlink',
  270. 'CSS class(es) used for the link. '
  271. 'Defaults to "headerlink"'],
  272. "permalink_title": ["Permanent link",
  273. "Title attribute of the permalink - "
  274. "Defaults to 'Permanent link'"],
  275. "baselevel": ['1', 'Base level for headers.'],
  276. "slugify": [slugify,
  277. "Function to generate anchors based on header text - "
  278. "Defaults to the headerid ext's slugify function."],
  279. 'separator': ['-', 'Word separator. Defaults to "-".'],
  280. "toc_depth": [6,
  281. 'Define the range of section levels to include in'
  282. 'the Table of Contents. A single integer (b) defines'
  283. 'the bottom section level (<h1>..<hb>) only.'
  284. 'A string consisting of two digits separated by a hyphen'
  285. 'in between ("2-5"), define the top (t) and the'
  286. 'bottom (b) (<ht>..<hb>). Defaults to `6` (bottom).'],
  287. }
  288. super().__init__(**kwargs)
  289. def extendMarkdown(self, md):
  290. md.registerExtension(self)
  291. self.md = md
  292. self.reset()
  293. tocext = self.TreeProcessorClass(md, self.getConfigs())
  294. # Headerid ext is set to '>prettify'. With this set to '_end',
  295. # it should always come after headerid ext (and honor ids assinged
  296. # by the header id extension) if both are used. Same goes for
  297. # attr_list extension. This must come last because we don't want
  298. # to redefine ids after toc is created. But we do want toc prettified.
  299. md.treeprocessors.register(tocext, 'toc', 5)
  300. def reset(self):
  301. self.md.toc = ''
  302. self.md.toc_tokens = []
  303. def makeExtension(**kwargs): # pragma: no cover
  304. return TocExtension(**kwargs)