diff --git a/docs/changelog.md b/docs/changelog.md index c1b8c9264..d3c2e4c38 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -18,6 +18,10 @@ See the [Contributing Guide](contributing.md) for details. * Fix a doubled `mailto:` in automatic email links which write the scheme in upper or mixed case, such as `` (#1733). +* Fix quadratic rendering time for documents with many links or images, a + regression in 3.11.4. The closing bracket for each index of the text is now + found only when a link's bracket does not close, rather than once for every + link (#1664). * 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, diff --git a/markdown/inlinepatterns.py b/markdown/inlinepatterns.py index c77eb445a..d27e99946 100644 --- a/markdown/inlinepatterns.py +++ b/markdown/inlinepatterns.py @@ -1129,12 +1129,15 @@ class LinkInlineProcessor(InlineProcessor): """ Return a link element from the given match. """ RE_LINK = re.compile(r'''\(\s*(?:(<[^<>]*>)\s*(?:('[^']*'|"[^"]*")\s*)?\))?''', re.DOTALL | re.UNICODE) RE_TITLE_CLEAN = re.compile(r'\s') + RE_BRACKETS = re.compile(r'[\[\]]') def __init__(self, pattern: str, md: Markdown | None = None): super().__init__(pattern, md) - # The text `getText` last saw and the closing bracket for each index of it. + # The text `getText` last scanned to the end of, the index it started from, + # and the closing bracket for each index of that text from there on. self._bracket_data: str | None = None - self._bracket_ends: list[int | None] = [] + self._bracket_start: int = 0 + self._bracket_ends: dict[int, int] = {} def handleMatch(self, m: re.Match[str], data: str) -> tuple[etree.Element | None, int | None, int | None]: """ Return an `a` [`Element`][xml.etree.ElementTree.Element] or `(None, None, None)`. """ @@ -1278,38 +1281,45 @@ def getText(self, data: str, index: int) -> tuple[str, int, bool]: resolving nested square brackets. """ - # Scanning forward from every `[` is quadratic when the brackets do not - # close, so find the closing bracket for every index of `data` at once. - if self._bracket_data is not data: + # Scanning to the closing bracket costs no more than the length of the link + # text, so only index the brackets after `index` once a scan has run to the + # end of `data` without finding one. Scanning from every `[` is quadratic + # when the brackets do not close, while indexing every `data` is quadratic + # in the number of links, as `data` is rebuilt after each match. + if self._bracket_data is not data or index < self._bracket_start: + end, ends = self._findBracketEnds(data, index) + if ends is None: + return data[index:end - 1], end, True self._bracket_data = data - self._bracket_ends = self._findBracketEnds(data) - end = self._bracket_ends[index] + self._bracket_start = index + self._bracket_ends = ends + end = self._bracket_ends.get(index) if end is None: return data[index:], len(data), False return data[index:end - 1], end, True - @staticmethod - def _findBracketEnds(data: str) -> list[int | None]: + @classmethod + def _findBracketEnds(cls, data: str, index: int) -> tuple[int | None, dict[int, int] | None]: """ - For each index of `data`, return the index just past the `]` which closes an - opening bracket before that index, or `None` if the bracket never closes. + Return the index just past the `]` which closes the bracket before `index`. + + If that bracket never closes, `data` has been scanned to the end, so return + `None` for it together with a mapping from each later index whose bracket + does close to the index just past the `]` which closes it. """ - ends: list[int | None] = [None] * (len(data) + 1) - depth = 0 - # `stack` holds the indexes still waiting for a closing bracket. The bracket - # depth before each one is strictly increasing from bottom to top. - stack: list[tuple[int, int]] = [] - for pos in range(len(data) + 1): - while stack and depth < stack[-1][1]: - ends[stack.pop()[0]] = pos - stack.append((pos, depth)) - if pos < len(data): - if data[pos] == '[': - depth += 1 - elif data[pos] == ']': - depth -= 1 - return ends + ends: dict[int, int] = {} + # The indexes still waiting for a closing bracket, innermost last. + open_ends = [index] + for m in cls.RE_BRACKETS.finditer(data, index): + if m.group() == '[': + open_ends.append(m.end()) + else: + start = open_ends.pop() + if start == index: + return m.end(), None + ends[start] = m.end() + return None, ends class ImageInlineProcessor(LinkInlineProcessor): diff --git a/tests/test_syntax/inline/test_links.py b/tests/test_syntax/inline/test_links.py index 48464da64..66f81b090 100644 --- a/tests/test_syntax/inline/test_links.py +++ b/tests/test_syntax/inline/test_links.py @@ -177,6 +177,13 @@ def test_many_unclosed_square_brackets(self): '

' + '[[' * 10000 + 'Text

' ) + def test_many_links(self): + # Each link used to index the brackets in the rest of the text again. + self.assertMarkdownRenders( + '[Text](http://link.com)' * 10000, + '

' + 'Text' * 10000 + '

' + ) + class TestReferenceLinks(TestCase):