Wednesday, January 22, 2025

Guide to the SyntaxHighlighter JavaScript Library

Guide to the SyntaxHighlighter JavaScript Library

SyntaxHighlighter is used by all sorts of information technology-oriented sites to display source code or specially formatted text. It was originally created in 2004 and is still maintained by Alex Gorbatchev. Since then, it has undergone several transformations between version 1 and 3. The latest version has not been hailed by everyone as an across-the-board improvement. In this guide to the SyntaxHighlighter, we’ll review some of the key version differences, as well as how to use, configure, and tweak the latest version.

Comparing Version 1, 2, and 3

The idea behind SyntaxHighlighter was to create a lightweight client-side tool for adding color to code snippet syntax on a web page. SyntaxHighlighter employed regular expressions to parse the text, which in my opinion, is not the optimal way to parse source code. I am more partial to using an iterator, like the one I presented in my Split on Non-quoted Characters article. Another drawback was that it wasn’t particularly fast; not a problem unless you tried to highlight hundreds or thousands of lines of code.

It had a few useful text buttons including a view plain text, copy to clipboard, print, and a help link:

 

Version 2.0 was an almost complete rewrite of 1.5 and added CSS themes and the ability to highlight HTML markup. The shLegacy.js add-on script was available to provide backwards compatibility with 1.5. The look & feel was also improved by replacing the link buttons with icons:

Version 3 introduced several improvements, which we’ll be looking at shortly. The most immediately apparent ones are that the alternate row highlighting is gone and that the icon buttons, referred to as the toolbar, are also conspicuously absent. All that remains is a small green help icon in the upper right corner. The decision to not include the copy to clipboard feature was largely due to user complaints regarding the Flash widget that provided cross-browser functionality. As a result, the button was replaced with the (supposedly) more intuitive double-clicking of the code. Doing so selects the entire snippet that users can then copy using the usual Ctrl/Cmd-C button combination. Clicking outside of the code block returns the view to the original state:

Using SyntaxHighlighter in your Pages

Looking around the Web, one could get the impression that a lot of folks aren’t in any particular hurry to move to version 3. Maybe they don’t mind the Flash copy implementation. Just in case you don’t mind it either, I’m going to show you how to use version 2 in your pages, as well as version 3.

Version 2 requires that you include a JavaScript file for each brush that you intend to use on your page. Judging from the test page that comes with it, that can be a lot of script files:

 
<head>
    <script type="text/javascript" src="scripts/shCore.js"></script>
    <script type="text/javascript" src="scripts/shBrushBash.js"></script>
    <script type="text/javascript" src="scripts/shBrushCpp.js"></script>
    <script type="text/javascript" src="scripts/shBrushCSharp.js"></script>
    <script type="text/javascript" src="scripts/shBrushCss.js"></script>
    <script type="text/javascript" src="scripts/shBrushDelphi.js"></script>
    <script type="text/javascript" src="scripts/shBrushDiff.js"></script>
    <script type="text/javascript" src="scripts/shBrushGroovy.js"></script>
    <script type="text/javascript" src="scripts/shBrushJava.js"></script>
    <script type="text/javascript" src="scripts/shBrushJScript.js"></script>
    <script type="text/javascript" src="scripts/shBrushPhp.js"></script>
    <script type="text/javascript" src="scripts/shBrushPlain.js"></script>
    <script type="text/javascript" src="scripts/shBrushPython.js"></script>
    <script type="text/javascript" src="scripts/shBrushRuby.js"></script>
    <script type="text/javascript" src="scripts/shBrushScala.js"></script>
    <script type="text/javascript" src="scripts/shBrushSql.js"></script>
    <script type="text/javascript" src="scripts/shBrushVb.js"></script>
    <script type="text/javascript" src="scripts/shBrushXml.js"></script>
    <link type="text/css" rel="stylesheet" href="styles/shCore.css"/>
    <link type="text/css" rel="stylesheet" href="styles/shThemeDefault.css"/>

One final script sets the path to the clipboard.swf file and calls the highlighter method:

 
    <script type="text/javascript">
        SyntaxHighlighter.config.clipboardSwf = 'scripts/clipboard.swf';
        SyntaxHighlighter.all();
    </script>
</head>

Version 3 adds Dynamic Brush Loading, so the script files don’t have to be included anymore. Instead, you only need to include the brush loading script and call it with the brushes you need:

 
<script src="shCore.js" type="text/javascript"></script>
<script src="shAutoloader.js" type="text/javascript"></script>
 
