diff --git a/CHANGELOG.md b/CHANGELOG.md index c411d126..13f16646 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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), diff --git a/docs/using.md b/docs/using.md index fd242313..ac27f085 100644 --- a/docs/using.md +++ b/docs/using.md @@ -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 `
`, unless it
+starts with `` 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
+`` output.
+
### Typographic components
The `smartquotes` and `replacements` components are intended to improve typography:
diff --git a/markdown_it/renderer.py b/markdown_it/renderer.py
index 6ccdee9b..2e189337 100644
--- a/markdown_it/renderer.py
+++ b/markdown_it/renderer.py
@@ -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)
diff --git a/markdown_it/utils.py b/markdown_it/utils.py
index cc48fa5c..602e0bf9 100644
--- a/markdown_it/utils.py
+++ b/markdown_it/utils.py
@@ -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']).
diff --git a/tests/test_api/test_highlight_verbatim.py b/tests/test_api/test_highlight_verbatim.py
new file mode 100644
index 00000000..b8548c33
--- /dev/null
+++ b/tests/test_api/test_highlight_verbatim.py
@@ -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 = 'highlighted
' + ending
+
+ def highlight(
+ content: str, language: str, attrs: str, result: str = rendered
+ ) -> str:
+ assert (content, language, attrs) == ("\n", "python", "extra")
+ return result
+
+ parser = MarkdownIt(
+ preset, {"highlight": highlight, "highlight_verbatim": True}
+ )
+ parser.enable("fence")
+ assert parser.render("```python extra\n\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\n```\n") == (
+ '<unsafe>\n
\n'
+ )
+
+
+def test_default_highlighter_wrapping_is_unchanged() -> None:
+ """The opt-in setting leaves the existing wrapper heuristic intact."""
+ for highlighted, expected in [
+ (
+ "code",
+ 'code
\n',
+ ),
+ ("code
", "code
\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