Monday, November 21, 2011

Blogger Syntax Highlighting

I just figured out how to auto syntax highlight and pretty print code in Blogger and I might as well write a post saying how I did it. All in all it was very straightforward.

Step 1)

Go into Blogger's "Design" tab for your blog and go into the "Edit HTML" tab for your style. Go down to just before the </head> tag and paste the following:
Notice that last little CSS snippet. For some reason (bug) the code segments that this generates will always have a vertical scrollbar when rendered in Chrome, even though a scrollbar is not needed. The workaround is that CSS which disable vertical scrollbars for the code region.

In this example I only added the scripts for HTML/XML, CSS, and JavaScript, but there are other script for other languages available like C++, C#, Python, Ruby, etc.

Step 2)

Final step is to add your code snippet. You can do it with a <pre> that has a class attribute that indicates the language of the code within. For example the following code in your Blogger post:
<pre class="brush : js">
function addition(a, b) {
    return a + b;
}
</pre>
Will produce a final output like the following:
function addition(a, b) {
    return a + b;
}

No comments:

Post a Comment