Line numbers alongside blocks of code are handy; you can refer to
them by number instead of saying things like “the second
if statement in your third loop”.
However often they get in the way when selecting code to cut and paste. This is an attempt to solve that problem.
The code
Here's how it looks. Try cut & pasting and see what you get:
You can download it here.
Minimal CSS:
Design Constraints
- Numbering must be automatic. My
<pre>blocks come from various sources; I don't want to modify them all. In practice this means having javascript go and find all the blocks of code, and add numbering to them. - The code must be selectable without also selecting the line numbers. If the line numbers are also selected, they must be visually hilighted (else you'd get a surprise when pasting!)
- Simple to maintain vertical alignment. If it's complex, it will go wrong.
- The gutter must scale in width according to the number of digits; fixed-width gutters look silly for short fragments of code, and they look worse for very large line numbers spilling over into the code itself.
I tried a few different approaches (which I've seen around), rejected as follows:
- Why not have the line numbers dynamically disabled with a button or somesuch?
- This is clutter.
- Why not use
<li>'s numbering? - I did try this; it turned out you could select it (in firefox) accidentally, without it being hilighted. Confusing!
- Why not use
:before { content: '123'; }for the numbering? - I tried that; the end effect is identical to simply outputting numbers as text.
- Why not generate the line-number
<div>server-side? - Because of my first design constraint.
This was adapted from somebody else's attempt at the same thing.
One place this sees use is in conjuction with my
PreCodeBrowserPlugin
for Trac. Together, they give selectable code for Trac's source
code browser. Additionally, the line numbering is great for Trac's
{{{ ... }}} wiki syntax used for snippets of code on
wiki pages and in blog entries.