From 5e06d19abeea432b98fc670a864a56790a659c13 Mon Sep 17 00:00:00 2001 From: Yihui Xie Date: Wed, 6 Nov 2024 09:47:37 -0600 Subject: [PATCH] add line numbers after document is loaded, instead of relying on the 'complete' hook of Prism.js, which can be problematic when a code block contains sub-blocks (a problem beyond my understanding) --- js/code-line-numbers.js | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/js/code-line-numbers.js b/js/code-line-numbers.js index fc6234f..4ccfb6f 100644 --- a/js/code-line-numbers.js +++ b/js/code-line-numbers.js @@ -2,8 +2,7 @@ (() => { function addNum(el) { const s = '', 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; @@ -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)); })();