Hugo: light syntax highlight

Hugo has a built-in syntax highlight that uses Chroma, a library written in go.

As much as I love libraries such as highlight.js, and even if they have plenty of crazy good options, I decided to drop them.

You don’t need that. Drop it. Permalink to heading You don’t need that. Drop it.

Performances are a common concern. To highlight code, you can use client-side libraries, but server-side can be a significant optimization.

The great news is Hugo provides that.

Instead of loading both CSS and JavaScript, I only need CSS. Fewer javaScript, fewer bytes, and, above all, with pretty much the same results.

How to Permalink to heading How to

I give you a sample config. Of course, feel free to make modifications. For example, I don’t use line numbers because I think it’s lame, especially for copy-paste, but that’s just my opinion.

The guessSyntax parameter is crucial to me, as I don’t use shortcodes to highlight code, only markdown tags.

You can read the documentation to get all the details.

As a starter, you can add the following in your config.toml file:

[markup.highlight]
  codeFences = true
  guessSyntax = true
  lineNos = false
  tabWidth = 4
  noClasses = false

Then run:

hugo gen chromastyles --style=xcode > syntax.css

And load syntax.css to get your styles. Of course, you can choose another predefined stylesheet.

See all predefined styles

Chroma shares some base code with Pygments, an older library. You get many common settings, which is pretty cool to ease the transition.

Possible caveats Permalink to heading Possible caveats

As far as I know, Chroma seems a little less precise than hyper boosted client-side libraries such as Prism.

I’ve noticed some minor glitches, such as a few inconsistencies with colors. However, that’s tolerably rare.

You won’t get features such as “copy to clipboard”, but that’s not the most complicated feature to code in vanilla js if you have to provide it.

You can read the complete list of supported languages here.

If that’s the same for you, you can safely switch to Chroma highlighting.

So convenient! Permalink to heading So convenient!

Server-side highlighting with Chroma is smooth:

Happy Chroma highlighting ;)