Hugo Syntax Highlighting

A quick tutorial on how to add syntax highlighting to a Hugo site using Chroma.

Prerequisites

Step 1. Choose a style

Visit the Chroma Style Gallery and pick out the style that you prefer (Example: xcode).

Step 2. Update config

You can get syntax highlighting one of two ways: Inline css or with a stylesheet.

Inline CSS

The quickest way to get syntax highlighting is to set pygmentsStyle to true in your config.[toml|yml] file.

// config.toml
pygmentsStyle = "xcode"

Stylesheet

Inline css styles can be a bit cumbersome, especially if you want to override styles. For this reason you might prefer to use a stylesheet for syntax styles.

First, replace pygmentsStyle with pygmentsUseClasses = true.

// config.toml
pyghmentsUseClasses = true

Then, generate the stylesheet from the command line like so:

$ hugo gen chromastyles --style=xcode > static/css/syntax.css

You must then add a reference to the stylesheet, probably from a head.html file.

<!-- head.html -->
<link type="text/css" rel="stylesheet" href="{{ .Site.BaseURL }}css/syntax.css">

Step 3. Using the syntax highlighting

Wrap your code around the highlight shortcode passing in the desired language (eg swift).

{{% highlight swift %}}
func sayHi() {
  print("hello")
}
{{% /highlight %}}

Here’s the full list of supported languages.

References