Friday, November 28, 2008

On-The-Fly Syntax Highlighting

Having opened my blog recently I knew that I needed syntax highlighting for my code snippets in my blog. I found various offline tools to convert code to html, but as I'm changing code frequently I was looking for something more dynamic.

Google-code-pretty is what I came up with. A single javascript file contains the code for highlighting dozens of languages and a stylesheet defines the layout. Enabling syntax highlighting for your pages is simple matter of including the javascript and stylesheet file as external resources to your html tree. For simplicity these external resources can simply point to Google's online repository browser.

Enable syntax highlighting by adding the external resources to your html's head section.

<link href='http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.css' rel='stylesheet' type='text/css'/> <script src='http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.js' type='text/javascript'></script>

The links point to the head revision of the repository. So you stay up-to-date automatically. Finally trigger parsing of the document when it loads by refining the body tag:

<body onload="prettyPrint();">

Having syntax highlighting enabled simply wrap your code by using pre/code tags and assign the class "prettyprint":

Update: Turns out SyntaxHighlighter provides a similar functionality.