| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import copy |
| 4 |
from typing import TYPE_CHECKING, Callable |
| 5 |
|
| 6 |
import markdown |
| 7 |
import markdown.treeprocessors |
| 8 |
|
| 9 |
if TYPE_CHECKING: |
| 10 |
from xml.etree import ElementTree as etree |
| 11 |
|
| 12 |
# TODO: This will become unnecessary after min-versions have Markdown >=3.4 |
| 13 |
_unescape: Callable[[str], str] |
| 14 |
try: |
| 15 |
_unescape = markdown.treeprocessors.UnescapeTreeprocessor().unescape |
| 16 |
except AttributeError: |
| 17 |
_unescape = lambda s: s |
| 18 |
|
| 19 |
# TODO: Most of this file will become unnecessary after https://github.com/Python-Markdown/markdown/pull/1441 |
| 20 |
|
| 21 |
|
| 22 |
def get_heading_text(el: etree.Element, md: markdown.Markdown) -> str: |
| 23 |
el = copy.deepcopy(el) |
| 24 |
_remove_anchorlink(el) |
| 25 |
_remove_fnrefs(el) |
| 26 |
_extract_alt_texts(el) |
| 27 |
return _strip_tags(_render_inner_html(el, md)) |
| 28 |
|
| 29 |
|
| 30 |
def _strip_tags(text: str) -> str: |
| 31 |
"""Strip HTML tags and return plain text. Note: HTML entities are unaffected.""" |
| 32 |
# A comment could contain a tag, so strip comments first |
| 33 |
while (start := text.find('<!--')) != -1 and (end := text.find('-->', start)) != -1: |
| 34 |
text = text[:start] + text[end + 3 :] |
| 35 |
|
| 36 |
while (start := text.find('<')) != -1 and (end := text.find('>', start)) != -1: |
| 37 |
text = text[:start] + text[end + 1 :] |
| 38 |
|
| 39 |
# Collapse whitespace |
| 40 |
text = ' '.join(text.split()) |
| 41 |
return text |
| 42 |
|
| 43 |
|
| 44 |
def _render_inner_html(el: etree.Element, md: markdown.Markdown) -> str: |
| 45 |
# The `UnescapeTreeprocessor` runs after `toc` extension so run here. |
| 46 |
text = md.serializer(el) |
| 47 |
text = _unescape(text) |
| 48 |
|
| 49 |
# Strip parent tag |
| 50 |
start = text.index('>') + 1 |
| 51 |
end = text.rindex('<') |
| 52 |
text = text[start:end].strip() |
| 53 |
|
| 54 |
for pp in md.postprocessors: |
| 55 |
text = pp.run(text) |
| 56 |
return text |
| 57 |
|
| 58 |
|
| 59 |
def _remove_anchorlink(el: etree.Element) -> None: |
| 60 |
"""Drop anchorlink from the element, if present.""" |
| 61 |
if len(el) > 0 and el[-1].tag == 'a' and el[-1].get('class') == 'headerlink': |
| 62 |
del el[-1] |
| 63 |
|
| 64 |
|
| 65 |
def _remove_fnrefs(root: etree.Element) -> None: |
| 66 |
"""Remove footnote references from the element, if any are present.""" |
| 67 |
for parent in root.findall('.//sup[@id]/..'): |
| 68 |
_replace_elements_with_text(parent, _predicate_for_fnrefs) |
| 69 |
|
| 70 |
|
| 71 |
def _predicate_for_fnrefs(el: etree.Element) -> str | None: |
| 72 |
if el.tag == 'sup' and el.get('id', '').startswith('fnref'): |
| 73 |
return '' |
| 74 |
return None |
| 75 |
|
| 76 |
|
| 77 |
def _extract_alt_texts(root: etree.Element) -> None: |
| 78 |
"""For images that have an `alt` attribute, replace them with this content.""" |
| 79 |
for parent in root.findall('.//img[@alt]/..'): |
| 80 |
_replace_elements_with_text(parent, _predicate_for_alt_texts) |
| 81 |
|
| 82 |
|
| 83 |
def _predicate_for_alt_texts(el: etree.Element) -> str | None: |
| 84 |
if el.tag == 'img' and (alt := el.get('alt')): |
| 85 |
return alt |
| 86 |
return None |
| 87 |
|
| 88 |
|
| 89 |
def _replace_elements_with_text( |
| 90 |
parent: etree.Element, predicate: Callable[[etree.Element], str | None] |
| 91 |
) -> None: |
| 92 |
"""For each child element, if matched, replace it with the text returned from the predicate.""" |
| 93 |
carry_text = "" |
| 94 |
for child in reversed(parent): # Reversed for the ability to mutate during iteration. |
| 95 |
# Remove matching elements but carry any `tail` text to preceding elements. |
| 96 |
new_text = predicate(child) |
| 97 |
if new_text is not None: |
| 98 |
carry_text = new_text + (child.tail or "") + carry_text |
| 99 |
parent.remove(child) |
| 100 |
elif carry_text: |
| 101 |
child.tail = (child.tail or "") + carry_text |
| 102 |
carry_text = "" |
| 103 |
if carry_text: |
| 104 |
parent.text = (parent.text or "") + carry_text |