From 167905b506981c7b054806680a631ea9348284d4 Mon Sep 17 00:00:00 2001 From: AMIRUL IAN Date: Thu, 3 Dec 2026 09:29:24 +0800 Subject: [PATCH 1/2] Fix quadratic processing time in fenced_code extension --- docs/changelog.md | 3 + markdown/extensions/fenced_code.py | 192 ++++++++++++------ .../extensions/test_fenced_code.py | 65 ++++++ 3 files changed, 200 insertions(+), 60 deletions(-) diff --git a/docs/changelog.md b/docs/changelog.md index 2020ed858..2e378d808 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -16,6 +16,9 @@ See the [Contributing Guide](contributing.md) for details. ### Fixed +* Fix quadratic processing time in the `fenced_code` extension for unclosed + fences, invalid opening fence lines with many spaces, and unclosed `hl_lines` + quotes. * 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/extensions/fenced_code.py b/markdown/extensions/fenced_code.py index 9ff1b28d7..a40319f3b 100644 --- a/markdown/extensions/fenced_code.py +++ b/markdown/extensions/fenced_code.py @@ -21,6 +21,7 @@ from __future__ import annotations +from bisect import bisect_right from textwrap import dedent from . import Extension from ..preprocessors import Preprocessor @@ -63,16 +64,27 @@ class FencedBlockPreprocessor(Preprocessor): FENCED_BLOCK_RE = re.compile( dedent(r''' - (?P^(?:~{3,}|`{3,}))[ ]* # opening fence + (?P^(?:~{3,}+|`{3,}+))[ ]*+ # opening fence ((\{(?P[^\n]*)\})| # (optional {attrs} or - (\.?(?P[\w#.+-]*)[ ]*)? # optional (.)lang - (hl_lines=(?P"|')(?P.*?)(?P=quot)[ ]*)?) # optional hl_lines) + (\.?(?P[\w#.+-]*+)[ ]*+)? # optional (.)lang + (hl_lines=(?P"|')(?P[^\n]*?)(?P=quot)[ ]*+)?) # optional hl_lines) \n # newline (end of opening fence) (?P.*?)(?<=\n) # the code block (?P=fence)[ ]*$ # closing fence '''), re.MULTILINE | re.DOTALL | re.VERBOSE ) + OPENING_FENCE_RE = re.compile( + dedent(r''' + ^(?P~{3,}+|`{3,}+)[ ]*+ # opening fence + (?: + \{(?P[^\n]*)\}| # optional {attrs} or + (?:\.?(?P[\w#.+-]*+)[ ]*+)? # optional (.)lang + (?:hl_lines=(?P"|')(?P[^\n]*?)(?P=quot)[ ]*+)? # optional hl_lines + )$ + '''), + re.VERBOSE + ) def __init__(self, md: Markdown, config: dict[str, Any]): super().__init__(md) @@ -101,6 +113,9 @@ def run(self, lines: list[str]) -> list[str]: self.checked_for_deps = True + if self.FENCED_BLOCK_RE is FencedBlockPreprocessor.FENCED_BLOCK_RE: + return self._run_indexed(lines) + text = "\n".join(lines) # Collect the output in pieces, as rebuilding the full text after each block is quadratic. pieces: list[str] = [] @@ -109,63 +124,11 @@ def run(self, lines: list[str]) -> list[str]: while 1: m = self.FENCED_BLOCK_RE.search(text, index) if m: - lang, id, classes, config = None, '', [], {} - if m.group('attrs'): - attrs, remainder = get_attrs_and_remainder(m.group('attrs')) - if remainder: # Does not have correctly matching curly braces, so the syntax is invalid. - index = m.end('attrs') # Explicitly skip over this, to prevent an infinite loop. - continue - id, classes, config = self.handle_attrs(attrs) - if len(classes): - lang = classes.pop(0) - else: - if m.group('lang'): - lang = m.group('lang') - if m.group('hl_lines'): - # Support `hl_lines` outside of `attrs` for backward-compatibility - config['hl_lines'] = parse_hl_lines(m.group('hl_lines')) - - # If `config` is not empty, then the `codehighlite` extension - # is enabled, so we call it to highlight the code - if self.codehilite_conf and self.codehilite_conf['use_pygments'] and config.get('use_pygments', True): - local_config = self.codehilite_conf.copy() - local_config.update(config) - # Combine classes with `cssclass`. Ensure `cssclass` is at end - # as Pygments appends a suffix under certain circumstances. - # Ignore ID as Pygments does not offer an option to set it. - if classes: - local_config['css_class'] = '{} {}'.format( - ' '.join(classes), - local_config['css_class'] - ) - highliter = CodeHilite( - m.group('code'), - lang=lang, - style=local_config.pop('pygments_style', 'default'), - **local_config - ) - - code = highliter.hilite(shebang=False) - else: - id_attr = lang_attr = class_attr = kv_pairs = '' - if lang: - prefix = self.config.get('lang_prefix', 'language-') - lang_attr = f' class="{prefix}{_escape_attrib_html(lang)}"' - if classes: - class_attr = f' class="{_escape_attrib_html(" ".join(classes))}"' - if id: - id_attr = f' id="{_escape_attrib_html(id)}"' - if self.use_attr_list and config and not config.get('use_pygments', False): - # Only assign key/value pairs to code element if `attr_list` extension is enabled, key/value - # pairs were defined on the code block, and the `use_pygments` key was not set to `True`. The - # `use_pygments` key could be either set to `False` or not defined. It is omitted from output. - kv_pairs = ''.join( - self._format_attr(k, v) - for k, v in config.items() if k != 'use_pygments' - ) - code = self._escape(m.group('code')) - code = f'{code}' - + parsed = self._parse_opening_fence(m) + if parsed is None: # Invalid `{attrs}` syntax (unmatched curly braces). + index = m.end('attrs') # Explicitly skip over this, to prevent an infinite loop. + continue + code = self._render_code_block(*parsed, m.group('code')) placeholder = self.md.htmlStash.store(code) pieces.append(f'{text[last:m.start()]}\n{placeholder}\n') # Continue from after the replaced text in the next iteration. @@ -175,6 +138,115 @@ def run(self, lines: list[str]) -> list[str]: pieces.append(text[last:]) return "".join(pieces).split("\n") + def _run_indexed(self, lines: list[str]) -> list[str]: + """ Match fenced code blocks in linear time using indexed closing fences. """ + lines = "\n".join(lines).split("\n") + + closing_fences: dict[str, list[int]] = {} + for idx, line in enumerate(lines): + if len(line) >= 3 and line[0] in ('`', '~'): + stripped = line.rstrip(' ') + if len(stripped) >= 3 and not stripped.strip(stripped[0]): + closing_fences.setdefault(stripped, []).append(idx) + + if not closing_fences: + return lines + + output: list[str] = [] + i = 0 + num_lines = len(lines) + while i < num_lines: + line = lines[i] + if len(line) >= 3 and line[0] in ('`', '~'): + m = self.OPENING_FENCE_RE.match(line) + if m: + positions = closing_fences.get(m.group('fence')) + if positions: + pos_idx = bisect_right(positions, i) + if pos_idx < len(positions): + parsed = self._parse_opening_fence(m) + if parsed is not None: + close_idx = positions[pos_idx] + code_str = "\n".join(lines[i + 1:close_idx]) + "\n" if close_idx > i + 1 else "" + code = self._render_code_block(*parsed, code_str) + placeholder = self.md.htmlStash.store(code) + output.extend(("", placeholder, "")) + i = close_idx + 1 + continue + output.append(line) + i += 1 + return output + + def _parse_opening_fence( + self, m: re.Match[str] + ) -> tuple[str | None, str, list[str], dict[str, Any]] | None: + """ Parse opening fence metadata, or return `None` if `{attrs}` has unmatched braces. """ + lang, id, classes, config = None, '', [], {} + if m.group('attrs'): + attrs, remainder = get_attrs_and_remainder(m.group('attrs')) + if remainder: # Does not have correctly matching curly braces, so the syntax is invalid. + return None + id, classes, config = self.handle_attrs(attrs) + if len(classes): + lang = classes.pop(0) + else: + if m.group('lang'): + lang = m.group('lang') + if m.group('hl_lines'): + # Support `hl_lines` outside of `attrs` for backward-compatibility + config['hl_lines'] = parse_hl_lines(m.group('hl_lines')) + return lang, id, classes, config + + def _render_code_block( + self, + lang: str | None, + id: str, + classes: list[str], + config: dict[str, Any], + code_str: str, + ) -> str: + """ Format a parsed fenced code block as HTML. """ + # If `config` is not empty, then the `codehighlite` extension + # is enabled, so we call it to highlight the code + if self.codehilite_conf and self.codehilite_conf['use_pygments'] and config.get('use_pygments', True): + local_config = self.codehilite_conf.copy() + local_config.update(config) + # Combine classes with `cssclass`. Ensure `cssclass` is at end + # as Pygments appends a suffix under certain circumstances. + # Ignore ID as Pygments does not offer an option to set it. + if classes: + local_config['css_class'] = '{} {}'.format( + ' '.join(classes), + local_config['css_class'] + ) + highliter = CodeHilite( + code_str, + lang=lang, + style=local_config.pop('pygments_style', 'default'), + **local_config + ) + + return highliter.hilite(shebang=False) + + id_attr = lang_attr = class_attr = kv_pairs = '' + if lang: + prefix = self.config.get('lang_prefix', 'language-') + lang_attr = f' class="{prefix}{_escape_attrib_html(lang)}"' + if classes: + class_attr = f' class="{_escape_attrib_html(" ".join(classes))}"' + if id: + id_attr = f' id="{_escape_attrib_html(id)}"' + if self.use_attr_list and config and not config.get('use_pygments', False): + # Only assign key/value pairs to code element if `attr_list` extension is enabled, key/value + # pairs were defined on the code block, and the `use_pygments` key was not set to `True`. The + # `use_pygments` key could be either set to `False` or not defined. It is omitted from output. + kv_pairs = ''.join( + self._format_attr(k, v) + for k, v in config.items() if k != 'use_pygments' + ) + code = self._escape(code_str) + return f'{code}' + def _format_attr(self, key: str, value: Any) -> str: """ Serialize a key/value pair for the `code` element as the serializer would. """ key = sanitize_name(key) diff --git a/tests/test_syntax/extensions/test_fenced_code.py b/tests/test_syntax/extensions/test_fenced_code.py index 6cbbef693..8a4cec996 100644 --- a/tests/test_syntax/extensions/test_fenced_code.py +++ b/tests/test_syntax/extensions/test_fenced_code.py @@ -653,6 +653,71 @@ def testManyFencedBlocks(self): extensions=['fenced_code'] ) + def testUnclosedFencesLinearTime(self): + # Unclosed fences, spaces on invalid fence lines, unclosed `hl_lines` quotes, + # and invalid `{attrs}` lines before a closing fence should not cause quadratic scanning. + self.assertMarkdownRenders( + '~~~a\n' * 5000, + '

