Colourful Code with Pygments

This is another entry in the ‘Note to Self’ category. 🙂 I’m sure I will need this information at some later point in time again.

The other day I wanted to have some code syntax-highlighted and be able to select the colour theme and well as use the highlighted listing in a number of ways.

Since Pygments is a library made for this task and it also provides a command line tool: pygmentize. It took me some time to use the tool the right way and produce the result I was looking for.

To show how I ended up using it, I’ll use fd as an example, a Ruby utility I wrote that dumps file contents as hex codes and utf-8 characters.

The command below is run inside a directory that contains a sub-folder ‘bin’, and inside that a (Ruby) file fd. To achieve this you can do the following (preferably when in a folder where you keep your cloned Git repositories):

> git clone git@github.com:s2k/fd.git
Cloning into 'fd'...
remote: Enumerating objects: 532, done.
remote: Counting objects: 100% (57/57), done.
remote: Compressing objects: 100% (9/9), done.
remote: Total 532 (delta 48), reused 53 (delta 47), pack-reused 475
Receiving objects: 100% (532/532), 105.97 KiB | 526.00 KiB/s, done.
Resolving deltas: 100% (261/261), done.
> cd fd

Here’s the command to create an HTML file using the given theme:

> pygmentize -l ruby -O full,style=monokai,linenos=1 -o fd.html -f html bin/fd

Here’s what the Parameters mean:

-l ruby
Set Ruby as the language to ge highlighted.
-O full,style=monokai,linenos=1
full generates output that includes everything to display the colourised code.
style=monokai sets the theme to ‘Monokai’.
linenos=1 displays the line numbers in the output.
-o fd.html
Set the output file name.
-f html
Set the output format to HTML.

When generating HTML, the full seems to be particularly important, as otherwise the HTML won’t contain the CSS used to colour the code.
The resulting highlighted code looks like this:

The colourised code of the file 'fd', including line numbers in front of each line.
The pygmentized source code

In case you’d like to experiment with pygmentize, here’s some zsh code that prints a sorted list of the styles it knows about:

> pygmentize -L styles | grep "* \(\w\+\):" | sed "s/* \([a-z_]*\):/\1/" | sort

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Seaside Testing

Subscribe now to keep reading and get access to the full archive.

Continue reading