Thursday, May 7, 2009

Highlight Code Syntax on Website Using SyntaxHighlighter

SyntaxHighlighter is a fully functional self-contained code syntax highlighter developed in JavaScript. The latest version (May 7, 2009) is version 2.0 (maintenance release 2.0.320 released at May 3, 2009). It is licensed under LGPL 3, but you encouraged to donate to the developer since it's a donationware.

Before using it, you can view the demo here.

Here, the guides how to use SyntaxHighlighter.

  1. Download the archived package here

  2. Extract the archived package

    Example, extract in directory named "sh". So, in this directory, there are 3 directories (scripts, src, and styles) and 2 files (LGPLv3.txt and test.html). You may look at the test.html for quick tutorial.

  3. In <head> tag, insert/link the CSS files of SyntaxHighlighter core and theme

       <link type="text/css" rel="stylesheet" href="sh/styles/shCore.css" />
       <link type="text/css" rel="stylesheet" href="sh/styles/shThemeDefault.css" />
      
  4. Still in <head> tag, insert/link the JavaScript files of SyntaxHighlighter core and all brushes you want to use

       <script type="text/javascript" src="sh/scripts/shCore.js" />
       <script type="text/javascript" src="sh/scripts/shBrushBash.js" />
       <script type="text/javascript" src="sh/scripts/shBrushCpp.js" />
       <script type="text/javascript" src="sh/scripts/shBrushPlain.js" />
       <script type="text/javascript" src="sh/scripts/shBrushXml.js" />
      

    You can view all brushes you can use here.

  5. Still in <head> tag, call SyntaxHighlighter.all()

       <script type='text/javascript'>
        SyntaxHighlighter.all();
       </script>
      
  6. Add code blocks

    All codes you want to highlight must be located in <pre> tag with specially formatted class attribute. The value of class atttribute is the parameters to edit the styles/looks of code block. There is only one required parameter, brush, while the others are optional (see configuration). The brush parameter must be set to one of the brush aliases that you have loaded prior. It is the simple example:

       <pre class="brush: html;">
        <a href="http://indoguides.blogspot.com">IndoGuides</a>
       </pre>
      

    Because browsers will interpret the text after bracket "<" as XML tags, in the code blocks you must replace all of character of < and > with html special character associated with (which start by character of &).

For you who don't have place for hosting the SyntaxHighlighter package, you may use the hosted version. Just change the link of CSS and JavaScript files to http://alexgorbatchev.com/pub/sh/[VERSION] like so:

 <link type="text/css" rel="stylesheet" href="http://alexgorbatchev.com/pub/sh/2.0.320/styles/shCore.css" />

No comments:

Post a Comment