Higher Order Blog


Syntax-highlighting in web pages

29 Jul 2008

I've recently moved my blog to http://blog.higher-order.net. In this transition I used Wordpress' feature of importing blog content from my old blog: higher-order.blogspot.com. Unfortunately all the line-breaks from the pre-formatted JavaScript source code disappeared in the process, and so, I will have to insert it manually. This whole process reminded me that I would really prefer to have syntax-highlighting for code-sniplets in the blog. A little bit of searching lead to GNU Source-highlight. After a little fight with the make system, I managed to install it on Mac OS X -- it is looks really neat (even in the default style), and it's simple to use. However, the main reason I'm using this tool is not presentation: When writing the source code presentation manually in HTML one has to remember to escape characters like <. This means that the transformed source (i.e. the HTML-fragment) is no longer a syntactically correct program in the programming language of the code-snipplet, which means we can't just paste it into an interpreter to check if it works. Sometimes this leads to people posting code which isn't even syntactically valid... If you instead maintain a file which holds the syntactically correct source code (and using a smart editor you will immediately see stupid syntax errors instead of having blog-readers find those errors). You can then compile the source code to HTML using the Source-highlight tool. This is significantly less error prone, and the quality improves. Here is the namespace function from a previous post.
function namespace(spec,context) {
   var validIdentifier = /^(?:[a-zA-Z_]\w*[.])*[a-zA-Z_]\w*$/,
   context = context || window;
   spec = spec.valueOf();
   if (typeof spec === 'object') {
      if (typeof spec.length === 'number') {//assume an array-like object
         for (i=0,N=spec.length;i<N;i++) {
      else {//spec is a specification object e.g, {com: {trifork: ['model,view']}}
         for (i in spec) if (spec.hasOwnProperty(i)) {
            context[i] = context[i] || {};
            namespace(spec[i], context[i]);//recursively descend tree
   } else if (typeof spec === 'string') {
          (function handleStringCase(){
              var parts;
              if (!validIdentifier.test(spec)) {
                throw new Error('"'+spec+'" is not a valid name for a package.');
              parts = spec.split('.');
              for (i=0,N=parts.length;i<N;i++) {
                  spec = parts[i];
                  context[spec] = context[spec] || {};
                  context = context[spec];
    }  else {
       throw new TypeError();