Saturday, December 3, 2011

Code snippets on blogs

I had a brief discussion with Casper Steinmann about how to present code snippets in blog-posts. We both agreed that nice formatting is really important. We also agreed that our previous attempts to do so were (and still are) crummy.

One of the (easy) ways to set up nice formatting can be found over at CraftyFella:


Just put some stuff in your blogger template and all you have to do is wrap your code examples in HTML <pre>  tags. "Pre tags" denote a pre-defined format, and are often used to wrap around code examples, with the color coding pertaining to that particular code-language and an equispaced font, which makes it possible to use indentations properly.

Most popular programming languages are supported in this method. C, C++ C#, python, and probably many others. Hoever, no support for FORTRAN - quantum chemists beware. If you know of a user-friendly syntax highlighter that does FORTRAN, do leave a comment! Everybody loves FORTRAN.

Here is a simple example of how a dumb python script looks after using CraftyFella's guide to set things up:

#!/usr/bin/python

def print_string(string):
    print string

hello_world = "Hello world, look at my fancy code formatting!"

for i in range(10):
    print_string(hello_world)

... and a little bit of C++:

//! Return size of collection
//! \return size of collection
unsigned int size() const {
     return data_vector.size();
}

2 comments:

Unknown said...

it is possible to make a fork of his git-repository, make the changes and make him include it in his repository (public web page).

https://github.com/alexgorbatchev/SyntaxHighlighter

Unknown said...

If you're mean for adding FORTRAN support, all that needs to be done is making a custom brush with the required regular expressions to match FORTRAN syntax. So doesn't even require forking!

http://www.undermyhat.org/blog/2009/09/list-of-brushes-syntaxhighligher/#do-it-yourself