Ever felt the need to post a piece of code into the web? Maybe in a forum or something? Well I came across that problem when I wanted to put in a page a couple of Python scripts I had made. As googling for a couple of minutes turned up empty, I just dumped the scripts in plain text.
But I recently found a solution. It’s called Pygments. Its command line utility could be a bit more user friendly, but other than that, it’s a great app. Oh, and it can be used to colourize a lot more than Python sripts.
OK, so here’s how I use the thing:
- to generate the CSS: $ pygmentize -f html -S colorful > python.css
‘colorful’ is the style name, on the site they teach you how to create your own (and if you do, please tell🙂 )
- to convert the source code: $ pygmentize -f html -O full=true,cssfile=python.css,style=colorful -o output_html.html python_file.py
a couple of remarks: the full=true option means that the html file generated will be complete (if this is omitted, the html file will contain a div with all the code). Next, if you give the name of the CSS file, but omit the style, the default style will be used AND THE CSS FILE WILL BE OVERWRITTEN (I think this is a bug, but I used version 0.6, not 0.8 which is at the time of writing the most recent one).
- if you want line numbers in the html, then append the following option: linenos=1 to the list of options!
- last, but surely not least, I use tab characters in the code, with the length of 4 spaces. But the only thing in the source file is the tab character, which when converted to html will result in the “standard” 8-chars wide tab. To avoid this, do the following: $ expand -t 4 source_file.py | pygmentize -f html -O full=true,cssfile=python.css,style=colorful -o output_html.html -l python
and presto!, an HTML file with 4 spaces of indentation will spring into existence, and you didn’t even had to change the original file! (the ‘-l’ handle informs the program of the language being used)
And that’s about it. Hope it’s useful…