Monday, September 22, 2008

How to use Google's Syntax Highlighter in Blogspot

Being a techie, we sometimes wish to post source code. Now, we all know that reading it can be a pain in the neck, especially if it's not nicely formatted. As convenient as blogspot is, it doesn't provide any funtionality to format source code. Luckily there's a thing called syntax highlighter and it's quite easy to have it working with your blog. Simply follow those four steps

1. Download Syntax Highlighter from Google
2. Extract files and upload them to a webserver ([your URL])
3. Edit your template and replace

</div></div> <!-- end outer-wrapper -->
</body>
</html>


by

</div></div> <!-- end outer-wrapper -->
<link href='[your URL]/SyntaxHighlighter.css' rel='stylesheet' type='text/css'/>
<script src='[your URL]]/shCore.js' type='text/javascript'/>
<script src='[your URL]/shBrushCpp.js' type='text/javascript'/>
<script src='[your URL]/shBrushCSharp.js' type='text/javascript'/>
<script src='[your URL]/shBrushCss.js'type='text/javascript'/>
<script src='[your URL]/shBrushJava.js' type='text/javascript'/>
<script src='[your URL]/shBrushJScript.js' type='text/javascript'/>
<script src='[your URL]/shBrushSql.js' type='text/javascript'/>
<script src='[your URL]/shBrushXml.js' type='text/javascript'/>
<script class='javascript'>
//<![CDATA[
function FindTagsByName(container, name, Tag){
var elements = document.getElementsByTagName(Tag);
for (var i = 0; i < elements.length; i++){
if (elements[i].getAttribute("name") == name) {
container.push(elements[i]);
}
}
}
var elements = [];
FindTagsByName(elements, "code", "pre");
FindTagsByName(elements, "code", "textarea");
for(var i=0; i < elements.length; i++) {
if(elements[i].nodeName.toUpperCase() == "TEXTAREA") {
var childNode = elements[i].childNodes[0];
var newNode = document.createTextNode(childNode.nodeValue.replace(/<br\s*\/?>/gi,'\n'));
elements[i].replaceChild(newNode, childNode);
} else if(elements[i].nodeName.toUpperCase() == "PRE") {
brs = elements[i].getElementsByTagName("br");
for(var j = 0, brLength = brs.length; j < brLength; j++) {
var newNode = document.createTextNode("\n");
elements[i].replaceChild(newNode, brs[0]);
}
}
}
//clipboard does not work well, no line breaks
// dp.SyntaxHighlighter.ClipboardSwf =
//"[your URL]/clipboard.swf";
dp.SyntaxHighlighter.HighlightAll("code");
//]]>
</script>
</body>
</html>



4. Write your post and add source code (in the HTML tab) using either

<pre name="code" class="java">
// your code here
</pre>

or

<textarea name="code" class="java">
// your code here
</textarea>

As an example, the following code

<textarea name="code" class="java">
/**
* Hello World Example
*/
   class HelloWorld {
      public static void main(String[] args) {
         String message="Hello World!";
         System.out.println(message);
   }
}
</textarea>

becomes

/**
* Hello World Example
*/
class HelloWorld {
public static void main(String[] args) {
String message="Hello World!";
System.out.println(message);
}
}

Note:
  • When posting XML or HTML, replace < by &lt; and > by &gt;
  • change class="java" as needed to java, csharp, css, xml, html, ... (complete list)
  • JavaScript removes <br/> tags because blogger automatically adds them in case of a linebreak but syntax highlighter would display them in plain text

10 comments:

Toby said...

Hi, Thanks for the post. I'm getting br's displayed in my page so tried to add your java script but it complains about it being well formed. I suspect the regex, any clues how to escape it? I'm using blogspot. Cheers :)

Thomas said...

Did you try to debug the page with Firebug? Usually that gives excellent hints on script errors.

Ruskin Dantra said...

I cannot get mine to show in Chrome and firefox although it works in IE, any pointers?

Basil Gasser said...

Have you accidentially disabled javascript? I successfully tested it with FF (3.0.4) and chrome (1.0). Can you please provide some more information.

Ruskin Dantra said...

I meant my site...http://ruskin-dantra.blogspot.com.

Your site successfully shows up in both. Is there something else I am missing?

Basil Gasser said...

There are actually several problems with your site.
First you have google friendconnect. This already causes Javascript execution to fail and hence the syntax highlighting fails (as javascript execution is stopped after an exception caused by the google friendconnect). I didn't investigate in those errors but just commented the code out for testing.
I then found that our script fails with "Node was not found" exception when trying to replace the html linebreaks (<br/> ) with \n . This is caused by the fact that you have <br> Tags for linebreaks instead of <br/>. Although <br> are correctly handled by web browser, dom seams to have a problem with that.
As just writting <br> instead of <br/> is probably a common habit, I think of an appropriate solution.
For now, fix the problems with the friendconnect and use <br/> instead of <br>

Ruskin Dantra said...

I removed that widget but after examining my blog in the blog editor I don't see any "br" or "br/". I examined my blog in both, the build in blog editor and windows live writer, can't find "br" tag at all.

Basil Gasser said...

Its a bit strange with the <br> tags. I don't see them in the source, but they are there when I save the html page to my drive and also when I debug the javascript.
In any case you can just catch the exception - not the nicest solution but one that will work:

try { elements[i].replaceChild(newNode,brs[0]);
} catch (e){}

Ruskin Dantra said...

Genius Basil...catching the exception fixed it. Then the formatting went weird then I realised that List<string> was the culprit because the generic symbols weren't being handled. Thanks a lot :)

عبدالرحمن اسحاق said...

Hey its work fine but i dont know
the language of this Search code

< form id="searchThis" actio....