It appears that the recent syntax highlighting enhancements to Google Code’s source browser are implemented with a slightly modified version of Mike Samuel’s JavaScript Code Prettifier: a 100% browser-side JavaScript/CSS syntax highlighting engine with a sufficiently simple implementation (~750 LOC / 37KB unpacked / 12KB gzipped), a liberal license, and decent language support. The README claims that C (and friends), Java, Python, Bash, SQL, HTML, XML, CSS, JavaScript, and Makefiles are highlighted well and
Ruby, PHP, Awk, and Perl are handled passably. As luck would have it, I just went through the process of wiring this script up last week with a few interesting tweaks to get automatic highlighting on all my posts.
The prescribed usage was fairly simple: bring in the stylesheet and external script, add a “prettyprint” class to
and/or blocks, and call prettyPrint() on load/ready.
This setup has a few (easily remedied) drawbacks, however:
Manually adding a “prettyprint” class is a bit of a pain with
Markdown since there’s no way to add a class name to a code block.
Manually adding a “prettyprint” class is a bit of a pain because I don’t
feel like flipping through looking for every post I’ve ever written with
a code block in it.
Adding prettifier.js to a all pages means a 37K download
even when no syntax highlighting is required.
The stock stylesheet’s color palette is somewhat lacking.
Making it Automatic
The following wee bit of code is running on each page to automatically highlight all code blocks on the page. I used jQuery but this should be easily ported to other JavaScript libraries or standard DOM.
$(document).ready(function() {
// add prettyprint class to all
blocks
var prettify = false;
$("pre code").each(function() {
$(this).addClass('prettyprint');
prettify = true;
});
// if code blocks were found, bring in the prettifier ...
if ( prettify ) {
$.getScript("/js/prettify.js", function() { prettyPrint() });
}
});
We run through the DOM after a page is fully loaded and look for elements nestled within a
(this is what Markdown puts out for code blocks). We add the “prettyprint” class to each of the elements and note that the prettifier is required. Lastly, we use jQuery’s getScript method to bring in the prettifier but only if we’ve detected that it’s required (jQuery.getScript is implemented by appending a tag to