I've thought about creating my own syntax highlighter. I've been using Chili, but there are some odd bugs that pop up here and there and it doesn't seem to play well with Chrome. And it hasn't been updated in 2 years.
One thing I did want was line numbering, but that's been a bugaboo of syntax highighlighters for a long time—you want the numbers but do not want them copied when code is selected. Firefox copies the numbers when using <li>
elements, and tables or inserted text will also copy everything. The answer seems to be using :before
to insert the line numbers, since that text won't be copied in any modern browser (IE 8 and below don't support :before
, but we won't worry about that).
The issue then is how to tell CSS about the lines. We want to wrap them in <span>
s, as so:
<pre>
<span class=line>This is a <em>text</em></span>
<span class=line>This is the second line</span>
</pre>
And number everything with CSS:
pre.test1 {
counter-reset: linecounter;
}
pre.test1 span.line{
counter-increment: linecounter;
}
pre.test1 span.line:before{
content: counter(linecounter);
width: 2em;
display: inline-block;
border-right: 1px solid black;
}
And this is the result, exactly as desired.
This is a text
This is the second line
The keys in the CSS are lines 1 and 4 that set up the counter (change line 1 to linecounter 4
to start the numbering at 5 (counter-increment
increments before displaying)) (change linecounter
to anything you want as long as its consistent). Line 7 displays the value of the counter in the :before
pseudoelement, and lines 8-10 are just old-fashioned styling to make it prettier. You of course would want to add some padding, margin, odd/even backgrounds etc., but that's old hat.
Continue reading ‘Line Numbering in <pre>
Elements’ »