Wednesday, October 21, 2009

Syntax highlighting your code snippets in Blogger

If you want to add syntax highlighting to code snippets in your blog, Blogger specifically, you are more than likely get the following results back from a Google search. At least that's what I get at the time of this writing.

But I soon realized that the instructions in all of those blog articles, while they must be useful in the past, are now obsolete with the latest SyntaxHighlighter from Alex Gorbachev. So here's how to add syntax highlighting to code snippets in your Blogger:

1. Navigate to Layout->Edit HTML, find the <head> tag. Right after that <head> tag, add the following (I use the Eclipse theme as shown on line 2 and include the scripts for the languages that I will be blogging about. But there are many more other themes and languages supported):

2. Wrap any code that you want to hightlight inside the following <script> tag (this example uses the brush:js for JavaScript, but again, there are brushes for many other languages, standard and non-standard. The ... is where your code snippets should be residing):

3. There are a couple of advantages that I see over using the legacy version 1.5 of the script. One advantage is that there are more than just one theme supported. The other advantage is inside the CDATA, you don't need to escape the < charater. You can just copy and paste anything from your IDE to the area inside the CDATA. However, the Blogger editor might complain by putting up the message: "Your HTML cannot be accepted: Tag is broken: <![CDATA[". I just checked the check box "Stop showing HTML errors for the body of this post" and publish again, and it seems to forgive.

Here's an example in Python:


IMPORTANT: When I saved as draft with the check box "Stop showing HTML errors for the body of this post" checked, and returned to the list of posts, I didn't see my post. So I quickly hit the back button on the browser, and published the post. What this means is while it's nice to be able to copy and paste code snippets directly from the IDE to the Blogger editor without worrying about escaping all the < characters, we might lose the ability to save as drafts.

1 comment:

  1. Hi there, I found your blog by the use of Google whilst searching for a comparable topic, your website came up, it seems to be good. I’ve bookmarked it in my google bookmarks.
    website design

    ReplyDelete