20 May 2008

dp.SyntaxHighlighter jQuery plugin

I've just added syntax highlighing to the code samples on my blog using the excellent dp.SyntaxHighlighter. Adding a class name e.g. "c#" or "xml" to your pre or textarea elements and calling HighlightAll magically highlights the content and turns the surrounding element into a fancy box complete with toolbar.

I tend to wrap my samples in a <pre><code>...</code></pre> so applying the highlight on the pre tag would have broken because of the additional code inside. A quick gander at the code, bit of refactoring in shCore.js and a jQuery one-liner later and I've got a nice(ish) plugin that will apply highlighting to the elements selected through jQuery thusly:

   $("code").syntaxHighlight({showGutter: false, firstLine: 5});

The settings are:

  • showGutter < bool >
  • showControls < bool >
  • collapseAll < bool >
  • firstLine < int >
  • showColumns < bool >

You can grab the files from here:

This mod is using the latest stable release (1.5.1) of dp.SyntaxHighlighter. It looks like version 1.6 is in the pipeline with some major changes so I'll keep an eye on that and maybe revisit this when it comes out.

1 comment:

Michael James said...

Worth noting that if you use Blogger you need to turn off convert line breaks. This is found under settings > formatting