Code Formatting with Blogger

Blogger provides a great free service for the starting amateur -- yours truly. Unfortunately, when deciding to start a blog about coding, I was dissapointed to find no standard solution for simple syntax highlighting. Most blogging solutions nowadays, come equipped with a code formatting utility, or at the very least community plugins which perform the task. I finally stumbled on

This little package from google code, will perform client side syntax highlighting using javascript. In layman's terms, since you can't touch what happens at the server blogger.com this is the only real option. And since it's from google, well, let's just say, i'm more inclined to trust it's quality. Here is a little sample:
module NMath
 def isPrime
   2.upto(self-1) do |n|
     return false if self%n==0
   end
   true
 end
end
It's pretty easy to set up too. Once you've downloaded and unzipped the syntaxhighlighter. You should have 2 folders of importance:
  1. Scripts - containing losts of .js files and one .swf
  2. Styles - containing the .css
To reference these, youll need to add 2 pieces of code to your html page (bloggers readon): Add this between your <head> </head> section
<link type="text/css" rel="stylesheet" href="SyntaxHighlighter.css"/>
<script language="javascript" src="shCore.js"/>
<script language="javascript" src="shBrushJava.js"/>
<script language="javascript" src="shBrushXml.js"/>
<script language="javascript" src="shBrushCss.js"/>
<script language="javascript" src="shBrushSql.js"/>
note 1: You always need SyntaxHighlighter.css, and shCore.js. You can choose if you want to add all of the others or not, depending on the languages you need. note 2: Make sure your relative positions are set! src="shCore.js" won't work if shCore.js is actually in subfolder scripts/shCore.js Finally Add this at the very bottom of your page, before the closing </body> tag
<script language="javascript">  
 dp.SyntaxHighlighter.ClipboardSwf = 'clipboard.swf';
 dp.SyntaxHighlighter.HighlightAll('code');
</script>
Once these are placed, all you need to do to produce the ruby example shown at the top of the page would be:
<pre class="ruby" name="code">
.... code .....
</pre>
Blogger users
  1. You can add the 2 portions of static code via Template / edit html
  2. If you need a place to host the js and css files, take a look at google pages ;)
  3. If you have trouble with blogger spewing <br> into your code, set Settings / Formatting / Convert Line Breaks to No.

Posted bykoderman at 10:14 PM  

0 comments:

Post a Comment