' + ('~~~a\n' * 5000).rstrip('\n') + '

', + extensions=['fenced_code'] + ) + line = '~~~' + ' ' * 20000 + '!' + self.assertMarkdownRenders( + line + '\n~~~\n', + f'

{line}\n~~~

', + extensions=['fenced_code'] + ) + hl_lines_input = '~~~hl_lines="1\n' * 2000 + '~~~\n' + self.assertMarkdownRenders( + hl_lines_input, + '

' + hl_lines_input.rstrip('\n') + '

', + extensions=['fenced_code'] + ) + invalid_attrs_input = '~~~{a} }\n' * 2000 + '~~~\n' + self.assertMarkdownRenders( + invalid_attrs_input, + '

' + invalid_attrs_input.rstrip('\n') + '

', + extensions=['fenced_code'] + ) + + def testCustomFencedBlockReFallback(self): + import re + from markdown.extensions.fenced_code import FencedBlockPreprocessor, FencedCodeExtension + + class CustomPreprocessor(FencedBlockPreprocessor): + FENCED_BLOCK_RE = re.compile( + FencedBlockPreprocessor.FENCED_BLOCK_RE.pattern + '\n', re.M | re.S | re.X + ) + + class CustomExtension(FencedCodeExtension): + def extendMarkdown(self, md): + md.registerExtension(self) + md.preprocessors.register(CustomPreprocessor(md, self.getConfigs()), 'fenced_code_block', 25) + + self.assertMarkdownRenders( + self.dedent( + ''' + ~~~ {.python} } + bad + ~~~ + + ``` python + ok + ``` + ''' + ), + self.dedent( + ''' +

~~~ {.python} } + bad + ~~~

+
ok
+                
+ ''' + ), + extensions=[CustomExtension()] + ) + class TestFencedCodeWithCodehilite(TestCase): From 892a39ae2aca2655b35045212eebd65297924ca9 Mon Sep 17 00:00:00 2001 From: AMIRUL IAN Date: Fri, 4 Dec 2026 19:24:55 +0800 Subject: [PATCH 2/2] Add PR number to changelog entry --- docs/changelog.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/changelog.md b/docs/changelog.md index 2e378d808..00b93d920 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -18,7 +18,7 @@ See the [Contributing Guide](contributing.md) for details. * Fix quadratic processing time in the `fenced_code` extension for unclosed fences, invalid opening fence lines with many spaces, and unclosed `hl_lines` - quotes. + quotes (#1731). * 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,