Skip to content

Commit

Permalink
add line numbers after document is loaded, instead of relying on the …
Browse files Browse the repository at this point in the history
…'complete' hook of Prism.js, which can be problematic when a code block contains sub-blocks (a problem beyond my understanding)
  • Loading branch information
yihui committed Nov 6, 2024
1 parent 2036433 commit 5e06d19
Showing 1 changed file with 2 additions and 7 deletions.
9 changes: 2 additions & 7 deletions js/code-line-numbers.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@
(() => {
function addNum(el) {
const s = '<span data-line-number=""></span>', sel = 'span[data-line-number]';
if (!el.classList.contains('line-numbers') || el.parentNode.tagName !== 'PRE'
|| el.querySelector(sel)) return;
if (el.querySelector(sel)) return;
el.innerHTML = s + el.innerHTML.replace(/\n(?=.|\s)/g, '\n' + s);
let n1 = +el.dataset.start; if (isNaN(n1)) n1 = 1;
const spans = el.querySelectorAll(sel), w = ('' + (n1 - 1 + spans.length)).length;
Expand All @@ -13,9 +12,5 @@
sp.dataset.lineNumber = n;
});
}
function addAll(e) {
e ? (e.grammar && addNum(e.element)) :
document.querySelectorAll('pre > code.line-numbers:first-child').forEach(addNum);
}
window.Prism?.hooks ? Prism.hooks.add('complete', addAll) : addAll();
addEventListener('load', e => document.querySelectorAll('pre > code.line-numbers:first-child').forEach(addNum));
})();

0 comments on commit 5e06d19

Please sign in to comment.