<script type="text/javascript">
SyntaxHighlighter.autoloader(
 'js jscript javascript /js/shBrushJScript.js',
 'applescript      /js/shBrushAppleScript.js'
);
 
SyntaxHighlighter.all();
</script>

Making Brush Loading Even More Dynamic

Since each <PRE> tag will have a class attribute that sets the brush to use, as in <PRE class=”brush: php;”>, it is not overly difficult to fetch the brush based on it:

 
var preTags = document.getElementsByTagName('pre');
for(var i=0; i<preTags.length;i++) {
 //load relevant brush
 if(!/\b(js)|(jscript)|(javascript)|(xml)|(xhtml)|(xslt)|(html)|(text)|(plain)\b/.test(preTags[i].className)){
  var brushType=preTags[i].className.match(/brush:\s*\b(\S+)\b/);
  if(brushType&&brushType.length>0){
   document.writeln('<script src="http://alexgorbatchev.com/pub/sh/3.0.83/scripts/shBrush'+brushType[1]+'.js"><\/script>');
  }
 }
}

Using Hosted Scripts

Like so many JS script libraries, SyntaxHighlighter also offers script hosting, so that you don’t even need to download them. The files are hosted on Amazon S3, but folders on the alexgorbatchev.com site take care of the redirecting. Pretty much all version numbers are available:

  • http://alexgorbatchev.com/pub/sh/1.5.1/
  • http://alexgorbatchev.com/pub/sh/2.0.278/
  • http://alexgorbatchev.com/pub/sh/2.0.287/
  • http://alexgorbatchev.com/pub/sh/2.0.296/
  • http://alexgorbatchev.com/pub/sh/2.0.320/
  • http://alexgorbatchev.com/pub/sh/2.1.364/
  • http://alexgorbatchev.com/pub/sh/2.1.364/
  • http://alexgorbatchev.com/pub/sh/2.1.382/
  • http://alexgorbatchev.com/pub/sh/3.0.83/

There is also a “current” folder so that you can always be at the cutting edge.

Inside each 2.x and 3.x root folder the subdirectory structure is identical to the download package so that the “styles” folder contains CSS files and “scripts” contains JavaScript files:

 
<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> 
<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shAutoloader.js" type="text/javascript"></script> 

Give Me Back My Alternating Line Highlighting!

I personally liked the alternate row highlighting of pre-version 3. Row highlighting is available using the highlight class attribute. It takes an array of lines to highlihgt, so I hooked it up to an inline function that returns an array of even numbers:

 
//this will highlight even rows
var newlines = preTags[i].innerHTML.match(/\n/g);
if(newlines && !/\bhighlight\b/.test(preTags[i].className)){
 preTags[i].className+=(preTags[i].className.charAt(preTags[i].className.length-1)!=';'?';':'')
            +'highlight:['+function(){var a=[];for(var i=2;i<=newlines.length+1;i+=2)a.push(i);return a}()+']'; 
}

Now that’s more like it!

Conclusion

SyntaxHighlighter’s ease of use and versatility have no doubt greatly contributed to it’s popularity. If there is one drawback, it’s the one to which I alluded to earlier. Regular expressions are not well suited for locating matched pairs like tags and braces. As a result, there are many elements that are simply not color-coded at all. I wouldn’t mind seeing some improvements in that regard.


If you enjoyed this article, please contribute to Rob’s less lucrative music career by purchasing one of Rob’s cover or original songs from iTunes.com for only 0.99 cents each.

Rob Gravelle resides in Ottawa, Canada, and is the founder of GravelleConsulting.com. Rob has built systems for Intelligence-related organizations such as Canada Border Services, CSIS as well as for numerous commercial businesses. Email Rob to receive a free estimate on your software project. Should you hire Rob and his firm, you’ll receive 15% off for mentioning that you heard about it here!

In his spare time, Rob has become an accomplished guitar player, and has released several CDs. His former band, Ivory Knight, was rated as one Canada’s top hard rock and metal groups by Brave Words magazine (issue #92).

Rob uses and recommends MochaHost, which provides Web Hosting at $3.10 per month, 2 LifeTime Free Domains, and 6 Months Free!

Rob Gravelle
Rob Gravelle
Rob Gravelle resides in Ottawa, Canada, and has been an IT guru for over 20 years. In that time, Rob has built systems for intelligence-related organizations such as Canada Border Services and various commercial businesses. In his spare time, Rob has become an accomplished music artist with several CDs and digital releases to his credit.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured