Sunday, January 18, 2009

Using google-code-prettify to highlight code in web page

I wanted to highlight my code in blogger and stumbled upon this from google. It also nicely formats the code. Henceforth, I am going to use prettify and not this. Here are the steps to do it.

- Edit your template in the dashboard (Layout->Edit HTML, see pic below)



- Include these two lines in the head tag.

< link href="http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.css" type="text/css" rel="stylesheet">
< script type="text/javascript" src="http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.js" > </script>


- Change the body tag to include onload='prettyPrint()'

< body onload='prettyPrint()'>

- Save the template.

- Now to highlight your code do this

< pre class="prettyprint">
... # Code goes here
</pre>


Thats it. Here is an example:

public class Factorial {

public static int getFactorial(int input) {
int fact = 1;
if (input==0 || input==1) return fact;
if (input < 0) fail("Provide argument >= 0");
for (int i = 2; i <= input; i++) {
fact = fact*i;
}
return fact;
}

public static void fail(String exception) throws
IllegalArgumentException{
throw new IllegalArgumentException(exception);
}

}

No comments:

Post a Comment