Monday 8 February 2010

Blogger.com code syntax highlighting, or always remember to save your code before you start playing around with it!

I've decided to re-vamp the look of this blog to give it more width and make the code fragments easier to read. I hope you like the new look!

When doing this I made one of the oldest mistakes in the programmer's book: I didn't save my work!

This meant I had to add all the site specific code to render the code in syntax-highlighted format, and add Google analytics tracking code back into the HTML, which whilst not the worst job in the world, did take me some time to remember what I had done. REMEMBER TO SAVE YOUR WORK!

This does give me the opportunity to thank the author of the fabulous syntax highlighter for Blogger.com that I have used, which can be found here: http://alexgorbatchev.com/wiki/SyntaxHighlighter. Thank you very much Alex, it's a superb bit of code!

The code I used to enable the nifty highlighter for C# should be pasted into the HEAD section of your blog:


<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'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js' type='text/javascript'></script>
<!-- add brushes here -->
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJScript.js' type='text/javascript'></script>

<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushBash.js' type='text/javascript'></script>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushSql.js' type='text/javascript'></script>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushXml.js' type='text/javascript'></script>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCpp.js' type='text/javascript'></script>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCSharp.js' type='text/javascript'></script>
<script type='text/javascript'>
  SyntaxHighlighter.config.bloggerMode = true;
  SyntaxHighlighter.all();
</script>


To use it, make sure that the code you want to display has been HTML escaped (which can be done using the utility available here: http://www.string-functions.com/htmlencode.aspx.

Now, to use this, just paste your escaped code into your blog and wrap it in the following HTML tags:
<pre class="brush:csharp">
   ...your code here...
</pre>

Note that this will work for C Sharp code. For other types of code highlighting, simply change the brush type in the <pre> tag, and make sure the appropriate brush is included in the list of brish types defined in the code above in the "!-- add brushes here --" section.

1 comment: