Wednesday, November 7, 2012

Blogger Syntax Highlighting

Introduction

One of the greatest features of any code editor is syntax highlighting. It makes code much easier to read. Luckily, there are several ways to add Syntax Highlighting to webpages, too. Like pretty much anything else on the web, you have two places you can perform the syntax highlighting: On the server, or on the client.

For server-side syntax highlighting there is the GeSHi tool written in PHP. For the client-side, there's Alex Gorbatchev's Syntax Highlighter written in Javascript. Both support a wide variety of languages and are fairly easy to use. There are pros and cons with each option.

A server-side solution obviously requires a server, and the server needs to be able host dynamic content.

A client-side solution doesn't need a server, but it does require the client to run a javascript program in order to get syntax highlighting. For most clients this is fine, but some clients, particularly older mobile clients, this can make your website fairly slow to load.

Because I want to use syntax highlighting with Blogger and I don't have access to the Blogger servers, the only option I have is a client-side solution, so I'll be using Alex Gorbatchev's Syntax Highlighter.

Note: at the time of this writing the latest version of Alex Gorbatchev's Syntax Highlighter is 3.0.83

Installing The Syntax Highlighter

There are a few different ways to "install" the Syntax Highlighter. You can modify your blog template or you can put it in each post. Having the Syntax Highlighter in each post means that you only have to load the Syntax Highlighter in posts you're actually using it. Of course, the down side is you have to copy/paste the Syntax Highlighter setup code into each post.

The first thing we need to do is add the core css stylesheet. At the time of this writing there's a bug with the Syntax Highlighter not displaying line numbers correctly in Google Chrome. This can be solved by adding the short override style after you load the core style.

<link href='http://alexgorbatchev.com/pub/sh/current/styles/shCore.css' rel='stylesheet' type='text/css'/>
<style type="text/css">
.syntaxhighlighter table td.gutter .line {
 padding: 0 5px  !important;
}
</style>

In addition to the core css stylesheet, there are various themes you can add to customize the look and feel of the syntax highlighter. There's a list of popular themes here.

<!-- Using the Eclipse style. Add this after you include the core style. -->
<link href='http://alexgorbatchev.com/pub/sh/current/styles/shThemeEclipse.css' rel='stylesheet' type='text/css'/>

Next we need to add the core javascript file.

<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js" type="text/javascript"></script>

This is the base setup, but it doesn't have any "brushes" or syntaxes. You can manually load the scripts you want to use or you can use the autoloader.

The default bundled brushes can be found here, a more complete list is available here.

<!-- Manually load some brushes to use -->
<script src="http://www.undermyhat.org/blog/wp-content/uploads/2009/09/shBrushMatlabSimple.js" type="text/javascript"></script>
<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushBash.js" type="text/javascript"></script>

To use the autoloader we need to load the autoloader script. We also need to tell it what aliases correspond to which scripts to load.

<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shAutoloader.js" type="text/javascript"></script>

The syntax highlighter autoloader taks an array of strings. Each string represents a potential script to be loaded. The syntax for each string is:

'alias_1 alias_2 ... alias_n script_url'

Where each alias is a trigger point for the autoloader to load in the appropriate syntax script file. You then pass this array to the apply function.

var langs = ['c cpp http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCss.js',
    'c# c-sharp csharp http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCSharp.js',
    'matlabkey http://www.undermyhat.org/blog/wp-content/uploads/2009/09/shBrushMatlabSimple.js'
   ];
SyntaxHighlighter.autoloader.apply(null, langs);

Note: In order to ensure the syntax highlighter will work properly you should only use aliases which are used by the individual syntax scripts. For example, the matlab syntax script listed above internally defines the alias matlabkey. You can try to add the alias matlab to the autoloader script which will load the matlab syntax script, but unfortunately the main syntax highlighting function will fail because it has its own alias list and doesn't recognize the autoloader aliases.

There are various configurations you can make. The most important one for proper Blogger support is to enable the bloggerMode flag.

SyntaxHighlighter.config.bloggerMode = true;

There's more information on configuring the Syntax Highlighter here.

Finally, to actually run the syntax highlighter script you need to run the all() function

SyntaxHighlighter.all();

Note: You should run the autoloader and main syntax only when you're sure the page is loaded. This is best done with a window.onload event listener.

Putting everything together, here's the final code. This is more or less the code I use.

<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/shThemeEclipse.css' rel='stylesheet' type='text/css'/>
<style type="text/css">
.syntaxhighlighter table td.gutter .line {
 padding: 0 5px  !important;
}
</style>
<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>

<script type='text/javascript'>
    // auto-loader script for Syntax Highlighting
    function path()
    {
      var args = arguments,
          result = [];
           
      for(var i = 0; i < args.length; i++)
          result.push(args[i].replace('@', 'http://alexgorbatchev.com/pub/sh/current/scripts/'));
           
      return result;
    };

    window.onload = function ()
    {
     var langs = path(
            'applescript            @shBrushAppleScript.js',
            'actionscript3 as3      @shBrushAS3.js',
            'bash shell             @shBrushBash.js',
            'coldfusion cf          @shBrushColdFusion.js',
            'cpp c                  @shBrushCpp.js',
            'c# c-sharp csharp      @shBrushCSharp.js',
            'css                    @shBrushCss.js',
            'delphi pascal          @shBrushDelphi.js',
            'diff patch pas         @shBrushDiff.js',
            'erl erlang             @shBrushErlang.js',
            'groovy                 @shBrushGroovy.js',
            'java                   @shBrushJava.js',
            'jfx javafx             @shBrushJavaFX.js',
            'js jscript javascript  @shBrushJScript.js',
            'perl pl                @shBrushPerl.js',
            'php                    @shBrushPhp.js',
            'text plain             @shBrushPlain.js',
            'py python              @shBrushPython.js',
            'ruby rails ror rb      @shBrushRuby.js',
            'sass scss              @shBrushSass.js',
            'scala                  @shBrushScala.js',
            'sql mysql                    @shBrushSql.js',
            'vb vbnet               @shBrushVb.js',
            'xml xhtml xslt html    @shBrushXml.js'
          );
     langs.push('matlabkey http://www.undermyhat.org/blog/wp-content/uploads/2009/09/shBrushMatlabSimple.js');
     SyntaxHighlighter.autoloader.apply(null, langs);
     
     SyntaxHighlighter.config.bloggerMode = true;
     SyntaxHighlighter.all();
    };
</script>

Modifying your Blogger Template

I'm not going to go too much into the details of how to modify the raw html Blogger template. If you need help finding the template, see the Blogger documentation. You can basically copy and paste the complete code into the blogger template. I would recommend putting it somewhere inside the head section.

Using the Syntax Highlighter

Now that we have the Syntax Highlighter setup we can finally use it. The official documentation is pretty good at describing how you can use it so I won't go too much into the details.

<pre class="brush: cpp">
// cpp code goes in here
#include  &lt;iostream&gt;
int main(void)
{
    for(int i = 0; i &lt; 10; ++i)
    {
     std::cout &lt;&lt; i &lt;&lt; std::endl;
    }
    return 0;
}
</pre>

This looks like:

// cpp code goes in here
#include  <iostream>
int main(void)
{
    for(int i = 0; i < 10; ++i)
    {
     std::cout << i << std::endl;
    }
    return 0;
}

Note: If you choose to use the pre tags make sure your code is properly HTML escaped. This means that < should be replaced with &lt; etc.

Conclusion

That's all you need to get syntax highlighting into Blogger. There are more advanced things you can do such as defining your own syntaxes and such, but I would recommend checking the available syntaxes before going out to make your own.

No comments :

Post a Comment