Tuesday, March 31, 2009

Code Hightlight and Indention

Google Blogger is one of popular Blogs. Maybe millions of people own the blogger's blog. I like its convenient, it integrated with many nice features such as YouTube, Picasso Web Albums, Google Adsense etc. Unfortunately, it is not enough good for Sofware developer, the reason is that it doesn't provide the Code Hightlight feature. Worst of all, it will automatically trim the spaces in front of each line when you post your blog. It will spoil the indented code and effect the readability of code snippet. It is bad news, isn't it?

Of course, you can search for the corresponding Add-in to solve the problem. But I don't find the good add-in for blogger so far. Some of them are not convenient, some are no nice format, and some decrease the performance of website because they will read some information from server.

Now, I find the best way to solve it finnally. It's very easy. The key is one website I will strongly recommend for you. That is 代码发芽网(Which means code germination. Funny, aha.). You can paste your code snippet to it, and select the language such as C#, Javascript, Python, php etc. Then submit it. Finnally the code snippet will convert the format according to the language syntax and present with highlight style. Now you only need to select the result code and copy to your blog post. That's it.

It is not yet over. Blogger will automatically trim the spaces described before. So there is a peice of advice for you. If you place your code snippet inside the <> < /pre > in Compose Mode, everything is ok. You will get the indented code with highlight. Here are some sample demos.

C# Code Snippet:
public class Bar
[CallTracingAttribute("In Bar ctor")]
public Bar() {}
[CallTracingAttribute("In Bar.Calculate method")]
public int Calculate(int x, int y){ return x + y; }

Javascript Code Snippet:
function bookmark(title, url) {
if (document.all)
window.external.AddFavorite(url, title);
else if (window.sidebar)
window.sidebar.addPanel(title, url, "")
Python Code Snippet:
#!/usr/bin/env python

'makeTextFile.py -- create text file'

import os
ls = os.linesep

# get filename
while True:
fname = raw_input('Enter file name: ')
if os.path.exists(fname):
print"*** ERROR: '%s' already exists" % fname

# get file content (text) lines
all = []
print "\nEnter lines ('.' by itself to quit).\n"

# loop until user terminates input
while True:
entry = raw_input('> ')
if entry == '.':

# write lines to file with proper line-ending
fobj = open(fname, 'w')
fobj.writelines(['%s%s' % (x, ls) for x in all])
print 'DONE!'
Only regret is that it can't deal with the html-like language in this way, because the blogger will parse them. Apart from this, it can't support the generic syntax.

No comments: