james mckay dot net
because there are few things that are less logical than business logic

Code syntax highlighting in WordPress

I’ve been thinking a bit recently that many other programmers’ blogs do a much better job of handling code snippets than mine does. Since time immemorial I’ve been using a very simple plugin called Code Auto Escape, which merely allows you to type code verbatim into your posts without having to go through all the rigmarole of HTML encoding them. I’ve never looked for anything fancier mainly because I never got round to it.

However, if you are geeky enough to post code on your blog in the first place, you need to do it properly, and that means syntax highlighting. Fortunately, it’s a simple case of finding and installing the right WordPress plugin. So, this morning, I finally got round to doing a bit of googling for one.

There are several such plugins to choose from. Most of them are based on GeSHi, a popular and very well supported PHP library which offers syntax highlighting for almost every programming language you can think of. It runs on the server, injecting extra markup into your code to achieve the desired effect.

In the end I settled for Syntax Highlighter. It takes a different approach, using JavaScript in your browser to render the highlighting and add a little toolbar at the top of each snippet with options such as copying it to the clipboard:

var highlightColour = "#ffff00";
var normalColour = "#ffffff";

$(document).ready(function() {
  $("#my-table tr").hover(
    function() {
      $(this).css("background-color", highlightColour);
    function() {
      $(this).css("background-color", normalColour);

Personally I think this is a better, cleaner approach: it delegates the heavy lifting involved from the server to your browser, and reduces the size of the markup in your posts. It is also semantically cleaner: while the output from GeSHi is valid XHTML strict, it does jumble up content and presentation a bit, which is the reason why table-based layouts, the tag and inline CSS tend to be frowned upon these days.

Unfortunately, none of these plugins address the biggest problem with writing code on your blog: that it is so fiddly and awkward with a rich text editor. Both Windows Live Writer and TinyMCE in WordPress take a perverse delight in messing up your indentation, your line breaks, and sometimes even with what gets HTML encoded and what doesn’t.