Saturday, April 19, 2008

SyntaxHighlighter on Blogger

Ironically, my first reasonable post here is going to cover Blogspot itself.

When I decided to set up a blog, one of the few things I knew it should have was a nice syntax coloring script. The most powerful one I've seen so far is SyntaxHighlighter, which not only features coloring as such, but also displays the code in a neat, scrollable box with actual line numbering. Now that's a killer!

However, wiring SyntaxHighlighter to your Blogspot site does take some doing. Especially if you tend to thoughtlessly copy someone else's code :)

First of all, Blogspot doesn't allow link tag in your posts. Which is where I put it, having simply copied the sample code from the Usage page.

Luckily, if you go to Layout -> Edit HTML pane, you may edit your blog's template in an XML format. That's where you need to find the head section and insert the link to your css.

Right, the link. Our friends at Blogspot haven't provided for uploading any external files like scripts or CSS, so you either have to host them somewhere else or manually insert the CSS in the CSS section of the Blogger's template. I opted for the latter, courtesy of my dearest Bro.

To get SyntaxHighlighter to work, you still need to call some JavaScript functions as well as import a Flash file. I'm pretty unlikely to be blogging about my love life, rather programming issues, so I'll probably include some code on a regular basis. Having to paste those script lines every time I do it would be an overhead. (My brother deleting the linked scripts is a hazard, too). Thus placing as well the script includes in the template seems to be a good idea.

So you think we've got the syntax coloring configured? Surprise. If you insert some code to your blog, you'll find the <pre> or <textarea> contain one line only, with some nasty br tags in them. Bad, bad Blogger, converting all line breaks into br tags, even in Html mode! Fortunately there are two solutions to this. Either you disable the "Convert line breaks" option in Settings -> Formatting pane, or you can resort to "blogger mode", already implemented in SyntaxHighlighter. Well, thanks guys for pointing that out - nothing is obvious at 2 AM...

Just two more hints, in case you've stayed up late as I have:

1. The syntax of JavaScript doesn't involve any funny question marks. If you find any in your code, you've probably copied it from a Wiki along with the camel case escape characters.

2. If you want test the coloring on your Java code, include shBrushJava.js instead of the sample shBrushCSharp.js.

So, let's give it a try. These are the vital snippets from my template xml:



Let's see how this renders... ;)

PS. Oddly enough, the textarea containing code gets doubled on the main page, while all is as expected if you follow the entry's link. No clue why this happens. Any ideas?

No comments: