Wednesday, January 30, 2013

SyntaxHighlighter at Blogger

Running a tech/developer blog means I will be posting source code and other technical text. This requires proper syntax highlighting and use of monospaced fonts. Unfortunately blogger.com doesn't really support this out of the box so we need to resort to 3rd parties. Alex Gorbatchev created an awesome syntax highlighter purely in javascript. This means it doesn't need a server side component and we can easily integrate it into blogger.

To integrate SyntaxHighlighter into blogger you have to edit the HTML of your template:
how to get to editing your blogger template

Next you have to insert some javascript and CSS just after the title tag:
editing the template html

Here is the snippet I inserted:
<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js" type="text/javascript"></script>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJava.js' type='text/javascript'></script>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushXml.js' type='text/javascript'></script>
<script type='text/javascript'>
  SyntaxHighlighter.config.bloggerMode = true;
  SyntaxHighlighter.defaults['auto-links'] = false;
  SyntaxHighlighter.defaults['tab-size'] = 2;
  SyntaxHighlighter.defaults['toolbar'] = false;
  SyntaxHighlighter.all();
</script>
<link href="http://alexgorbatchev.com/pub/sh/current/styles/shCore.css" rel="stylesheet" type="text/css">
<link href="http://alexgorbatchev.com/pub/sh/current/styles/shThemeDefault.css" rel="stylesheet" type="text/css">

The first line loads the core javascript and then I load the javascript for each type of brush I intend to use. A full list of brushes/syntax files and the required javascript can be found at Alex' site.

After loading the brushes there are a few lines of inline javascript. Prior to running the SyntaxHighlighter with SyntaxHighlighter.all() I enable bloggerMode as we are using this at blogger.com and I setup defaults. Documentation on configuration of the highlighter itself and defaults for each highlighted element can be found at Alex' site. You might want to tweak these for your site.

Finally I add the core css file to the page as well as a css file with the theme I choose. You can pick your own theme that matchs your site.

Finally, please consider hosting these files on your own server (although that can't be blogger). If you are using the files hosted by Alex himself, as in the examples, please consider making a donation to cover his bandwidth costs and to show your appreciation with the work he's done.

1 comment:

  1. It took me several tries to integrate SyntaxHighlighter into my Blogger template. Your instructions worked. Thanks.

    ReplyDelete

Comments might be held for moderation. Be sure to enable the "Notify me" checkbox so you get an email when the comment is accepted and I reply.