Sunday, October 31, 2010

syntax highlight with SyntaxHighlighter (for Blogger)

SyntaxHighlighter is the standard way to put syntax highlight for your code snippets on a Web page. It is very straightforward to set up for Blogger (thanks to Leonid's excellent Blogger post).

Here is a quick summary of what you need to do (a bit variations for better performance):

1. Go to Design->Edit HTML, update the template with SyntaxHighlighter CSS and Javascript elements.

Splitting the CSS part and JavaScript part: put CSS that inside (not before) the <head> element. The JavaScript part goes right before the closing <body> element.

Comment out or delete AutoLoader JavaScript (the line with shAutoLoader.js) since we are not using it (I could not get it working either, although some people claimed it worked for them). The new AutoLoader basically loads the JavaScript brushes on demand instead of load from a list and use only one of them.

Limit the list of JavaScript brushes to what you need only. Leonid lists all the brush types he is using, you can adjust that for your own needs. Since these JavaScripts will be loaded each time, it is better to keep the list short to get good performance. Here is the list of all existing brush JavaScript files.

OK, the Blogger template update is done. Now, let's use it in the actual post.

2. In your new post, simply insert code inside a pair of <pre></pre> elements and specify brush type based on language like this:

<pre class="brush: _brush_lang_">your code</pre>

3. More adjustments and tips.

Use a different CSS theme. Leonid uses Midnight theme (shThemeMidnight.css), I am using the Eclipse theme. You can choose a theme that you like, here is the list of available themes.

Customize different styles for individual code block. The changes in the Blogger template applies to all the code blocks. You can also specify/override styles for individual blocks. The simplest way is use the parameters in the <pre> class attributes. You can read available parameters on SyntaxHighlighter configuration page.

For example, I can easily highlight line #1 and #12 using

<pre class="brush: javascript; highlight: [1, 12]">your_code</pre>

This is what it looks like:

var stringArray = new Array();
  stringArray[0] = "A";
  stringArray[1] = "B";
  stringArray[2] = "C";
  stringArray[3] = "D";
  stringArray[4] = "E";
  stringArray[5] = "F";
  stringArray[6] = "G";

  document.write("String value");
  for (var i = 0; i < stringArray.length; i++) {
    document.write(i + 1 + ". " + stringArray[i] + "");

Host your own SyntaxHighlighter scripts. You can use the hosted CSS and Javascript like the URLs in Leonid's example, which always points to the current/latests SyntaxHighlighter code base. If you want, you can also host it on you own.


No comments:

Post a Comment