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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Change Log

## Unreleased

- ✨ Add `highlight_verbatim` to preserve complete syntax-highlighter HTML without an extra code wrapper ([#256](https://github.com/executablebooks/markdown-it-py/issues/256)).

## 4.3.0 - 2026-11-10

This release fixes two quadratic-time parsing paths that let crafted input stall rendering for minutes (security),
Expand Down
33 changes: 33 additions & 0 deletions docs/using.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,39 @@ Additionally `renderInline` runs the parser with all block syntax rules disabled
md.renderInline("__*emphasise this*__")
```

### Syntax highlighting

The `highlight` option accepts a callback `(code, language, attrs) -> str` for
fenced code blocks. Its HTML is normally wrapped in `<pre><code>`, unless it
starts with `<pre`. Returning an empty string uses the default escaped code.

When a highlighter supplies a complete HTML block, such as Pygments' default
`<div class="highlight">` wrapper, set `highlight_verbatim=True`:

```python
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import get_lexer_by_name
from pygments.util import ClassNotFound


def highlight_code(code: str, language: str, attrs: str) -> str:
try:
lexer = get_lexer_by_name(language)
except ClassNotFound:
return ""
return highlight(code, lexer, HtmlFormatter())


md = MarkdownIt("commonmark", {"highlight": highlight_code, "highlight_verbatim": True})
```

This Python only option defaults to `False`. When enabled, a nonempty callback
result is returned exactly as supplied, including its line endings; no wrapper,
language class or newline is added. The callback is responsible for escaping
code in its HTML. An empty result, or no callback, still uses the usual escaped
`<pre><code>` output.

### Typographic components

The `smartquotes` and `replacements` components are intended to improve typography:
Expand Down
7 changes: 4 additions & 3 deletions markdown_it/renderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,9 +296,10 @@ def fence(
langAttrs = arr[1]

if options.highlight:
highlighted = options.highlight(
token.content, langName, langAttrs
) or escapeHtml(token.content)
highlighted = options.highlight(token.content, langName, langAttrs)
if highlighted and options.get("highlight_verbatim", False):
return highlighted
highlighted = highlighted or escapeHtml(token.content)
else:
highlighted = escapeHtml(token.content)

Expand Down
5 changes: 5 additions & 0 deletions markdown_it/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ class OptionsType(TypedDict):
"""CSS language prefix for fenced blocks."""
highlight: Callable[[str, str, str], str] | None
"""Highlighter function: (content, lang, attrs) -> str."""
highlight_verbatim: NotRequired[bool]
"""Return nonempty highlighter output unchanged, without a code wrapper.

This Python only option defaults to False.
"""
store_labels: NotRequired[bool]
"""Store link label in link/image token's metadata (under Token.meta['label']).

Expand Down
50 changes: 50 additions & 0 deletions tests/test_api/test_highlight_verbatim.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
from itertools import product

from markdown_it import MarkdownIt


def test_highlight_verbatim_preserves_complete_html() -> None:
"""A complete highlighter block keeps its wrapper and exact line endings."""
for preset, ending in product(["commonmark", "js-default", "zero"], ["", "\n"]):
rendered = '<div class="highlight"><pre>highlighted</pre></div>' + ending

def highlight(
content: str, language: str, attrs: str, result: str = rendered
) -> str:
assert (content, language, attrs) == ("<unsafe>\n", "python", "extra")
return result

parser = MarkdownIt(
preset, {"highlight": highlight, "highlight_verbatim": True}
)
parser.enable("fence")
assert parser.render("```python extra\n<unsafe>\n```\n") == rendered


def test_empty_highlight_keeps_escaped_fallback() -> None:
"""No highlighter result still gets the ordinary escaped code wrapper."""
for highlight, verbatim in product([None, lambda *_: ""], [False, True]):
parser = MarkdownIt(
"commonmark", {"highlight": highlight, "highlight_verbatim": verbatim}
)
assert parser.render("```py\n<unsafe>\n```\n") == (
'<pre><code class="language-py">&lt;unsafe&gt;\n</code></pre>\n'
)


def test_default_highlighter_wrapping_is_unchanged() -> None:
"""The opt-in setting leaves the existing wrapper heuristic intact."""
for highlighted, expected in [
(
"<div>code</div>",
'<pre><code class="language-py"><div>code</div></code></pre>\n',
),
("<pre>code</pre>", "<pre>code</pre>\n"),
]:
parser = MarkdownIt(
"commonmark", {"highlight": lambda *_, result=highlighted: result}
)
source = "```py\ncode\n```\n"
assert parser.render(source) == expected
parser.options["highlight_verbatim"] = True
assert parser.render(source) == highlighted
Loading