Thursday, July 16, 2009

Code Syntax Highlighting on Blogger.com

I found a good syntax highlighter at the following address http://alexgorbatchev.com/and use it on my blog at blogger.com. However there is one big problem with this Javascript library. Since blogger removes new lines (\n) and inserts < br > instead the code looks bad, it only consists of one line and has html break tags in it. In order to fix this problem I also add jQuery hosted by Google and come up with the following code for Layout of my blog:



<link href='http://alexgorbatchev.com/pub/sh/2.0.320/styles/shCore.css' rel='stylesheet' type='text/css'/>
<link href='http://alexgorbatchev.com/pub/sh/2.0.320/styles/shThemeDefault.css' rel='stylesheet' type='text/css'/>
<script language='javascript' src='http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shCore.js'/>
<script language='javascript' src='http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shBrushCSharp.js'/>
<script language='javascript' src='http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shBrushXml.js'/>
<script language='javascript' src='http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shBrushAS3.js'/>
<script language='javascript' src='http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shBrushJava.js'/>

<script language='javascript'>
$(document).ready(function () {
$("pre br").after("\n").remove();
SyntaxHighlighter.config.clipboardSwf = 'http://alexgorbatchev.com/pub/sh/2.0.320/scripts/clipboard.swf';
SyntaxHighlighter.all();
});
</script>

The only line for the fix for blogger.com is the following line:

$("pre br").after("\n").remove();

This line uses jQuery in order to modify HTML content. Basically, it finds all <br> tags which are under <pre> tags in DOM hierarchy, adds a new line after these tags and removes them from HTML. Just one line of code doing everything for us. Power of jQuery.

For each language you want to highlight you need to add the corresponding <script> tag. For example to highlight php you need to add the following line:

<script language='javascript' src='http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shBrushPhp.js'/>


You can check the following link to see the languages supported: http://alexgorbatchev.com/pub/sh/2.0.320/scripts/.

You need to put your code into a <pre> tag to highlight it. Also you need to add a class attribute like "brush:html" in order for the script know the language you are using. The final code looks like


<pre class="brush:jscript">
function doNothing()
{
var a = 1;
var b = 2;
var nothing = a*b;
// alert(nothing);
}
</pre>


and this is rendered as

function doNothing()
{
var a = 1;
var b = 2;
var nothing = a*b;
// alert(nothing);
}
You should remember that in order to insert < or > characters in HTML or XML, you need to replace them with &lt; and &gt; respectively.

Keep on posting.

1 comment:

Dicky said...

Thanks for your blog, I now can use Precode!