Sunday, December 5, 2010

CSS and syntax-colored Python for blogspot

Ever since I started posting on blogspot, I've used a standard layout for code fragments and output (also R code) that I originally borrowed from Peter Norvig. (Of course, in the meantime he's moved on).  


Now they have a new editor, and it's "recommended", so I tried it on the last post and struggled quite a bit. One problem is that I've been editing the html directly, but the new editor keeps slipping lots of tags in there while I'm working and makes it a pain to see what's going on and where I'm working, etc.  In fact, the auto-save feature interrupts an edit to tell me there's no matching tag---for the thing I'm editing right now!


So I want a tool to do the html markup before I get to blogger's editor, then I'll just paste it in there, and back out to the compose tab and work, not worrying about how much weird stuff gets added to the html.


I went looking for syntax-coloring (Python, of course) and found a post about Pygments here. I basically followed those instructions, except that currently the Design tab gives access to a Template Designer, where under Advanced you will find: Add CSS. I used easy_install to get Pygments (after fixing my .pydistutils.cfg file from this morning). Pygments will spew out a stylesheet with:

pygmentize -S default -f html -a "code.syntax" > syntax.css

I edited that to make this addition as the post describes:

code.syntax .hll { background-color: #ffffcc;
display: block;
overflow: auto;
padding: 3px 5px;
margin: 5px 3px;
border: solid 1px #afafaf;
color: #000;
white-space: pre;
}


and just pasted that into the template. Now I save a code sample I want to color in a file sample.py and do:

pygmentize -f html sample.py > sample.html

Copy that into the edit window flanked by <b><big>
<code class="syntax"> and </code></big></b>
. It looks like this:




import sys

# this is a sample for Pygment
def f(n):
    try:
        n += 3.14
    except TypeError:
        print 'oops'
    print n

f('my bad')