Sunday, August 14, 2011

Pretty code

[ UPDATE2: In an earlier version of this post, I missed one HTML tag in the code below, as a result the example wouldn't run as described when copy/pasted. Sorry. ]
I've been looking into solutions for posting code on the blog. Since the beginning, I've used <table> tags like this:
<div style="overflow-x: scroll ">
<table bgcolor="#ffffb0" border="0" width="100%" padding="4">
<tbody><tr><td><pre style=" hidden;font-family:monaco;">
my code here

With results looking like a bit like this, but larger :)

I borrowed the technique from Peter Norvig. He's moved on, but I hadn't.

In the last few days Blogger changed something that inserts newlines into such tables. I found another guy who noticed, but no solution. (Perhaps if I used the "new" editor?).

So, I googled around for syntax highlighting. Here is a listing of a bunch of methods. The one I decided to try is google-code-prettify. Like all the methods, it uses javascript and some css to do its work. Instructions are in the readme. The footprint in the html is pretty small, and I like the minimalist style.

To test it, I downloaded the distribution (see the link), and then put a file with the following html in the same directory as the source:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html>
<html ... >
<head ... >
<link href="prettify.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="prettify.js"></script>

<body onload="prettyPrint()">

<pre class="prettyprint" lang-python>
def f(n, s='abc'):
    print 'Hello world!'
    for i in range(n):
        # this is a loop
        print s

<pre class="prettyprint">
#include <math.h>
#include "Python.h"

int process (const char *c, double f) {
    int i = 0;
    if (c[0] == 'c') {
        i = floor(f);
    return i;


and then drag-n-dropped it on Safari:

One small problem is this note:

Include the script and stylesheets in your document (you will need to make sure the css and js file are on your server, and adjust the paths in the script and link tag)

Server, what server?

Seriously, I'd be happy to do it, but I don't want to pay Comcast $$ for the privilege.

However, there is a very nice answer on Stack Overflow (here) that shows how to embed the relatively simple css instructions into the html document. Then you just load the code from

I tested it in a simple html document and it worked. Now I'll have to try to incorporate all this into a Blogger template.

[ UPDATE: I see it choked on the <math.h>. I'll have to remember that. ]