Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ See the [Contributing Guide](contributing.md) for details.

## Unreleased

### Changed

* Cache inline pattern metadata per `InlineProcessor.run()` call and use a
`collections.deque` queue instead of `list.pop(0)` during inline tree
traversal (#1730).

### Fixed

* Footnote definitions are no longer recognized within a footnote definition,
Expand Down
72 changes: 55 additions & 17 deletions markdown/treeprocessors.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@

from __future__ import annotations

from collections import deque
import re
import xml.etree.ElementTree as etree
from typing import TYPE_CHECKING, Any
Expand Down Expand Up @@ -86,6 +87,9 @@ def __init__(self, md: Markdown):
self.md = md
self.inlinePatterns = md.inlinePatterns
self.ancestors: list[str] = []
self._patterns: list[
tuple[inlinepatterns.Pattern, bool, re.Pattern[str], tuple[str, ...]]
] | None = None

def __makePlaceholder(self, type: str) -> tuple[str, str]:
""" Generate a placeholder """
Expand Down Expand Up @@ -131,13 +135,24 @@ def __handleInline(self, data: str, patternIndex: int = 0) -> str:
"""
if not isinstance(data, util.AtomicString):
startIndex = 0
count = len(self.inlinePatterns)
while patternIndex < count:
data, matched, startIndex = self.__applyPattern(
self.inlinePatterns[patternIndex], data, patternIndex, startIndex
)
if not matched:
patternIndex += 1
patterns = self._patterns
if patterns is not None:
count = len(patterns)
while patternIndex < count:
pattern, new_style, compiled_re, excludes = patterns[patternIndex]
data, matched, startIndex = self.__applyPattern(
pattern, data, patternIndex, startIndex, new_style, compiled_re, excludes
)
if not matched:
patternIndex += 1
else: # pragma: no cover
count = len(self.inlinePatterns)
while patternIndex < count:
data, matched, startIndex = self.__applyPattern(
self.inlinePatterns[patternIndex], data, patternIndex, startIndex
)
if not matched:
patternIndex += 1
return data

def __processElementText(self, node: etree.Element, subnode: etree.Element, isText: bool = True) -> None:
Expand Down Expand Up @@ -255,7 +270,10 @@ def __applyPattern(
pattern: inlinepatterns.Pattern,
data: str,
patternIndex: int,
startIndex: int = 0
startIndex: int = 0,
new_style: bool | None = None,
compiled_re: re.Pattern[str] | None = None,
excludes: tuple[str, ...] | None = None,
) -> tuple[str, bool, int]:
"""
Check if the line fits the pattern, create the necessary
Expand All @@ -271,26 +289,36 @@ def __applyPattern(
String with placeholders instead of `ElementTree` elements.

"""
new_style = isinstance(pattern, inlinepatterns.InlineProcessor)

for exclude in pattern.ANCESTOR_EXCLUDES:
if exclude.lower() in self.ancestors:
return data, False, 0
if new_style is None:
new_style = isinstance(pattern, inlinepatterns.InlineProcessor)

if excludes is None:
for exclude in pattern.ANCESTOR_EXCLUDES:
if exclude.lower() in self.ancestors:
return data, False, 0
elif excludes and self.ancestors:
ancestors = self.ancestors
for exclude in excludes:
if exclude in ancestors:
return data, False, 0

if compiled_re is None:
compiled_re = pattern.getCompiledRegExp()

if new_style:
match = None
# Since `handleMatch` may reject our first match,
# we iterate over the buffer looking for matches
# until we can't find any more.
for match in pattern.getCompiledRegExp().finditer(data, startIndex):
for match in compiled_re.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:])
match = compiled_re.match(data[startIndex:])
leftData = data[:startIndex]

if not match:
Expand Down Expand Up @@ -364,17 +392,26 @@ def run(self, tree: etree.Element, ancestors: list[str] | None = None) -> etree.

"""
self.stashed_nodes: dict[str, etree.Element | str] = {}
self._patterns: list[tuple[inlinepatterns.Pattern, bool, re.Pattern[str], tuple[str, ...]]] | None = [
(
p,
isinstance(p, inlinepatterns.InlineProcessor),
p.getCompiledRegExp(),
tuple(e.lower() for e in p.ANCESTOR_EXCLUDES),
)
for p in self.inlinePatterns
]

# 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[:]

self.parent_map = {c: p for p in tree.iter() for c in p}
stack = [(tree, tree_parents)]
stack: deque[tuple[etree.Element, list[str]]] = deque([(tree, tree_parents)])
self.__build_ancestors(tree, tree_parents)

while stack:
currElement, parents = stack.pop(0)
currElement, parents = stack.popleft()

self.ancestors = parents
if currElement is not tree:
Expand Down Expand Up @@ -420,6 +457,7 @@ def run(self, tree: etree.Element, ancestors: list[str] | None = None) -> etree.
# parsed elements are not retained until the next convert().
self.parent_map = {}
self.stashed_nodes = {}
self._patterns = None
return tree


Expand Down
Loading