Syntax highlighting of code examples in Movable Type

Another small change I did to my blog recently: enhancing the layout of code-example blocks and adding syntax highlighting to them. As this has been no big deal but still involved some tricky parts I'm documenting my results for the interested audience.

First start with downloading the code prettify javascript module from the google-code-prettify project page. This is a javascript module which allows to dynamically add syntax highlighting to <pre> or <code> tags in your webpages which are marked with the attribute class="prettyprint". Movable Type allows very easy creation of <code>-blocks with its Markdown-syntax for code blocks. Since these are not identified with the needed class-attribute we have to implement a workaround but more on that shortly.

From the downloaded package I took the files prettify.css and prettify.js. Open the file prettify.js and add the following code at the bottom of the file:

function prettifyCodeTags() {
  var codes=document.getElementsByTagName('code');
  for (var i=0;i<codes.length;i++){
    codes[i].className = "prettyprint " + codes[i].className;

This is now the code which parses all the <code>-tags on the page and adds the class "prettyprint" to each tag. It is neccessary to enable the syntax highlighting without modifying the highlighting-code itself which would be much more difficult.

The next step is to put these two files on the website so that they can be included by the other files. I have created two index templates containing the contents of those files for that reason but if you just upload the files to your webpage that's fine too I guess.

Now all templates which could include <code>-sections have to be modified to call the prettifying-JavaScript-function. To include the files add following lines to all appropiate header-sections in your templates:

<link href="prettify.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="prettify.js"></script>

Finally this modification to the <body>-tags in the templates enables the syntax highlighting upon the onLoad()-event of the webpage which occours when the page has finished loading.

<body onload="prettifyCodeTags()">

That's it. If you republish your site now all code-blocks should be syntax-highlighted automatically. Combined with the easy creation of code-blocks with the Markdown-Format available in Movable Type it cannot get much easier I guess.

Thanks Google for this little module :)


Similar entries