Monday, January 24, 2011

Syntax highlighting code in Blogger

Posting code in Blogger by default results in something that is inexcusably ugly.  How can you make code posted in blogger look pretty?  For me, syntax highlighting and scrollable text boxes are a must.

The solution is: google-code-prettify, which does the highlighting for code.google.com (you could also consider SyntaxHighlighter).  Now the next problem is, how do you distribute the javascript and CSS for prettify?  Unfortunately Google doesn't make it available via their CDN like they do for other libraries like jQuery.  This would obviously be the best option for users since:
  • it would negate the need for additional hosting; and 
  • minimise load time since browsers could cache the code across many sites, and if needed download it from the closest CDN node.
So the remaining options are to slap it into your blogger template, host it yourself somewhere (like Google pages), use the subversion browse code link (ick), or figure out what code.google.com does, since it uses the same code. 

I opted for the last option, which works a treat.  Put this in your blogger template, right after the <head> tag:

<link type="text/css" rel="stylesheet" href="http://www.gstatic.com/codesite/ph/3799605220899551948/css/ph_core.css">
 
<link type="text/css" rel="stylesheet" href="http://www.gstatic.com/codesite/ph/3799605220899551948/css/ph_detail.css" >
 
<link type="text/css" rel="stylesheet" href="http://www.gstatic.com/codesite/ph/3799605220899551948/css/d_sb_20080522.css" >

Then add an onload event to the body tag to call the PrettyPrint function:

<body onload="prettyPrint()" >

and, since the prettyprint CSS doesn't give you a scrolling box by default (!?), add this to the CSS in your template to avoid your code being chopped off:

/* Override prettyprint CSS, which doesn't allow scrolling box */
pre.prettyprint {
  overflow: auto;
}

Once you have done all that, you just need to wrap the code in your posts in:

<pre class="prettyprint">
</pre>

In summary, much harder than it needs to be. Blogger team, please build this functionality in!

No comments: