Thursday, October 15, 2009

Code in Blogger

So, I've been looking for a way to make my code examples in blog posts more readable. I had tried to use the hosted version of SyntaxHighlighter, but couldn't seem to get it working right (I'm sure it was something simple) and it needed several lines added to the Blogger html template. Instead, I've opted to use google-code-prettify. Though it doesn't support as many languages (in particular no groovy), all I needed was 2 lines pasted into the template, and making it load the class when the body element is. Couldn't be simpler. I followed the instructions (slightly tweaked) from here. Thanks Luka.

These are the lines you need (anywhere in head tag):
<link href="http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.js" />
Then modify body tag to load the script:
...
<body onload='prettyPrint()'>
...
Use:
<pre class="prettyprint" style="overflow:auto;">
  <!-- Your code goes here -->
</pre>
You don't need to specify the language since the script will guess, but you can if you like:
<pre class="prettyprint lang-html">
  <!-- HTML code here -->
</pre>
The lang-* class specifies the language file extensions. File extensions supported by default include "bsh", "c", "cc", "cpp", "cs", "csh", "cyc", "cv", "htm", "html", "java", "js", "m", "mxml", "perl", "pl", "pm", "py", "rb", "sh", "xhtml", "xml", "xsl".

I've gone back and added the syntax highlighting to all my code examples in previous posts.