Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions docs/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 (#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,
Expand Down
192 changes: 132 additions & 60 deletions markdown/extensions/fenced_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

from __future__ import annotations

from bisect import bisect_right
from textwrap import dedent
from . import Extension
from ..preprocessors import Preprocessor
Expand Down Expand Up @@ -63,16 +64,27 @@ class FencedBlockPreprocessor(Preprocessor):

FENCED_BLOCK_RE = re.compile(
dedent(r'''
(?P<fence>^(?:~{3,}|`{3,}))[ ]* # opening fence
(?P<fence>^(?:~{3,}+|`{3,}+))[ ]*+ # opening fence
((\{(?P<attrs>[^\n]*)\})| # (optional {attrs} or
(\.?(?P<lang>[\w#.+-]*)[ ]*)? # optional (.)lang
(hl_lines=(?P<quot>"|')(?P<hl_lines>.*?)(?P=quot)[ ]*)?) # optional hl_lines)
(\.?(?P<lang>[\w#.+-]*+)[ ]*+)? # optional (.)lang
(hl_lines=(?P<quot>"|')(?P<hl_lines>[^\n]*?)(?P=quot)[ ]*+)?) # optional hl_lines)
\n # newline (end of opening fence)
(?P<code>.*?)(?<=\n) # the code block
(?P=fence)[ ]*$ # closing fence
'''),
re.MULTILINE | re.DOTALL | re.VERBOSE
)
OPENING_FENCE_RE = re.compile(
dedent(r'''
^(?P<fence>~{3,}+|`{3,}+)[ ]*+ # opening fence
(?:
\{(?P<attrs>[^\n]*)\}| # optional {attrs} or
(?:\.?(?P<lang>[\w#.+-]*+)[ ]*+)? # optional (.)lang
(?:hl_lines=(?P<quot>"|')(?P<hl_lines>[^\n]*?)(?P=quot)[ ]*+)? # optional hl_lines
)$
'''),
re.VERBOSE
)

def __init__(self, md: Markdown, config: dict[str, Any]):
super().__init__(md)
Expand Down Expand Up @@ -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] = []
Expand All @@ -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'<pre{id_attr}{class_attr}><code{lang_attr}{kv_pairs}>{code}</code></pre>'

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.
Expand All @@ -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'<pre{id_attr}{class_attr}><code{lang_attr}{kv_pairs}>{code}</code></pre>'

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)
Expand Down
65 changes: 65 additions & 0 deletions tests/test_syntax/extensions/test_fenced_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
'<p>' + ('~~~a\n' * 5000).rstrip('\n') + '</p>',
extensions=['fenced_code']
)
line = '~~~' + ' ' * 20000 + '!'
self.assertMarkdownRenders(
line + '\n~~~\n',
f'<p>{line}\n~~~</p>',
extensions=['fenced_code']
)
hl_lines_input = '~~~hl_lines="1\n' * 2000 + '~~~\n'
self.assertMarkdownRenders(
hl_lines_input,
'<p>' + hl_lines_input.rstrip('\n') + '</p>',
extensions=['fenced_code']
)
invalid_attrs_input = '~~~{a} }\n' * 2000 + '~~~\n'
self.assertMarkdownRenders(
invalid_attrs_input,
'<p>' + invalid_attrs_input.rstrip('\n') + '</p>',
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(
'''
<p>~~~ {.python} }
bad
~~~</p>
<pre><code class="language-python">ok
</code></pre>
'''
),
extensions=[CustomExtension()]
)


class TestFencedCodeWithCodehilite(TestCase):

Expand Down