2024-03-04 01:15:23 +08:00
|
|
|
# Python Markdown
|
|
|
|
|
|
|
|
# A Python implementation of John Gruber's Markdown.
|
2022-01-24 12:07:52 +08:00
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
# Documentation: https://python-markdown.github.io/
|
|
|
|
# GitHub: https://github.com/Python-Markdown/markdown/
|
|
|
|
# PyPI: https://pypi.org/project/Markdown/
|
2022-01-24 12:07:52 +08:00
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
# Started by Manfred Stienstra (http://www.dwerg.net/).
|
|
|
|
# Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
|
|
|
|
# Currently maintained by Waylan Limberg (https://github.com/waylan),
|
|
|
|
# Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
|
2022-01-24 12:07:52 +08:00
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
# Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
|
|
|
|
# Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
|
|
|
|
# Copyright 2004 Manfred Stienstra (the original version)
|
2022-01-24 12:07:52 +08:00
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
# License: BSD (see LICENSE.md for details).
|
2022-01-24 12:07:52 +08:00
|
|
|
|
|
|
|
"""
|
2024-03-04 01:15:23 +08:00
|
|
|
Tree processors manipulate the tree created by block processors. They can even create an entirely
|
|
|
|
new `ElementTree` object. This is an excellent place for creating summaries, adding collected
|
|
|
|
references, or last minute adjustments.
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
from __future__ import annotations
|
2022-01-24 12:07:52 +08:00
|
|
|
|
2022-11-08 02:06:49 +08:00
|
|
|
import re
|
2022-01-24 12:07:52 +08:00
|
|
|
import xml.etree.ElementTree as etree
|
2024-03-04 01:15:23 +08:00
|
|
|
from typing import TYPE_CHECKING, Any
|
2018-09-17 08:27:00 +08:00
|
|
|
from . import util
|
|
|
|
from . import inlinepatterns
|
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
if TYPE_CHECKING: # pragma: no cover
|
|
|
|
from markdown import Markdown
|
2018-09-17 08:27:00 +08:00
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
|
|
|
|
def build_treeprocessors(md: Markdown, **kwargs: Any) -> util.Registry[Treeprocessor]:
|
|
|
|
""" Build the default `treeprocessors` for Markdown. """
|
2022-01-24 12:07:52 +08:00
|
|
|
treeprocessors = util.Registry()
|
|
|
|
treeprocessors.register(InlineProcessor(md), 'inline', 20)
|
|
|
|
treeprocessors.register(PrettifyTreeprocessor(md), 'prettify', 10)
|
2022-11-08 02:06:49 +08:00
|
|
|
treeprocessors.register(UnescapeTreeprocessor(md), 'unescape', 0)
|
2018-09-17 08:27:00 +08:00
|
|
|
return treeprocessors
|
|
|
|
|
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
def isString(s: object) -> bool:
|
|
|
|
""" Return `True` if object is a string but not an [`AtomicString`][markdown.util.AtomicString]. """
|
2018-09-17 08:27:00 +08:00
|
|
|
if not isinstance(s, util.AtomicString):
|
2022-01-24 12:07:52 +08:00
|
|
|
return isinstance(s, str)
|
2018-09-17 08:27:00 +08:00
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
|
|
class Treeprocessor(util.Processor):
|
|
|
|
"""
|
2024-03-04 01:15:23 +08:00
|
|
|
`Treeprocessor`s are run on the `ElementTree` object before serialization.
|
2018-09-17 08:27:00 +08:00
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
Each `Treeprocessor` implements a `run` method that takes a pointer to an
|
|
|
|
`Element` and modifies it as necessary.
|
2018-09-17 08:27:00 +08:00
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
`Treeprocessors` must extend `markdown.Treeprocessor`.
|
2018-09-17 08:27:00 +08:00
|
|
|
|
|
|
|
"""
|
2024-03-04 01:15:23 +08:00
|
|
|
def run(self, root: etree.Element) -> etree.Element | None:
|
2018-09-17 08:27:00 +08:00
|
|
|
"""
|
2024-03-04 01:15:23 +08:00
|
|
|
Subclasses of `Treeprocessor` should implement a `run` method, which
|
|
|
|
takes a root `Element`. This method can return another `Element`
|
|
|
|
object, and the existing root `Element` will be replaced, or it can
|
|
|
|
modify the current tree and return `None`.
|
2018-09-17 08:27:00 +08:00
|
|
|
"""
|
|
|
|
pass # pragma: no cover
|
|
|
|
|
|
|
|
|
|
|
|
class InlineProcessor(Treeprocessor):
|
|
|
|
"""
|
2024-03-04 01:15:23 +08:00
|
|
|
A `Treeprocessor` that traverses a tree, applying inline patterns.
|
2018-09-17 08:27:00 +08:00
|
|
|
"""
|
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
def __init__(self, md: Markdown):
|
2018-09-17 08:27:00 +08:00
|
|
|
self.__placeholder_prefix = util.INLINE_PLACEHOLDER_PREFIX
|
|
|
|
self.__placeholder_suffix = util.ETX
|
|
|
|
self.__placeholder_length = 4 + len(self.__placeholder_prefix) \
|
|
|
|
+ len(self.__placeholder_suffix)
|
|
|
|
self.__placeholder_re = util.INLINE_PLACEHOLDER_RE
|
2022-01-24 12:07:52 +08:00
|
|
|
self.md = md
|
2018-09-17 08:27:00 +08:00
|
|
|
self.inlinePatterns = md.inlinePatterns
|
2024-03-04 01:15:23 +08:00
|
|
|
self.ancestors: list[str] = []
|
2018-09-17 08:27:00 +08:00
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
def __makePlaceholder(self, type: str) -> tuple[str, str]:
|
2018-09-17 08:27:00 +08:00
|
|
|
""" Generate a placeholder """
|
|
|
|
id = "%04d" % len(self.stashed_nodes)
|
|
|
|
hash = util.INLINE_PLACEHOLDER % id
|
|
|
|
return hash, id
|
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
def __findPlaceholder(self, data: str, index: int) -> tuple[str | None, int]:
|
2018-09-17 08:27:00 +08:00
|
|
|
"""
|
2024-03-04 01:15:23 +08:00
|
|
|
Extract id from data string, start from index.
|
2018-09-17 08:27:00 +08:00
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
Arguments:
|
|
|
|
data: String.
|
|
|
|
index: Index, from which we start search.
|
2018-09-17 08:27:00 +08:00
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
Returns:
|
|
|
|
Placeholder id and string index, after the found placeholder.
|
2018-09-17 08:27:00 +08:00
|
|
|
|
|
|
|
"""
|
|
|
|
m = self.__placeholder_re.search(data, index)
|
|
|
|
if m:
|
|
|
|
return m.group(1), m.end()
|
|
|
|
else:
|
|
|
|
return None, index + 1
|
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
def __stashNode(self, node: etree.Element | str, type: str) -> str:
|
|
|
|
""" Add node to stash. """
|
2018-09-17 08:27:00 +08:00
|
|
|
placeholder, id = self.__makePlaceholder(type)
|
|
|
|
self.stashed_nodes[id] = node
|
|
|
|
return placeholder
|
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
def __handleInline(self, data: str, patternIndex: int = 0) -> str:
|
2018-09-17 08:27:00 +08:00
|
|
|
"""
|
2024-03-04 01:15:23 +08:00
|
|
|
Process string with inline patterns and replace it with placeholders.
|
2018-09-17 08:27:00 +08:00
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
Arguments:
|
|
|
|
data: A line of Markdown text.
|
|
|
|
patternIndex: The index of the `inlinePattern` to start with.
|
2018-09-17 08:27:00 +08:00
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
Returns:
|
|
|
|
String with placeholders.
|
2018-09-17 08:27:00 +08:00
|
|
|
|
|
|
|
"""
|
|
|
|
if not isinstance(data, util.AtomicString):
|
|
|
|
startIndex = 0
|
2022-01-24 12:07:52 +08:00
|
|
|
count = len(self.inlinePatterns)
|
|
|
|
while patternIndex < count:
|
2018-09-17 08:27:00 +08:00
|
|
|
data, matched, startIndex = self.__applyPattern(
|
2022-01-24 12:07:52 +08:00
|
|
|
self.inlinePatterns[patternIndex], data, patternIndex, startIndex
|
|
|
|
)
|
2018-09-17 08:27:00 +08:00
|
|
|
if not matched:
|
|
|
|
patternIndex += 1
|
|
|
|
return data
|
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
def __processElementText(self, node: etree.Element, subnode: etree.Element, isText: bool = True) -> None:
|
2018-09-17 08:27:00 +08:00
|
|
|
"""
|
2024-03-04 01:15:23 +08:00
|
|
|
Process placeholders in `Element.text` or `Element.tail`
|
|
|
|
of Elements popped from `self.stashed_nodes`.
|
2018-09-17 08:27:00 +08:00
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
Arguments:
|
|
|
|
node: Parent node.
|
|
|
|
subnode: Processing node.
|
|
|
|
isText: Boolean variable, True - it's text, False - it's a tail.
|
2018-09-17 08:27:00 +08:00
|
|
|
|
|
|
|
"""
|
|
|
|
if isText:
|
|
|
|
text = subnode.text
|
|
|
|
subnode.text = None
|
|
|
|
else:
|
|
|
|
text = subnode.tail
|
|
|
|
subnode.tail = None
|
|
|
|
|
|
|
|
childResult = self.__processPlaceholders(text, subnode, isText)
|
|
|
|
|
|
|
|
if not isText and node is not subnode:
|
|
|
|
pos = list(node).index(subnode) + 1
|
|
|
|
else:
|
|
|
|
pos = 0
|
|
|
|
|
|
|
|
childResult.reverse()
|
|
|
|
for newChild in childResult:
|
|
|
|
node.insert(pos, newChild[0])
|
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
def __processPlaceholders(
|
|
|
|
self,
|
|
|
|
data: str | None,
|
|
|
|
parent: etree.Element,
|
|
|
|
isText: bool = True
|
|
|
|
) -> list[tuple[etree.Element, list[str]]]:
|
2018-09-17 08:27:00 +08:00
|
|
|
"""
|
2024-03-04 01:15:23 +08:00
|
|
|
Process string with placeholders and generate `ElementTree` tree.
|
2018-09-17 08:27:00 +08:00
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
Arguments:
|
|
|
|
data: String with placeholders instead of `ElementTree` elements.
|
|
|
|
parent: Element, which contains processing inline data.
|
|
|
|
isText: Boolean variable, True - it's text, False - it's a tail.
|
2018-09-17 08:27:00 +08:00
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
Returns:
|
|
|
|
List with `ElementTree` elements with applied inline patterns.
|
2018-09-17 08:27:00 +08:00
|
|
|
|
|
|
|
"""
|
2024-03-04 01:15:23 +08:00
|
|
|
def linkText(text: str | None) -> None:
|
2018-09-17 08:27:00 +08:00
|
|
|
if text:
|
|
|
|
if result:
|
|
|
|
if result[-1][0].tail:
|
|
|
|
result[-1][0].tail += text
|
|
|
|
else:
|
|
|
|
result[-1][0].tail = text
|
|
|
|
elif not isText:
|
|
|
|
if parent.tail:
|
|
|
|
parent.tail += text
|
|
|
|
else:
|
|
|
|
parent.tail = text
|
|
|
|
else:
|
|
|
|
if parent.text:
|
|
|
|
parent.text += text
|
|
|
|
else:
|
|
|
|
parent.text = text
|
|
|
|
result = []
|
|
|
|
strartIndex = 0
|
|
|
|
while data:
|
|
|
|
index = data.find(self.__placeholder_prefix, strartIndex)
|
|
|
|
if index != -1:
|
|
|
|
id, phEndIndex = self.__findPlaceholder(data, index)
|
|
|
|
|
|
|
|
if id in self.stashed_nodes:
|
|
|
|
node = self.stashed_nodes.get(id)
|
|
|
|
|
|
|
|
if index > 0:
|
|
|
|
text = data[strartIndex:index]
|
|
|
|
linkText(text)
|
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
if not isinstance(node, str): # it's Element
|
2018-09-17 08:27:00 +08:00
|
|
|
for child in [node] + list(node):
|
|
|
|
if child.tail:
|
|
|
|
if child.tail.strip():
|
|
|
|
self.__processElementText(
|
|
|
|
node, child, False
|
|
|
|
)
|
|
|
|
if child.text:
|
|
|
|
if child.text.strip():
|
|
|
|
self.__processElementText(child, child)
|
|
|
|
else: # it's just a string
|
|
|
|
linkText(node)
|
|
|
|
strartIndex = phEndIndex
|
|
|
|
continue
|
|
|
|
|
|
|
|
strartIndex = phEndIndex
|
|
|
|
result.append((node, self.ancestors[:]))
|
|
|
|
|
|
|
|
else: # wrong placeholder
|
|
|
|
end = index + len(self.__placeholder_prefix)
|
|
|
|
linkText(data[strartIndex:end])
|
|
|
|
strartIndex = end
|
|
|
|
else:
|
|
|
|
text = data[strartIndex:]
|
|
|
|
if isinstance(data, util.AtomicString):
|
2024-03-04 01:15:23 +08:00
|
|
|
# We don't want to loose the `AtomicString`
|
2018-09-17 08:27:00 +08:00
|
|
|
text = util.AtomicString(text)
|
|
|
|
linkText(text)
|
|
|
|
data = ""
|
|
|
|
|
|
|
|
return result
|
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
def __applyPattern(
|
|
|
|
self,
|
|
|
|
pattern: inlinepatterns.Pattern,
|
|
|
|
data: str,
|
|
|
|
patternIndex: int,
|
|
|
|
startIndex: int = 0
|
|
|
|
) -> tuple[str, bool, int]:
|
2018-09-17 08:27:00 +08:00
|
|
|
"""
|
|
|
|
Check if the line fits the pattern, create the necessary
|
2024-03-04 01:15:23 +08:00
|
|
|
elements, add it to `stashed_nodes`.
|
2018-09-17 08:27:00 +08:00
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
Arguments:
|
|
|
|
data: The text to be processed.
|
|
|
|
pattern: The pattern to be checked.
|
|
|
|
patternIndex: Index of current pattern.
|
|
|
|
startIndex: String index, from which we start searching.
|
2018-09-17 08:27:00 +08:00
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
Returns:
|
|
|
|
String with placeholders instead of `ElementTree` elements.
|
2018-09-17 08:27:00 +08:00
|
|
|
|
|
|
|
"""
|
2022-01-24 12:07:52 +08:00
|
|
|
new_style = isinstance(pattern, inlinepatterns.InlineProcessor)
|
2018-09-17 08:27:00 +08:00
|
|
|
|
|
|
|
for exclude in pattern.ANCESTOR_EXCLUDES:
|
|
|
|
if exclude.lower() in self.ancestors:
|
|
|
|
return data, False, 0
|
|
|
|
|
2022-01-24 12:07:52 +08:00
|
|
|
if new_style:
|
|
|
|
match = None
|
2024-03-04 01:15:23 +08:00
|
|
|
# Since `handleMatch` may reject our first match,
|
2022-01-24 12:07:52 +08:00
|
|
|
# we iterate over the buffer looking for matches
|
|
|
|
# until we can't find any more.
|
|
|
|
for match in pattern.getCompiledRegExp().finditer(data, startIndex):
|
|
|
|
node, start, end = pattern.handleMatch(match, data)
|
|
|
|
if start is None or end is None:
|
|
|
|
startIndex += match.end(0)
|
|
|
|
match = None
|
|
|
|
continue
|
|
|
|
break
|
|
|
|
else: # pragma: no cover
|
|
|
|
match = pattern.getCompiledRegExp().match(data[startIndex:])
|
|
|
|
leftData = data[:startIndex]
|
2018-09-17 08:27:00 +08:00
|
|
|
|
|
|
|
if not match:
|
|
|
|
return data, False, 0
|
|
|
|
|
2022-01-24 12:07:52 +08:00
|
|
|
if not new_style: # pragma: no cover
|
|
|
|
node = pattern.handleMatch(match)
|
|
|
|
start = match.start(0)
|
|
|
|
end = match.end(0)
|
2018-09-17 08:27:00 +08:00
|
|
|
|
|
|
|
if node is None:
|
2022-01-24 12:07:52 +08:00
|
|
|
return data, True, end
|
2018-09-17 08:27:00 +08:00
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
if not isinstance(node, str):
|
2018-09-17 08:27:00 +08:00
|
|
|
if not isinstance(node.text, util.AtomicString):
|
|
|
|
# We need to process current node too
|
|
|
|
for child in [node] + list(node):
|
|
|
|
if not isString(node):
|
|
|
|
if child.text:
|
|
|
|
self.ancestors.append(child.tag.lower())
|
|
|
|
child.text = self.__handleInline(
|
|
|
|
child.text, patternIndex + 1
|
|
|
|
)
|
|
|
|
self.ancestors.pop()
|
|
|
|
if child.tail:
|
|
|
|
child.tail = self.__handleInline(
|
|
|
|
child.tail, patternIndex
|
|
|
|
)
|
|
|
|
|
|
|
|
placeholder = self.__stashNode(node, pattern.type())
|
|
|
|
|
2022-01-24 12:07:52 +08:00
|
|
|
if new_style:
|
|
|
|
return "{}{}{}".format(data[:start],
|
|
|
|
placeholder, data[end:]), True, 0
|
|
|
|
else: # pragma: no cover
|
|
|
|
return "{}{}{}{}".format(leftData,
|
|
|
|
match.group(1),
|
|
|
|
placeholder, match.groups()[-1]), True, 0
|
2018-09-17 08:27:00 +08:00
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
def __build_ancestors(self, parent: etree.Element | None, parents: list[str]) -> None:
|
2018-09-17 08:27:00 +08:00
|
|
|
"""Build the ancestor list."""
|
|
|
|
ancestors = []
|
|
|
|
while parent is not None:
|
|
|
|
if parent is not None:
|
|
|
|
ancestors.append(parent.tag.lower())
|
|
|
|
parent = self.parent_map.get(parent)
|
|
|
|
ancestors.reverse()
|
|
|
|
parents.extend(ancestors)
|
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
def run(self, tree: etree.Element, ancestors: list[str] | None = None) -> etree.Element:
|
2018-09-17 08:27:00 +08:00
|
|
|
"""Apply inline patterns to a parsed Markdown tree.
|
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
Iterate over `Element`, find elements with inline tag, apply inline
|
|
|
|
patterns and append newly created Elements to tree. To avoid further
|
|
|
|
processing of string with inline patterns, instead of normal string,
|
|
|
|
use subclass [`AtomicString`][markdown.util.AtomicString]:
|
2018-09-17 08:27:00 +08:00
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
node.text = markdown.util.AtomicString("This will not be processed.")
|
2018-09-17 08:27:00 +08:00
|
|
|
|
|
|
|
Arguments:
|
2024-03-04 01:15:23 +08:00
|
|
|
tree: `Element` object, representing Markdown tree.
|
|
|
|
ancestors: List of parent tag names that precede the tree node (if needed).
|
2018-09-17 08:27:00 +08:00
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
Returns:
|
|
|
|
An element tree object with applied inline patterns.
|
2018-09-17 08:27:00 +08:00
|
|
|
|
|
|
|
"""
|
2024-03-04 01:15:23 +08:00
|
|
|
self.stashed_nodes: dict[str, etree.Element | str] = {}
|
2018-09-17 08:27:00 +08:00
|
|
|
|
|
|
|
# Ensure a valid parent list, but copy passed in lists
|
|
|
|
# to ensure we don't have the user accidentally change it on us.
|
|
|
|
tree_parents = [] if ancestors is None else ancestors[:]
|
|
|
|
|
2022-01-24 12:07:52 +08:00
|
|
|
self.parent_map = {c: p for p in tree.iter() for c in p}
|
2018-09-17 08:27:00 +08:00
|
|
|
stack = [(tree, tree_parents)]
|
|
|
|
|
|
|
|
while stack:
|
|
|
|
currElement, parents = stack.pop()
|
|
|
|
|
|
|
|
self.ancestors = parents
|
|
|
|
self.__build_ancestors(currElement, self.ancestors)
|
|
|
|
|
|
|
|
insertQueue = []
|
|
|
|
for child in currElement:
|
|
|
|
if child.text and not isinstance(
|
|
|
|
child.text, util.AtomicString
|
|
|
|
):
|
|
|
|
self.ancestors.append(child.tag.lower())
|
|
|
|
text = child.text
|
|
|
|
child.text = None
|
|
|
|
lst = self.__processPlaceholders(
|
|
|
|
self.__handleInline(text), child
|
|
|
|
)
|
2022-01-24 12:07:52 +08:00
|
|
|
for item in lst:
|
|
|
|
self.parent_map[item[0]] = child
|
2018-09-17 08:27:00 +08:00
|
|
|
stack += lst
|
|
|
|
insertQueue.append((child, lst))
|
|
|
|
self.ancestors.pop()
|
|
|
|
if child.tail:
|
|
|
|
tail = self.__handleInline(child.tail)
|
2022-01-24 12:07:52 +08:00
|
|
|
dumby = etree.Element('d')
|
2018-09-17 08:27:00 +08:00
|
|
|
child.tail = None
|
|
|
|
tailResult = self.__processPlaceholders(tail, dumby, False)
|
|
|
|
if dumby.tail:
|
|
|
|
child.tail = dumby.tail
|
|
|
|
pos = list(currElement).index(child) + 1
|
|
|
|
tailResult.reverse()
|
|
|
|
for newChild in tailResult:
|
|
|
|
self.parent_map[newChild[0]] = currElement
|
|
|
|
currElement.insert(pos, newChild[0])
|
|
|
|
if len(child):
|
|
|
|
self.parent_map[child] = currElement
|
|
|
|
stack.append((child, self.ancestors[:]))
|
|
|
|
|
|
|
|
for element, lst in insertQueue:
|
2022-01-24 12:07:52 +08:00
|
|
|
for i, obj in enumerate(lst):
|
2018-09-17 08:27:00 +08:00
|
|
|
newChild = obj[0]
|
|
|
|
element.insert(i, newChild)
|
|
|
|
return tree
|
|
|
|
|
|
|
|
|
|
|
|
class PrettifyTreeprocessor(Treeprocessor):
|
2024-03-04 01:15:23 +08:00
|
|
|
""" Add line breaks to the html document. """
|
2018-09-17 08:27:00 +08:00
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
def _prettifyETree(self, elem: etree.Element) -> None:
|
|
|
|
""" Recursively add line breaks to `ElementTree` children. """
|
2018-09-17 08:27:00 +08:00
|
|
|
|
|
|
|
i = "\n"
|
2022-01-24 12:07:52 +08:00
|
|
|
if self.md.is_block_level(elem.tag) and elem.tag not in ['code', 'pre']:
|
2018-09-17 08:27:00 +08:00
|
|
|
if (not elem.text or not elem.text.strip()) \
|
2022-01-24 12:07:52 +08:00
|
|
|
and len(elem) and self.md.is_block_level(elem[0].tag):
|
2018-09-17 08:27:00 +08:00
|
|
|
elem.text = i
|
|
|
|
for e in elem:
|
2022-01-24 12:07:52 +08:00
|
|
|
if self.md.is_block_level(e.tag):
|
2018-09-17 08:27:00 +08:00
|
|
|
self._prettifyETree(e)
|
|
|
|
if not elem.tail or not elem.tail.strip():
|
|
|
|
elem.tail = i
|
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
def run(self, root: etree.Element) -> None:
|
|
|
|
""" Add line breaks to `Element` object and its children. """
|
2018-09-17 08:27:00 +08:00
|
|
|
|
|
|
|
self._prettifyETree(root)
|
2024-03-04 01:15:23 +08:00
|
|
|
# Do `<br />`'s separately as they are often in the middle of
|
|
|
|
# inline content and missed by `_prettifyETree`.
|
2018-09-17 08:27:00 +08:00
|
|
|
brs = root.iter('br')
|
|
|
|
for br in brs:
|
|
|
|
if not br.tail or not br.tail.strip():
|
|
|
|
br.tail = '\n'
|
|
|
|
else:
|
|
|
|
br.tail = '\n%s' % br.tail
|
|
|
|
# Clean up extra empty lines at end of code blocks.
|
|
|
|
pres = root.iter('pre')
|
|
|
|
for pre in pres:
|
|
|
|
if len(pre) and pre[0].tag == 'code':
|
2022-11-08 02:06:49 +08:00
|
|
|
code = pre[0]
|
|
|
|
# Only prettify code containing text only
|
|
|
|
if not len(code) and code.text is not None:
|
|
|
|
code.text = util.AtomicString(code.text.rstrip() + '\n')
|
|
|
|
|
|
|
|
|
|
|
|
class UnescapeTreeprocessor(Treeprocessor):
|
|
|
|
""" Restore escaped chars """
|
|
|
|
|
|
|
|
RE = re.compile(r'{}(\d+){}'.format(util.STX, util.ETX))
|
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
def _unescape(self, m: re.Match[str]) -> str:
|
2022-11-08 02:06:49 +08:00
|
|
|
return chr(int(m.group(1)))
|
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
def unescape(self, text: str) -> str:
|
2022-11-08 02:06:49 +08:00
|
|
|
return self.RE.sub(self._unescape, text)
|
|
|
|
|
2024-03-04 01:15:23 +08:00
|
|
|
def run(self, root: etree.Element) -> None:
|
2022-11-08 02:06:49 +08:00
|
|
|
""" Loop over all elements and unescape all text. """
|
|
|
|
for elem in root.iter():
|
|
|
|
# Unescape text content
|
|
|
|
if elem.text and not elem.tag == 'code':
|
|
|
|
elem.text = self.unescape(elem.text)
|
|
|
|
# Unescape tail content
|
|
|
|
if elem.tail:
|
|
|
|
elem.tail = self.unescape(elem.tail)
|
|
|
|
# Unescape attribute values
|
|
|
|
for key, value in elem.items():
|
|
|
|
elem.set(key, self.unescape(value))
|