Skip to content

Commit 1e3e788

Browse files
committed
nav.js: add highlight.js for syntax blocks on reference/example pages
1 parent aafffe0 commit 1e3e788

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

assets/nav.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,40 @@
8686
s.src = SITE + '/assets/search.js';
8787
document.head.appendChild(s);
8888
}
89+
90+
// Syntax highlighting on reference/example pages
91+
if (!document.getElementById('hljs-css') &&
92+
document.querySelector('.syntax-block, .impl-block, .cm-static-wrap')) {
93+
const lnk = document.createElement('link');
94+
lnk.id = 'hljs-css';
95+
lnk.rel = 'stylesheet';
96+
lnk.href = 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-light.min.css';
97+
document.head.appendChild(lnk);
98+
99+
const lnkDark = document.createElement('link');
100+
lnkDark.id = 'hljs-css-dark';
101+
lnkDark.rel = 'stylesheet';
102+
lnkDark.href = 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css';
103+
lnkDark.disabled = true;
104+
document.head.appendChild(lnkDark);
105+
106+
const scr = document.createElement('script');
107+
scr.src = 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js';
108+
scr.onload = function() {
109+
document.querySelectorAll('.syntax-block, .impl-block, .cm-static-wrap code').forEach(el => {
110+
el.innerHTML = el.innerHTML
111+
.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&');
112+
el.classList.add('language-cpp');
113+
hljs.highlightElement(el);
114+
});
115+
// Apply dark if already in dark mode
116+
if (document.body.classList.contains('dark-mode')) {
117+
document.getElementById('hljs-css').disabled = true;
118+
document.getElementById('hljs-css-dark').disabled = false;
119+
}
120+
};
121+
document.head.appendChild(scr);
122+
}
89123
// Dark mode via CSS class
90124
(function() {
91125
if (!document.getElementById('dark-mode-style')) {
@@ -181,6 +215,10 @@
181215
}
182216
if (window.editor && window.editor.setOption)
183217
window.editor.setOption('theme', on ? 'cppmode-dark' : 'cppmode');
218+
const hljsLight = document.getElementById('hljs-css');
219+
const hljsDark = document.getElementById('hljs-css-dark');
220+
if (hljsLight) hljsLight.disabled = on;
221+
if (hljsDark) hljsDark.disabled = !on;
184222
try { localStorage.setItem('darkMode', on ? '1' : '0'); } catch(e) {}
185223
}
186224
window.__toggleDark = function() {

0 commit comments

Comments
 (0)