diff --git a/.spell-dict b/.spell-dict index f70d2bc8d..25847db53 100644 --- a/.spell-dict +++ b/.spell-dict @@ -109,6 +109,8 @@ refactored refactors registerExtension rescan +rescanned +rescanning resettable richeland RSS diff --git a/docs/changelog.md b/docs/changelog.md index 51fb99359..2020ed858 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -16,6 +16,8 @@ See the [Contributing Guide](contributing.md) for details. ### Fixed +* Fix cubic processing time in the `legacy_attrs` extension for text with many + `{@` that are not closed by a `}` (#1721). * Footnote definitions are no longer recognized within a footnote definition, matching PHP Markdown Extra: an indented definition nested in another footnote's content now remains as text in the parent footnote instead of diff --git a/markdown/extensions/legacy_attrs.py b/markdown/extensions/legacy_attrs.py index 4b82c0efd..bd6d410f0 100644 --- a/markdown/extensions/legacy_attrs.py +++ b/markdown/extensions/legacy_attrs.py @@ -57,9 +57,19 @@ def run(self, doc: etree.Element) -> None: def handleAttributes(self, el: etree.Element, txt: str) -> str: """ Set attributes and return text without definitions. """ - def attributeCallback(match: re.Match[str]): - el.set(sanitize_name(match.group(1)), match.group(2).replace('\n', ' ')) - return ATTR_RE.sub(attributeCallback, txt) + # Neither part of a definition can contain `}`, so one that starts at `{@` ends at the next + # `}`, and if the first `{@` before a `}` does not match, no later one before it can. Matching + # only there avoids `ATTR_RE.sub` rescanning to the end of the text from every `{@`. + parts = txt.split('}') + for i in range(len(parts) - 1): + part = parts[i] + '}' + start = part.find('{@') + m = ATTR_RE.match(part, start) if start != -1 else None + if m: + el.set(sanitize_name(m.group(1)), m.group(2).replace('\n', ' ')) + part = part[:start] + parts[i] = part + return ''.join(parts) class LegacyAttrExtension(Extension): diff --git a/tests/test_syntax/extensions/test_legacy_attrs.py b/tests/test_syntax/extensions/test_legacy_attrs.py index c261d932f..4307d54a5 100644 --- a/tests/test_syntax/extensions/test_legacy_attrs.py +++ b/tests/test_syntax/extensions/test_legacy_attrs.py @@ -73,3 +73,12 @@ def testLegacyAttrsSanitizesName(self): '

text more

', extensions=['legacy_attrs'] ) + + def testLegacyAttrsManyUnclosed(self): + # Each `{@` with no closing `}` used to be rescanned to the end of the text for every `=`. + text = '{@a=' * 2000 + self.assertMarkdownRenders( + text, + f'

{text}

', + extensions=['legacy_attrs'] + )