How-to: Add Code Syntax Highlighting to MediaWiki

Here’s a short tutorial on how to integrate Google’s “prettify.js” (which does automatic syntax highlighting of code snippets) into a MediaWiki wiki installation.

This is totally done MacGyver style, we’re going to patch the MediaWiki skin to do it.

For the purposes of the steps below, I’ll assume you’re using the standard “Monobook” skin, otherwise I’m sure it roughly applicable for other skins as well.

  1. Download a copy of prettify.js
  2. Unzip it and put the *.js and *.css files into a folder called “pretty“.
  3. Move the “pretty” folder into /your-mediawiki-root-folder/skins/monobook folder.
  4. You should now have a folder /your-mediawiki-root-folder/skins/monobook/pretty with all the code in it.
  5. We need to modify the file /your-mediawiki-root-folder/skins/MonoBook.php so open it up in your favourite text editor.
  6. Find the line “<?php $this->html(‘headlinks’) ?>” and add the two following lines:
    <link href=”<?php $this->text(‘stylepath’) ?>/monobook/pretty/prettify.css” type=”text/css” rel=”stylesheet” />
    <script type=”text/javascript” src=”<?php $this->text(‘stylepath’) ?>/monobook/pretty/prettify.js”></script>
  7. Find the line that starts “<body ” and change the line that immediately follows it to:
    onload=”<?php $this->text(‘body_onload’) ?>; prettyPrint();”
  8. Save “MonoBook.php”
  9. Now on any page where you wish to syntax-highlight code, use a <pre></pre> tag modified as such:
    <pre class=”prettyprint”>… your code….</pre>

Done!

This is a pretty hacked-up way of getting this working, so if someone knows of proper extension that does this let me know. Otherwise this is a great duct-tape solution for your team’s development wiki (if you’re using MediaWiki anyhow :P )

Related posts:

  1. Add Package (or Class) Filtering To Your Findbugs Ant Task
  2. Writing reflective unit tests to improve code quality

This entry was posted in IT, Software Engineering and tagged developer, documentation, Google, hack, web, wiki. Bookmark the permalink.

2 Responses to How-to: Add Code Syntax Highlighting to MediaWiki

  1. I done this way and works very well, you can even choose the language you wanto to highlight.

    I used the manual instalation, just folowed the instructions (mode 2 manual) and it was a home run!

    http://www.mediawiki.org/wiki/Extension:SyntaxHighlight_GeSHi

  2. Akzhan says:

    New MediaWiki extension just released – GoogleCodePrettify.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>