Friday, February 27, 2009

SyntaxHighlighter in Blogger

If you want to display well-formatted and easy-to-read source code in your Blogger blog, you may want to used Alex Gorbatchev's SyntaxHighlighter. Here is a sample of formatted Java:
public @interface Politics {}

@Override
public final void liveInAmerica(boolean insane) {
  Party<Fool>    republican = new Party<Fool>(false);
  // Party like it's 1999!
  Party<Dude> nonRepublican = new Party<Dude>(true);
  while(isBush()) {
    suffer(13);
  }
  if(insane) {
    elect(republican);
  }
  else {
    System.out.println("Free at last!");
    elect(nonRepublican);
    beHappy(7);
  }
}
In order to display my Java code, I perform the following three steps:
  1. Add CSS styles and a JavaScript to the Blogger template.
  2. Make source code more HTML friendly.
  3. Wrap code in <pre> tag when posting.


Step 1: Modify Template
In Blogger's Layout tab, select the “Edit HTML” sub-tab. Locate </head> in the text area. Right BEFORE this tag (before the <), paste the following code.
<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 src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJava.js' type='text/javascript'/> <script type='text/javascript'> SyntaxHighlighter.config.clipboardSwf = &#39;http://alexgorbatchev.com/pub/sh/current/scripts/clipboard.swf&#39;; SyntaxHighlighter.config.bloggerMode = true; SyntaxHighlighter.all(); </script>
Click the SAVE TEMPLATE button. If no errors occurred, you may navigate away from the Layout tab. This step only needs to be performed once. For each subsequent blog post, you only need to do the remaining steps to get highlighted source code.


Step 2: Clean the Code
Java code that uses generics contains lots of less-than (<) and greater-than (>) symbols. These symbols confuse HTML renderers. So the generified Java must be converted to a more friendly format. That is, each less-than and greater-than symbol needs to be replaced with “&lt;” and “&gt;” (without the quotation marks,) respectively. I use an online HTML encoder to quickly format the code. There are many other tools that achieve the same result.


Step 3: Wrap Code in <pre> Tag
Precede each block of Java code with the following:
<pre class="brush: java">
Finish the code block with:
</pre>


Blank Lines in IE
In order for Blogger to display blank lines within highlighted source code on Internet Explorer, one additional setting must be adjusted. Under the Settings tab, in the Formatting sub-tab, the option “Convert line breaks” must be changed to “No.” With this setting, hard-returns typed in the WYSIWYG post editor will not be converted to HTML line break tags.

WARNING: changing this option from yes to no will reformat all posts. If you don't want to spend forever re-entering all line breaks in your existing posts, then you may want to live without blank lines in your highlighted source code. But if you only have a few posts, then it is worth the reformatting exercise. Blank lines can make long source code listings much more readable. Keep in mind that the WYSIWYG “Compose” editor will be basically useless after changing this option to “No.” All line breaks will have to be entered as <br /> tags in the “Edit Html” editor, or a third-party blog editor.


Other Languages
The brush option in the <pre> tag tells SyntaxHighlighter which language to use. If you want to post source code in other languages, you would need to change the brush type in the <pre> tag and add the appropriate language script to your Blogger template. I only use Java, so I only added the Java script. It is a good idea to add as few JavaScripts as possible to your template in order to minimize page load times. You may choose from a complete list of supported languages and add the appropriate script line to your template for each desired language. For example, to add C++ support to your blog, add the following line to your template:
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCpp.js' type='text/javascript'/>


SyntaxHighlighter Usage
In order for the “copy to clipboard” feature to work, the blog viewer must have the Flash plugin installed. Without the appropriate Flash plugin, a blank area will be displayed where the clipboard button is usually located.

If you wish to host the SyntaxHighlighter scripts on your own site and not rely on the developer's server, you can find more information here. It is preferred that you host SyntaxHighlighter on your own server in order to conserve the developer's hosting bandwidth.


10 comments:

  1. Thank you very much, finally am able to format the code in my posts!

    ReplyDelete
  2. This works great. But the wrapped lines are not easy to read. Is there a way to have the lines not wrapped, but a horizontal scrollbar to show up instead?

    ReplyDelete
  3. funny though out of all the available instructions on syntax hi lighter and even at cartercole blog .
    I find your instructions Much easier and with code suited to blogger has served my purpose of installing it on blogger.
    the difference being here
    SyntaxHighlighter.config.clipboardSwf = 'http://alexgorbatchev.com/pub/sh/current/scripts/clipboard.swf'; SyntaxHighlighter.config.bloggerMode = true; SyntaxHighlighter.all();

    Thanks
    here is my first neat code snippet with syntax hi lighter thanks to you.
    http://www.adityagameprogrammer.com/2010/01/pick-random-number-between-2-numbers.html

    ReplyDelete
  4. @stanb:
    You can disable wrapping by setting the wrap-lines option in your pre tag, like this:
    <pre class="brush: java; wrap-lines: false">
    This will enable a horizontal scroll bar if needed.

    @Aditya:
    Thanks for the comment. Your code looks good.

    ReplyDelete
  5. Hi,

    Although this post is incredibly old, it is still worth mentioning that "Step 2: Clean the Code" is no longer necessary. In the newest version, you can instead write this:

    <script type='syntaxhighlighter' class='brush: c#'>
    var list = new List<string>();
    </script>

    ReplyDelete
  6. thanks. finally i got it working.

    ReplyDelete
  7. @katty:
    Rest assured, the next home I buy in Costa Rica will be FULL of cheese! Thank you for your relevant comment.

    ReplyDelete
  8. This comment has been removed by a blog administrator.

    ReplyDelete