Blog

Syntax highlighting in custom pelican themes

I recently ported my blog to Pelican and built a custom theme. The documentation is okay but I had to look at the source of the default theme (notmyidea) to figure a lot of things out.

The one thing not mentioned in the documentation is how to get syntax highlighting in your custom theme. It's actually pretty easy. You have two options for syntax highlighting in pelican:

Option 1 - Pygments

You can use Pygments to generate your syntax highlighting server side. This is actually the default for pelican as long as you have pygments installed pip install pygments. What this will do is run your html through the pygments processor and it will automatically wrap html elements with unique classes around your code. For example, your code might go from this

<code>print "hello world"</code>

to something like this (not guaranteed to be accurate!)

<code><span class="kk">print</span><span class="sr">"hello world"</span>

You can then style these elements as you desire, see the docs for more information on creating your own style. However, the easier method would be to use an already developed style sheet.

Pygments has several default stylesheets that you use. To generate them use the following command:

pygmentize -S style_name -f html > style_name.css

This is a good resource for getting a preview of the stylesheets and this repo has some pre-generated themes if you'd rather not generate your own.

Once you've selected your theme you just have to include it in your base template and you're good to go! <link rel="stylesheet" href="/theme/style_name.css" />

Option 2 - Javascript library

Alternatively, if you don't want to do do syntax highlighting on the server side you can utilize a javascript library. There are plenty of options, some popular ones are HighlightJS, Google Code Prettify, and Syntax Highlighter.

The nice thing about these libraries is that they'll automatically detect the programming language and will automatically highlight anything wrapped in a code tag.

More most of them, all you need to do is download the javascript file and include it in your template, just don't forget to uninstall pygments or you might run into some conflicts)