I’ve been using the Google Code Prettify plugin for my code samples, which is nice for syntax highlighting, but still lacks something I think every code sample should have: line numbers.
I didn’t want to have to add them manually to every code sample I put up, so I came up with a quick solution to auto-generate line numbers with JavaScript. Because I wanted a quick solution, this code uses jQuery for all the heavy lifting.
Here it is, complete with line numbers:
$(document).ready( function() { $("pre.prettyprint").each( function() { var code = $(this).html(); code = escape(code); // %0A is a line feed, %0D is a carriage return if (code.indexOf("%0D%0A") > -1) { linecount = code.match(/%0D%0A/g).length; } else if (code.indexOf("%0A") > -1) { linecount = code.match(/%0A/g).length; } else if (code.indexOf("%0D") > -1) { linecount = code.match(/%0D/g).length; } code = unescape(code); var linenumbers = 1; for (i = 1; i < linecount; i++) { linenumbers += "<br />" + (i + 1); } $(this).before("<pre class=\"linenumbers\">" + linenumbers + "</pre>") } ); } );
And then this little bit of CSS so it matches the prettify.css that comes with the Google Code Prettify plugin:
pre.linenumbers { width: auto; background-color: #EEE; border-width: 1px 0 1px 1px; border-style: solid; border-color: #888; float: left; margin: 0; padding: 2px 4px; color: #888; text-align: right; }
I purposefully keep the numbers in a separate element from the code, so they don’t interfere when you try to copy the code samples to your clipboard.
And there you have it. Now I can easily reference specific line numbers in my code.
Really like this!
I found a problem with IE not appending appending %0A to the final line and added this after line 7:
var lastChars = code.substring(code.length-3, code.length);
if(lastChars != "%0A" && lastChars != "%0D")
{
code += "%0D%0A";
}