diff --git a/docs/changelog.md b/docs/changelog.md index 828d283cb..7dec4211b 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -47,6 +47,9 @@ See the [Contributing Guide](contributing.md) for details. * Fix quadratic processing time in the `tables` extension for long blocks which are split into many smaller blocks, such as many headers with no blank lines between them (#1704). +* Fix quadratic processing time in emphasis handling for many unclosed openers + which the rule of 3 keeps an ambiguous closer from pairing with, such as + `*a **b` repeated. ## [3.11.3] - 2026-11-05 diff --git a/markdown/inlinepatterns.py b/markdown/inlinepatterns.py index 82aadadbf..1b7260325 100644 --- a/markdown/inlinepatterns.py +++ b/markdown/inlinepatterns.py @@ -662,6 +662,8 @@ def __init__( self.stack: list[tuple[int, int, bool, int, int]] = [] # Position of every delimiter token (valid or not) encountered while pairing, in ascending order. self.positions: list[int] = [] + # For each token and run length, how deep the last failed rule of 3 search went and the entry at that depth. + self.searched: dict[tuple[str, int], tuple[int, tuple[int, int, bool, int, int]]] = {} self.tokens: list[str] = [] self.delimiters: dict[str, Delimiter] = {} self.cache_index = 0 @@ -710,6 +712,7 @@ def reset(self) -> None: self.cache.clear() self.stack.clear() self.positions.clear() + self.searched.clear() self.cache_index = 0 self.cache_pos = 0 self.remainder = None @@ -994,12 +997,23 @@ def _handle_match( stack and is_ambiguous and current != last and self.rule_of_3(stack[-1][3], current) ): - for i in range(len(stack) - 2, -1, -1): + # Skip the entries an earlier search for this length already ruled out. They are unchanged + # as long as the last of them is still in place, as entries are only ever appended or popped. + lowest = 0 + key = (token, current) + if key in self.searched: + depth, entry = self.searched[key] + if depth < len(stack) and stack[depth - 1] is entry: + lowest = depth + for i in range(len(stack) - 2, lowest - 1, -1): if stack[i][-1] == current and not self.rule_of_3(stack[i][3], current): while len(stack) > i + 1: stack.pop() last = current break + else: + if len(stack) > 1: + self.searched[key] = (len(stack) - 1, stack[-2]) # Find closing tokens # Looking for: diff --git a/tests/test_syntax/inline/test_emphasis.py b/tests/test_syntax/inline/test_emphasis.py index c7cfa6340..d6d151529 100644 --- a/tests/test_syntax/inline/test_emphasis.py +++ b/tests/test_syntax/inline/test_emphasis.py @@ -944,6 +944,15 @@ def test_rule_of_3_skipped_opener_removed(self): '

abcde**fgh**

' ) + def test_rule_of_3_many_unclosed_openers(self): + """Test that unclosed openers rejected by the rule of 3 are not searched again for every closer.""" + + count = 10000 + self.assertMarkdownRenders( + '*a **b*a **b' * count, + '

' + 'a **ba **b' * count + '

' + ) + class TestProcessorRemoval(TestCase):