Sunday, April 01, 2007

Google Code Prettify

While working on a completely different post regarding subtle bugs surfacing in a Java 1.4 to 5 migration, I asked myself whether there was simple way of getting code samples to be syntax-highlighted on my blog. Pure CSS would not work, unless the code samples were completely messed up with spans and divs to indicate which style to apply to every word, number or punctuation.

This could have been done with tools like Java2Html, but it generates lots of font tags instead of CSS based style instructions.

Looking around I found Google-Code-Prettify, a combined JavaScript and CSS solution to my problem. It turns out to be very easy to use, you just have to specify a class="prettyprint" to your pre blocks and activate the JavaScript via the body tag's onLoad hook. It will then try and guess which language any "prettyprinted" pre block contains and format it according to a stylesheet you may modify to fit into your site's layout. The number of languages recognized is impressive, even though I would have been satisfied with Java alone :)

I will probably go back though my posts that contain code samples and update them. New posts will of course be "prettified" right from the start.

No comments: