typedef int (*funcptr)();

An engineers technical notebook

Generating stylesheets for pygments

For this blog I am using Python markdown with the Pygments plugin that is available. Pygments does all of the code highlighting and outputs the required span tags and inputs them within the page.

If you were to look at the <div><pre></pre></div> block that is generated you'd see something like this:

<div class="codehilite"><pre><span class="k">def</span> <span class="nf">function</span><span class="p">(</span><span class="n">var</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
<span class="k">if</span> <span class="n">var</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span>
    <span class="k">print</span> <span class="n">var</span>
</pre></div>

which is generated from the following snippet of code:

def function(var=None):
    if var is not None:
        print var

As you see the top css class is codehilite, and then underneath that there are a bunch of other classes such as k, n, o, and so forth. Those are all classes that can be styled. Now one could write such a stylesheet by hand or we can simply use one of the stylesheets that Pygments ships with.

The documentation for Pygments tells you how to get built-in styles, which is as simple as:

>>> from pygments.styles import get_all_styles
>>> styles = list(get_all_styles())
>>> styles
['monokai', 'manni', 'perldoc', 'borland', 'colorful', 'default', ...]

These are all the styles that are available to you the user, now how do we get the style into an actual .css file that we can link to in our sites HTML file? We use the pygmentize command line tool:

pygmentize -f html -S trac -a .codehilite > pygments.css

Feel free to replace trac with any of the styles you have installed on your system. -f tells it what formatter to use, since we want it to output the css we ask it to use the HTML formatter, -S tells pygmentize what style to use, and -a prepends the .codehilite class before every rule (this way we don't pollute the whole CSS namespace with all the aforementioned class's such as k, o, ow and others).