Syntax highlighting on web pages

Added on: Wednesday 24th August 2011

I've recently been looking at various solutions for highlighting code snippets as I wanted something to make it easier to publish on this blog. I've settled on highlight.js as it is so simple.

Part of the reason I haven't published an article for a while is that I wanted a better way of displaying the code than I had before. (The other reason is lack of time!)

highlight.js is a javascript library releases by Software Maniacs and setting it up couldn't be easier because it automatically recognises the scripting language - well, as long as you use one of the 41 that it knows about.

To add the feature to a web site you just have to reference a script file and a stylesheet. These are both hosted on external servers so you don't even need to download them.

The javascript reference is:

<script src="http://yandex.st/highlightjs/6.0/highlight.min.js"></script>

and the stylesheet reference is:

<link rel="stylesheet" href="http://yandex.st/highlightjs/6.0/styles/default.min.css">

If you want a style other than the default just replace default in the url above with the name of the style. (see the site for available styles).

Thats about it, except that you have to initialise the script when the page loads - after that it will format any code within <pre><code> tags.

I had a slight problem here in that I use WymEditor for my blog which doesn't easily allow me to wrap text within these two elements.

However, a bit of jquery soon sorted this. Within the editor, I give any code a class of code_block. The jquery then goes to work on each element with this class and wraps the contents in <pre><code> tags.

I've included the script below (because I can highlight it now!)

$("p.code_block").each(function(){
var txt = $(this).html();
$(this).replaceWith('<pre><code>'+txt+'</code></pre>');
});

Except I've found a problem. As the code above contains < and > characters to show the html being output, it isn't formatted. If I take that line out it recognises it as javascript

comments powered by Disqus