diff --git a/netbox_documentation/highlighting.py b/netbox_documentation/highlighting.py new file mode 100644 index 0000000..6599db4 --- /dev/null +++ b/netbox_documentation/highlighting.py @@ -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 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"[^>]*)>(?:[^>]*)>)?(?P.*?)(?:)?", re.S) +_LANGUAGE = re.compile(r'class="[^"]*\b(?:lang|language)-(?P[\w+#.-]+)') +_BR = re.compile(r"", 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'
{highlighted}
' + + +def highlight_code_blocks(value): + return _PRE.sub(_replace, value) diff --git a/netbox_documentation/models.py b/netbox_documentation/models.py index f5d9ac4..fa73a1e 100644 --- a/netbox_documentation/models.py +++ b/netbox_documentation/models.py @@ -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): diff --git a/netbox_documentation/templates/netbox_documentation/document.html b/netbox_documentation/templates/netbox_documentation/document.html index b524771..e28e8d8 100644 --- a/netbox_documentation/templates/netbox_documentation/document.html +++ b/netbox_documentation/templates/netbox_documentation/document.html @@ -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 = ' 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(); diff --git a/netbox_documentation/templates/netbox_documentation/document_print.html b/netbox_documentation/templates/netbox_documentation/document_print.html index 2963afe..06b5f51 100644 --- a/netbox_documentation/templates/netbox_documentation/document_print.html +++ b/netbox_documentation/templates/netbox_documentation/document_print.html @@ -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; } diff --git a/pyproject.toml b/pyproject.toml index 97c8ae8..8f5b02d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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", diff --git a/tests/test_highlighting.py b/tests/test_highlighting.py new file mode 100644 index 0000000..6edd660 --- /dev/null +++ b/tests/test_highlighting.py @@ -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('
def f():\n    return 1\n
') + assert 'class="doc-hl" data-lang="Python"' in result + assert 'def' in result + + +def test_highlights_tinymce_code_sample_and_keeps_escaping(): + result = highlighting.highlight_code_blocks('
<b onclick="x">hi</b>
') + assert 'data-lang="HTML"' in result + assert "interface Gi0/1', '
x
'): + assert highlighting.highlight_code_blocks(block) == block