Friday, February 13, 2009

Code Syntax Highlighting on Blogger

Summary:

If you want your code formatted in a Blogger post, just add the following two lines to your template, before the </body> tag.

<script src='http://easy-blog-code-syntax-highlighting.googlecode.com/svn/trunk/ebcsh.js' type='text/javascript'/>

<link href='http://www.geocities.com/easyblogcodesyntax/ebcsh.css' rel='stylesheet' type='text/css'/>


Then, just wrap any code in <pre> tags, make sure you add the name="code" attribute, and select the language you are formatting for in the class:

<pre name="code" class="brush: c-sharp;">
function test() : String
{
return 10;
}
</pre>


becomes


function test() : String
{
return 10;
}


Explanation:

The first order of business for this blog was getting code syntax highlighting working. Not too difficult, there's a utility called SyntaxHighlighter that will do this in JavaScript, and instructions here and here on making it work in Blogger. Unfortunately, this still required hosting the Syntax Highlighter files somewhere, and adding some custom code from one of the above posts, or else Blogger adds visible <br/> tags to the line breaks in the code.

So, I combined all the relevant JavaScript from the Syntax Highlighter project (built against 2.0.287), added the necessary code to remove the <br/> tags, and put that up on a Google code project here. Then I just linked to that file (ebcsh.js) directly out of the svn trunk.

The css required a little more work, as Firefox refused to load css served from the Google Code's svn trunk. Google served the file with a MIME type of "text/plain", instead of "text/css", so I dialed up 1997 for some swanky free Geocities hosting.

6 comments:

  1. Cool stuff, listen I've got currently working on a project related to Scala, a new functional programming language. It would great if i could make a file to recognize and highlight Scala. Can i put it on svn?

    ReplyDelete
  2. Actually, it looks like they already have a Scala brush (http://alexgorbatchev.com/wiki/SyntaxHighlighter:Brushes). I'll add it to this conglomeration shortly.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. The main thing I don't like about this type of plugin is that it makes it difficult for users to copy the code and actually run it, due to the line numbers. The actual color and highlighting is great visually though.

    James

    ReplyDelete