Monday, May 25, 2009

Pretty printing code in Blogger

If like me you need to paste in chunks of code into your blog, then it's nice to have it looking similar to how it looks in your code editor. Theres a project called SyntaxHighlighter which does just that. It's a bunch of css, javascript and image files which apply the code formatting on the clientside. Previously on my self hosted wordpress blog it was quite easy to upload the required files and change the site template. Unfortunately this isn't possible with a hosted account, however luckily its still easy enough to get this working in Blogger.

This trick involves linking directly to the javascript files on the projects webpage. The idea came from urenjoy, which at first I was thoroughly reluctant to do, which was linking to the files in the google code trunk. However that was for v1.5, with version 2.x we are a little luckier:


A big thumbs up to alex for allowing us to do this!


  1. Go to the Layout tab, and select Edit HTML.
  2. Paste the contents of shCore.css and shThemeDefault.css straight into the skin section of the template.
  3. Add the script code shCore.js shBrushPlain.js and the brushes you will want into the head section.
  4. Add the necessary syntax highlighter configuration javascript into the body section.

Here's a rough example of how it should look:

<b:include data='blog' name='all-head-content' />


    /*  Theres probably a bunch of code for your theme here, leave it as-is */

    [paste the contents of here]
    [paste the contents of here]


    <script src='' type='text/javascript'/>
    <script src='' type='text/javascript'/>
    <script src='' type='text/javascript'/>
    <script src='' type='text/javascript'/>
    <script src='' type='text/javascript'/>
    <script src='' type='text/javascript'/>
    /* You can add more brushes from */


    /* You can paste the below right after the body tag. */
    <script language='javascript'>
            SyntaxHighlighter.config.clipboardSwf = &#39;;
            SyntaxHighlighter.config.bloggerMode = true;
            SyntaxHighlighter.config.gutter = false;

You will need to avoid messing with your blog theme within the template. I would recommend copying the template into an editor, adding the changes, then copying it all back to save. I hope that makes things easier for you.

Oh and as mentioned in the below posts, you will need to HTML encode the code you wish to embed or any angle brackets will screw up the site template etc...!

To actually prettify some code you will need to wrap it in pre tags whilst specifying which brush (code style) to use. You can get a full list of brushes here.

<pre class="brush:xml">
... code here

Here a couple of links which aided me in my quest, although I wrote this post to bring the information up to date with SyntaxHighlighter 2.0 and hopefully slightly easier to follow. Good luck.

No comments:

Post a Comment