Real Ultimate Programming

The Home for People Who Like to Flip Out and Write Code

Syntax Highlighting on Blogger

You may have noticed that my code blocks are suddenly syntax-highlighted. You might think a tech-oriented company like Google would have included something like this by default, but you’d be wrong.

My new syntax highlighting comes courtesy of highlight.js, which is great, although it does have some holes in the English documentation. Unfortunately, I couldn’t find any place it was being hosted for free, so I needed to set up a place of my own from which to serve it. Enter Google App Engine.

App Engine is Google’s entry into the cloud computing space; if you write your application according to their guidelines, Google will run it on their infrastructure. As such, it is massive overkill for serving up static files, but it’s free and it has good reporting tools. So I followed the “Hello, World!” documentation, added the files for highlight.js, then modified my pp.yaml to add handler for serving static files.

- url: /
 static_dir: highlight

Note that this conflicts with the handler from “Hello, World!”; since I didn’t want to serve up “Hello, World!” anyway, I just deleted the other handler.

According to the documentation for highlight.js, all you should have to do now is add one simple block of Javascript:

<script src="$PATH_TO_HOSTED_JS" type="text/javascript"></script>
<script type="text/javascript">

This is technically accurate: this will cause the markup to be modified to support syntax highlighting. That’s not enough for the highlighting to take place, however; you still need to bring in the CSS for the highlighting style you want to use (my two favorites are Sunburst and IDEA).

<link href="$PATH_TO_HOSTED_CSS" rel="stylesheet"/>

On Blogger, the best place to put this code is in the raw HTML for your template; that way you don’t have to remember to include it in individual posts that will have code blocks. One final note: your code blocks have to be marked up by nesting a code tag inside a pre tag—if you’ve done something silly like nesting a pre tag inside a code tag, it won’t work. Here’s an example of the proper style:

#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
print "Hello, World!"

Back to flipping out…