2011-03-29

Posting code on blogger

Since I decided that I'd start blogging, I figured I'd better learn how to post code on my blog. The obvious approach is to use pre tags.

class Greeter(object):
    def __init__(self, message):
        self.message = message

    def repr(self):
        return 'Greeter(%s)' % self.message

    def print(self):
        print self.message

if __name__ == '__main__':
    g = Greeter('hello, world')
    g.print()

However, I've been using IDEs for almost a decade now... so the code looks somehow wrong when it hasn't been highlighted. Enter pygmentize, which takes code and spits out html. It does plenty of other clever things, too, but that's what I'm using it for. Setup is pretty simple. Install it however your OS requires / desires. On the command line, run

pygmentize -S default -f html

copy that output. On blogger, go to Design -> Template Designer -> Advanced -> Add CSS. Paste here.

Now, type up most of your new blog post and then flip over to Edit HTML. Take your code and feed it through pygmentize:

pygmentize -f html helloworld.py

Take that raw html and paste it into your post. You now have colorized, highlighted code that might even be readable and awesome.

class Greeter(object):
    def __init__(self, message):
        self.message = message

    def repr(self):
        return 'Greeter(%s)' % self.message

    def print(self):
        print self.message

if __name__ == '__main__':
    g = Greeter('hello, world')
    g.print()

0 comments: