diff --git a/docs/changelog.md b/docs/changelog.md index 828d283cb..54265e0f6 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 `}`. * The `toc` extension no longer raises `TypeError` for a heading whose `data-toc-label` attribute is present but valueless, as the `attr_list` extension's bare-attribute syntax (`{: data-toc-label }`) writes it: like a 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'] + )