MCPcopy Create free account
hub / github.com/Python-Markdown/markdown / run

Method run

markdown/extensions/toc.py:387–444  ·  view source on GitHub ↗
(self, doc: etree.Element)

Source from the content-addressed store, hash-verified

385 return div
386
387 def run(self, doc: etree.Element) -> None:
388 # Get a list of id attributes
389 used_ids = set()
390 for el in doc.iter():
391 if "id" in el.attrib:
392 used_ids.add(el.attrib["id"])
393 id_counters: dict[str, int] = {}
394
395 toc_tokens = []
396 for el in doc.iter():
397 if isinstance(el.tag, str) and self.header_rgx.match(el.tag):
398 self.set_level(el)
399 innerhtml = render_inner_html(remove_fnrefs(el), self.md)
400 name = strip_tags(innerhtml)
401
402 # Do not override pre-existing ids
403 if not el.attrib.get("id"):
404 # The `attr_list` extension writes bare attributes with a
405 # value of None. A valueless id is no id at all, so a slug
406 # is generated for it like for any other id-less heading.
407 el.attrib["id"] = unique(self.slugify(html.unescape(name), self.sep), used_ids, id_counters)
408
409 data_toc_label = ''
410 if 'data-toc-label' in el.attrib:
411 # Remove the data-toc-label attribute as it is no longer needed
412 label = el.attrib.pop('data-toc-label')
413 # The `attr_list` extension writes bare attributes with a value of
414 # None. A valueless label is treated like a missing one.
415 if label is not None:
416 data_toc_label = run_postprocessors(unescape(label), self.md)
417 # Overwrite name with sanitized value of `data-toc-label`.
418 name = escape_cdata(strip_tags(data_toc_label))
419
420 if int(el.tag[-1]) >= self.toc_top and int(el.tag[-1]) <= self.toc_bottom:
421 toc_tokens.append({
422 'level': int(el.tag[-1]),
423 'id': unescape(el.attrib["id"]),
424 'name': name,
425 'html': innerhtml,
426 'data-toc-label': data_toc_label
427 })
428
429 if self.use_anchors:
430 self.add_anchor(el, el.attrib["id"])
431 if self.use_permalinks not in [False, None]:
432 self.add_permalink(el, el.attrib["id"])
433
434 toc_tokens = nest_toc_tokens(toc_tokens)
435 div = self.build_toc_div(toc_tokens)
436 if self.marker:
437 self.replace_marker(doc, div)
438
439 # serialize and attach to markdown instance.
440 toc = self.md.serializer(div)
441 for pp in self.md.postprocessors:
442 toc = pp.run(toc)
443 self.md.toc_tokens = toc_tokens
444 self.md.toc = toc

Callers 2

run_postprocessorsFunction · 0.45
build_toc_divMethod · 0.45

Calls 15

set_levelMethod · 0.95
add_anchorMethod · 0.95
add_permalinkMethod · 0.95
build_toc_divMethod · 0.95
replace_markerMethod · 0.95
render_inner_htmlFunction · 0.85
remove_fnrefsFunction · 0.85
strip_tagsFunction · 0.85
uniqueFunction · 0.85
run_postprocessorsFunction · 0.85
unescapeFunction · 0.85
escape_cdataFunction · 0.85

Tested by

no test coverage detected