My Technical Notes

Sunday, 21 March 2010

Setting up Alex Gorbatchev's Syntax Highlighter on Blogger

I am no longer using Alex Gorbatchev's Syntax Highlighter. I have instead converted by blog to use Highlight Js because it supports more languages and is enjoying an upswing in popularity, which means better maintenance and quicker updates.

Because my blog posts are essentially technical notes, I found a need to include code samples, especially in C#. Currently, the syntax highlighter most in vogue is Alex Gorbatchev's Syntax Highlighter. Here is an example of what it is capable of:

foreach (var str in new List<string> { "Hello", "World" })
{
   Console.Write(str);
   Console.Write(" ");
}

I had a bit of trouble setting it all up as I have no real website to host the Syntax Highlighter source files. Since I am a cheapskate, I ended up using Google Sites. Be aware though, that Google Sites is slow so your blog may take longer to load. If you do not want to go through the bother of uploading the source files you can instead use the files I have uploaded instead (as I describe below).

Below are steps that you would need to follow in order to set it up on Blogger.

1. Download the Syntax Highlighter source files and upload them to a location on the web. I am assuming that you have uploaded it to SITE/syntaxhighlighter where SITE is your website address. Inside the syntaxhighlighter folder you should have three sub-folders: scripts, styles and src. (I am using Syntax Highlighter 2.1.364).

If you do not wish to upload the files yourself you can instead replace `SITE` with


http://sites.google.com/site/tahassan 
in what follows.

2. In Blogger, click on Settings -> Formatting and set "Convert Line Breaks" option to No.

3. In Blogger, click on Layout -> Edit HTML. Here you want to add the following under the <head> element:


<link href='SITE/syntaxhighlighter/styles/shCore.css' rel='stylesheet' type='text/css'/>
<link href='SITE/syntaxhighlighter/styles/shThemeDefault.css' rel='stylesheet' type='text/css'/>
<script src='SITE/syntaxhighlighter/scripts/shCore.js' type='text/javascript'/>
<script src='SITE/syntaxhighlighter/scripts/shBrushCSharp.js' type='text/javascript'/>
<script type='text/javascript'>
  SyntaxHighlighter.config.clipboardSwf = 'SITE/syntaxhighlighter/scripts/clipboard.swf'; 
  SyntaxHighlighter.all(); 
</script>
(Replace SITE with the address of your actual site.)

4. To write a code sample you merely have to write:


<script type='syntaxhighlighter' class='brush: c#; wrap-lines: false'>
foreach (var str in new List<string> { "Hello", "World" })
{
   Console.Write(str);
   Console.Write(" ");
}
</script>

1 comment:

Kyle Gobel said...

Nice post, saved me lots of time.