soscripted / sox

Stack Overflow Extras: a userscript for the Stack Exchange websites to add a bunch of optional toggle-able features
http://stackapps.com/q/6091/
MIT License
72 stars 15 forks source link

Add line numbers to code blocks (use existing script) #410

Open SmartManoj opened 5 years ago

SmartManoj commented 5 years ago

Not maintained 5 years old, https://greasyfork.org/en/scripts/1781-so-code-line-nums

Updated one https://raw.githubusercontent.com/SmartManoj/SmartUserScripts/master/SO_Lines.user.js

shu8 commented 5 years ago

I'd be happy to accept a pull request for this, if you want to include it in SOX :)

SmartManoj commented 3 years ago

Any reason for the removal of that label? @mezmi

double-beep commented 3 years ago

Does this look good? Partly inspired from Stacks.

[...document.querySelectorAll('.s-prose pre')].forEach(codeBlock => {
    codeBlock.classList.add('s-code-block'); // add the stacks class in case it doesn't already exist
    // the last item of the array is just a newline and not an actual line of code
    const lineNumber = codeBlock.innerText.split(/\r?\n/).length - 1;
    // index is zero-based, so we need to increase by 1
    const lineDivs = [...Array(lineNumber).keys()].map(number => `<div>${number + 1}</div>`).join('');
    codeBlock.insertAdjacentHTML('afterbegin', `<code class="s-code-block--line-numbers">${lineDivs}</code>`);
});
shu8 commented 3 years ago

@double-beep that looks perfect! would you mind making a quick PR to add that in as a feature? :) /cc @SmartManoj!