feat: VS Code-like syntax highlighting for code blocks
Code blocks in documents are now highlighted server-side with Pygments according to their language (Markdown fences and TinyMCE code samples), using VS Code "Dark+" colours in the viewer and a light variant in the print view. A language label is shown next to the copy button. Blocks marked as plain text/Cisco config stay unchanged; blocks without a language are only coloured when the language is detected confidently. Works offline, no CDN needed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
8458cbe8cf
commit
f7e1e21c24
6 files changed
+130
-1
No files matched your search
@@ -0,0 +1,57 @@
|
||||
"""Server-side syntax highlighting of code blocks in rendered documents (VS Code-like colours).
|
||||
|
||||
Runs on already sanitised HTML: the code text is unescaped, re-tokenised by Pygments and
|
||||
re-escaped, so only Pygments' own <span class="..."> markup is added.
|
||||
"""
|
||||
import html
|
||||
import re
|
||||
|
||||
from pygments import highlight
|
||||
from pygments.formatters import HtmlFormatter
|
||||
from pygments.lexers import get_lexer_by_name, guess_lexer
|
||||
from pygments.util import ClassNotFound
|
||||
|
||||
_PRE = re.compile(r"<pre(?P<attrs>[^>]*)>(?:<code(?P<code_attrs>[^>]*)>)?(?P<body>.*?)(?:</code>)?</pre>", re.S)
|
||||
_LANGUAGE = re.compile(r'class="[^"]*\b(?:lang|language)-(?P<name>[\w+#.-]+)')
|
||||
_BR = re.compile(r"<br\s*/?>", re.I)
|
||||
_TAG = re.compile(r"<[^>]+>")
|
||||
|
||||
# Language names used by TinyMCE's code sample plugin and common Markdown fences.
|
||||
_ALIASES = {
|
||||
"markup": "html", "shell": "bash", "sh": "bash", "ps": "powershell", "ps1": "powershell",
|
||||
"yml": "yaml", "js": "javascript", "ts": "typescript", "py": "python",
|
||||
}
|
||||
_PLAIN = {"none", "plaintext", "text", "plain", "txt"}
|
||||
_FORMATTER = HtmlFormatter(nowrap=True)
|
||||
|
||||
|
||||
def _lexer(name, code):
|
||||
if name:
|
||||
name = _ALIASES.get(name.lower(), name.lower())
|
||||
if name in _PLAIN:
|
||||
return None
|
||||
try:
|
||||
return get_lexer_by_name(name)
|
||||
except ClassNotFound:
|
||||
return None
|
||||
# No language given: only trust a confident guess, otherwise leave the block plain.
|
||||
try:
|
||||
lexer = guess_lexer(code)
|
||||
except ClassNotFound:
|
||||
return None
|
||||
return lexer if lexer.analyse_text(code) >= 0.5 else None
|
||||
|
||||
|
||||
def _replace(match):
|
||||
language = _LANGUAGE.search((match.group("attrs") or "") + (match.group("code_attrs") or ""))
|
||||
code = html.unescape(_TAG.sub("", _BR.sub("\n", match.group("body")))).rstrip("\n")
|
||||
lexer = _lexer(language.group("name") if language else None, code)
|
||||
if lexer is None:
|
||||
return match.group(0)
|
||||
highlighted = highlight(code, lexer, _FORMATTER).rstrip("\n")
|
||||
label = html.escape(lexer.name, quote=True)
|
||||
return f'<pre class="doc-hl" data-lang="{label}"><code>{highlighted}</code></pre>'
|
||||
|
||||
|
||||
def highlight_code_blocks(value):
|
||||
return _PRE.sub(_replace, value)
|
||||
@@ -68,7 +68,10 @@ class Document(NetBoxModel):
|
||||
"padding-left", "padding-right", "padding-top", "text-align", "text-decoration",
|
||||
"text-indent", "vertical-align", "white-space", "width",
|
||||
})
|
||||
return bleach.clean(value, tags=tags, attributes=attributes, protocols=("http", "https", "mailto"), css_sanitizer=css)
|
||||
from .highlighting import highlight_code_blocks
|
||||
|
||||
cleaned = bleach.clean(value, tags=tags, attributes=attributes, protocols=("http", "https", "mailto"), css_sanitizer=css)
|
||||
return highlight_code_blocks(cleaned)
|
||||
|
||||
|
||||
class DocumentCategory(NetBoxModel):
|
||||
|
||||
@@ -63,6 +63,29 @@
|
||||
border: 1px solid rgba(255,255,255,.25); border-radius: 4px;
|
||||
}
|
||||
.documentation-content .doc-code-copy:hover { background: rgba(255,255,255,.2); }
|
||||
.documentation-content .doc-code-lang {
|
||||
position: absolute; top: .55rem; right: 6.2rem;
|
||||
font-size: .7rem; color: #9da5b4; text-transform: uppercase; letter-spacing: .03em;
|
||||
pointer-events: none; user-select: none;
|
||||
}
|
||||
.documentation-content pre.doc-hl[data-lang] { padding-right: 11rem; }
|
||||
/* Syntax highlighting (Pygments token classes) - VS Code "Dark+" colours */
|
||||
.documentation-content pre.doc-hl { color: #d4d4d4 !important; }
|
||||
.doc-hl .k, .doc-hl .kc, .doc-hl .kd, .doc-hl .kr, .doc-hl .kp, .doc-hl .ow, .doc-hl .nt, .doc-hl .bp { color: #569cd6; }
|
||||
.doc-hl .kn, .doc-hl .cp, .doc-hl .cpf { color: #c586c0; }
|
||||
.doc-hl .kt, .doc-hl .nc, .doc-hl .nn, .doc-hl .ne { color: #4ec9b0; }
|
||||
.doc-hl .nf, .doc-hl .fm, .doc-hl .nb, .doc-hl .nd { color: #dcdcaa; }
|
||||
.doc-hl .n, .doc-hl .nv, .doc-hl .vi, .doc-hl .vg, .doc-hl .vc, .doc-hl .na, .doc-hl .py, .doc-hl .nl { color: #9cdcfe; }
|
||||
.doc-hl .s, .doc-hl .s1, .doc-hl .s2, .doc-hl .sa, .doc-hl .sb, .doc-hl .sc, .doc-hl .sd, .doc-hl .sh,
|
||||
.doc-hl .si, .doc-hl .sx, .doc-hl .sr, .doc-hl .ss, .doc-hl .dl { color: #ce9178; }
|
||||
.doc-hl .se { color: #d7ba7d; }
|
||||
.doc-hl .m, .doc-hl .mi, .doc-hl .mf, .doc-hl .mh, .doc-hl .mo, .doc-hl .mb, .doc-hl .il { color: #b5cea8; }
|
||||
.doc-hl .c, .doc-hl .c1, .doc-hl .cm, .doc-hl .ch, .doc-hl .cs, .doc-hl .sd { color: #6a9955; }
|
||||
.doc-hl .o, .doc-hl .p { color: #d4d4d4; }
|
||||
.doc-hl .gh, .doc-hl .gu { color: #569cd6; font-weight: bold; }
|
||||
.doc-hl .gi { color: #b5cea8; }
|
||||
.doc-hl .gd { color: #ce9178; }
|
||||
.doc-hl .err { color: #f44747; }
|
||||
.documentation-content table { cursor: zoom-in; }
|
||||
#documentation-viewer.documentation-page-focus {
|
||||
position: fixed;
|
||||
@@ -171,6 +194,12 @@
|
||||
setTimeout(() => { copyButton.innerHTML = '<i class="mdi mdi-content-copy"></i> Kopieren'; }, 1500);
|
||||
});
|
||||
wrapper.appendChild(copyButton);
|
||||
if (pre.dataset.lang) {
|
||||
const label = document.createElement('span');
|
||||
label.className = 'doc-code-lang';
|
||||
label.textContent = pre.dataset.lang;
|
||||
wrapper.appendChild(label);
|
||||
}
|
||||
});
|
||||
document.addEventListener('keydown', event => {
|
||||
if (event.key === 'Escape' && viewer.classList.contains('documentation-page-focus')) closeViewer();
|
||||
|
||||
@@ -43,6 +43,15 @@
|
||||
table, figure, img, pre, blockquote { break-inside: avoid; }
|
||||
h1, h2, h3, h4 { break-after: avoid; }
|
||||
}
|
||||
.doc-hl .k, .doc-hl .kc, .doc-hl .kd, .doc-hl .kr, .doc-hl .kp, .doc-hl .ow, .doc-hl .nt, .doc-hl .bp { color: #0000ff; }
|
||||
.doc-hl .kn, .doc-hl .cp, .doc-hl .cpf { color: #af00db; }
|
||||
.doc-hl .kt, .doc-hl .nc, .doc-hl .nn, .doc-hl .ne { color: #267f99; }
|
||||
.doc-hl .nf, .doc-hl .fm, .doc-hl .nb, .doc-hl .nd { color: #795e26; }
|
||||
.doc-hl .n, .doc-hl .nv, .doc-hl .vi, .doc-hl .vg, .doc-hl .vc, .doc-hl .na, .doc-hl .py, .doc-hl .nl { color: #001080; }
|
||||
.doc-hl .s, .doc-hl .s1, .doc-hl .s2, .doc-hl .sa, .doc-hl .sb, .doc-hl .sc, .doc-hl .sh,
|
||||
.doc-hl .si, .doc-hl .sx, .doc-hl .sr, .doc-hl .ss, .doc-hl .dl, .doc-hl .se { color: #a31515; }
|
||||
.doc-hl .m, .doc-hl .mi, .doc-hl .mf, .doc-hl .mh, .doc-hl .mo, .doc-hl .mb, .doc-hl .il { color: #098658; }
|
||||
.doc-hl .c, .doc-hl .c1, .doc-hl .cm, .doc-hl .ch, .doc-hl .cs, .doc-hl .sd { color: #008000; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -15,6 +15,7 @@ dependencies = [
|
||||
"pypdf>=5,<7",
|
||||
"tabulate>=0.9,<1",
|
||||
"bleach[css]>=6.2,<7",
|
||||
"Pygments>=2.15,<3",
|
||||
"markdown>=3.7,<4",
|
||||
"django-tinymce>=5,<6",
|
||||
"pillow>=10,<13",
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"documentation_highlighting",
|
||||
Path(__file__).parents[1] / "netbox_documentation" / "highlighting.py",
|
||||
)
|
||||
highlighting = importlib.util.module_from_spec(spec)
|
||||
sys.modules[spec.name] = highlighting
|
||||
spec.loader.exec_module(highlighting)
|
||||
|
||||
|
||||
def test_highlights_markdown_fence_with_language():
|
||||
result = highlighting.highlight_code_blocks('<pre><code class="language-python">def f():\n return 1\n</code></pre>')
|
||||
assert 'class="doc-hl" data-lang="Python"' in result
|
||||
assert '<span class="k">def</span>' in result
|
||||
|
||||
|
||||
def test_highlights_tinymce_code_sample_and_keeps_escaping():
|
||||
result = highlighting.highlight_code_blocks('<pre class="language-markup"><code><b onclick="x">hi</b></code></pre>')
|
||||
assert 'data-lang="HTML"' in result
|
||||
assert "<b" not in result.replace("<span", "")
|
||||
assert "<" in result
|
||||
|
||||
|
||||
def test_plain_text_and_unknown_language_stay_untouched():
|
||||
for block in ('<pre class="language-none">interface Gi0/1</pre>', '<pre><code class="language-unknownlang">x</code></pre>'):
|
||||
assert highlighting.highlight_code_blocks(block) == block
|
||||
Reference in new issue
Block a user