// #167: with line wrapping on, a logical line can occupy several visual // lines; the gutter must show one number per VISUAL line. Per-line spans // give each logical line its own box so its height identifies the wrapped // row count; blank gutter rows keep numbers aligned with line starts. (function () { var body = document.getElementById('codebody'); var gutter = document.getElementById('gutter'); var code = document.getElementById('code'); if (!body || !gutter || !code) return; var wrapOn = function () { return document.documentElement.hasAttribute('data-wrap'); }; // Wrap each logical line (split on newline; spans never contain newlines // because HighlightCode highlights per line) in a .codeline block. The // blocks must be adjacent with NO newline text between them (#194): // .codeline is display:block, and under pre-wrap each interleaved '\n' // text node renders as an extra phantom row in the code column that // renumber() does not count, drifting the gutter off alignment on // wrapped lines. Blank lines become empty blocks; .codeline:empty keeps // them one row tall (see app.css). function splitLines() { var html = body.innerHTML; var parts = html.split('\n'); var out = []; for (var i = 0; i < parts.length; i++) { out.push('' + parts[i] + ''); } body.innerHTML = out.join(''); } function renumber() { var lines = body.querySelectorAll('.codeline'); var s = ''; if (wrapOn() && lines.length) { // Each logical line block occupies rows = height / line-height when // wrapped; its number sits on the first row and the remaining rows get // blank gutter lines so numbers stay aligned with line starts. // The gutter has a fixed CSS width now (.code .gutter), so its row // count never changes the code column width: measurement is stable // with no measurement/layout feedback. var lh = parseFloat(getComputedStyle(body).lineHeight) || 1; gutter.textContent = ''; var frag = document.createDocumentFragment(); for (var i = 0; i < lines.length; i++) { var num = document.createElement('span'); num.className = 'gutline'; num.textContent = String(i + 1); frag.appendChild(num); var rows = Math.max(1, Math.round(lines[i].getBoundingClientRect().height / lh)); for (var r = 1; r < rows; r++) { var blank = document.createElement('span'); blank.className = 'gutline'; blank.textContent = '\u00a0'; frag.appendChild(blank); } } gutter.appendChild(frag); } else { for (var k = 1; k <= lines.length; k++) s += k + '\n'; gutter.textContent = lines.length ? s.slice(0, -1) : '1'; } } splitLines(); renumber(); // Re-renumber on toggle (theme.js toggles data-wrap on ) and on any // size change (paste of lots of text, window resize, zoom). var mo = new MutationObserver(renumber); mo.observe(document.documentElement, { attributes: true, attributeFilter: ['data-wrap'] }); if (window.ResizeObserver) { var ro = new ResizeObserver(function () { renumber(); }); ro.observe(body); } else { window.addEventListener('resize', renumber); } })();