Blog About Contact

How-to: Add Code Syntax Highlighting to MediaWiki

Published Tue, 6 Apr 2010 • 2 comments

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>


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 )

About the Author

Richard Nichols is an Australian software engineer with a passion for making things.

Follow him on twitter or subscribe by RSS or email.

You might also enjoy reading -

Discuss / Comment

There are 2 comments.

Add a comment

  • {{e.error}}

Thanks for your comment!/

Valid email address required.
Posting message, please wait...