Skip to content
Merged
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
26 changes: 14 additions & 12 deletions python/mdhtml/export.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@

from ._html import parse_mdhtml

try: from fastpylight import highlight, highlight_spans, languages
except ImportError: highlight = highlight_spans = languages = None
try: from fastpylight import highlight, highlight_spans
except ImportError: highlight = highlight_spans = None

__all__ = ["SCHEMES", "REFTYPES", "ref_tokens", "ref_variant", "decode_raw", "group_plan", "HeadingNums", "Resolver", "to_html", "math_js"]

Expand Down Expand Up @@ -331,16 +331,18 @@ def _hl(self, pre):
if self.hl_lang and (new := self.hl_lang(text, lang)) != lang:
lang = new
if lang: code.attrs["class"] = f"language-{lang}"
if self.hl and highlight_spans and lang is not None and lang in languages():
if self.hl == "spans":
frag = parse_mdhtml(highlight_spans(text, lang))
_set_children(code, list(frag.children[0].children[0].children))
else:
frag = parse_mdhtml(highlight(text, lang))
hlc = _mk("hl-code", {"toks": frag.children[0].attrs.get("toks")})
pre.parent.replace_child(hlc, pre)
hlc.append_child(pre)
pre = hlc
if self.hl and highlight_spans and lang is not None:
try:
if self.hl == "spans":
frag = parse_mdhtml(highlight_spans(text, lang))
_set_children(code, list(frag.children[0].children[0].children))
else:
frag = parse_mdhtml(highlight(text, lang))
hlc = _mk("hl-code", {"toks": frag.children[0].attrs.get("toks")})
pre.parent.replace_child(hlc, pre)
hlc.append_child(pre)
pre = hlc
except ValueError: pass
if self.code_wrap and (repl := self.code_wrap(pre.to_html(pretty=False), lang, text)) is not None:
pre.parent.replace_child(parse_mdhtml(repl), pre)

Expand Down
5 changes: 5 additions & 0 deletions tests/test_export.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,11 @@ def wrap(html, lang, text):
assert '<div class="copy-wrap"><pre>' in h
assert '<pre class="mermaid">graph TD</pre>' in h and 'language-mermaid' not in h

def test_hl_lang_alias():
h = to_html(to_mdhtml('```py\n1+1\n```\n\n```nosuchlang\nx\n```\n'))
assert '<span class="hl-number">1</span>' in h # alias resolved by the highlighter
assert '<code class="language-nosuchlang">x\n</code>' in h # unknown language left unhighlighted

def test_refs_ids():
src = to_mdhtml('# A {#sec-a}\n\nSee [@sec-a], [Clause @sec-b], [-@sec-a], and [@fig-e; @sec-nope].\n\n![E](e.png){#fig-e}\n',
implicit_figures=True)
Expand Down
Loading