Pygments to Chroma Migration

Chasing the syntax highlighting train in Hugo


As mentioned in my Pip Permissions post, when I upgraded past Hugo v0.28 I noticed that Chroma was now preferred over Pygments. Eventually, I tried tackling the migration.

Using Pygments Before v0.28

In order to use Pygments before, I needed to have it installed and then add the following line to my config.toml:

1
pygmentsUseClasses = true

And then using highlight shortcode in your post:

1
2
3
{{< highlight bash "linenos=inline" >}}
// ... code
{{< / highlight >}}

Note in the above, &lt; should be replaced with <. For some reason I wasn’t able to get the escaping of the shortcode quite right within code fences (which I switched to after this was written).

Using Pygments After v0.28

As of this writing, I’m on v0.30.2 of Hugo. To continue using Pygments requires adding another line to your config.toml but otherwise still works.

1
pygmentsUseClassic = true

Converting to Chroma

When moving to Chroma, the first obvious think is to remove the pygmentsUseClassic = true line from your config.toml file.

While doing this, I noticed that you can also set some global options for highlighting via the pygmentsOptions line in config.toml. This may have been possible in earlier versions of Hugo and I didn’t happen to see it.

Updating Beautiful Hugo

I also found that it was valuable to update Beautiful Hugo as there was a merge on November 10, 2017 related to Chroma support.

As part of that update, I re-read the README for that theme and saw the recommendation to add the following to config.toml:

1
2
3
4
pygmentsCodeFences = true
pygmentsUseClasses = true
[params]
    useChroma = true

The pygmentsCodeFences line was new and I chose to add it even though I hadn’t been making use of those in Hugo to this point. The useChroma line appears to be particular to this theme - or missing from the Hugo docs.

Generating a Stylesheet for Chroma

In order for Chroma to look better than horrible, you also need to generate a stylesheet. This isn’t complex but you might want to look at the options available to you with the following command:

1
> hugo gen chromastyles -h

There is a set of styles you can skim in a gallery here.

In the end I went with the default monokai from the Hugo docs.

1
2
> mkdir static/css
> hugo gen chromastyles --style=monokai > static/css/syntax.css

Strange Boxes

With these settings in place, I found that while things worked for the most part, I was seeing what looked like strange boxes around the right-hand side of the code block.

/img/2017-11-12_chroma-tables-bug.png

This appears to be true for any code block that does not take up the full width of the column available for text in Hugo. It doesn’t make me thrilled but I am going to leave it for now and call it a night and submit a bug.

Update: The bug I reported earlier looks to be an issue with Chroma instead. Continuing to chase this down by opening an issue with Chroma and closing the original.