Aug 22, 2021

Setting up syntax highlighting for Hugo

Hugo uses chroma[1] as its syntax highlighter. All you basically need for having your code highlighted is to let chroma put the syntax classes in the generated HTML, for the correct language, and then make sure you have corresponding CSS for those classes.

1: https://github.com/alecthomas/chroma

Let's start by enabling syntax highlighting in your configuration file.

In your configuration file, `config.toml` for example, add these settings so you can have your code highlighted and have it recognize Fenced Code Blocks for markdown:

pygmentsUseClasses = true
pygmentsCodeFences = true

Next you have to include the styles. There are two ways to go about this, one is to choose a style from the list of available styles (more on that below), and the second method is to use your own syntax theme.

You can have your own CSS styles, but there are *a lot* of classes, so if you're just starting out and want to have it working quickly, you should choose an existing style.

Browse the gallery[2] of available styles and use that style name to save the CSS file into your `assets` directory:

2: https://xyproto.github.io/splash/docs/

mkdir -p assets/syntax
hugo gen chromastyles --style=friendly > assets/syntax/main.css

If you'd like to use different styles for dark mode and light mode (like me), then you can change "main.css" to "light.css", and save the dark mode style to "dark.css". It doesn't matter where you put the file, but just remember to use that file name with referencing it later.

You don't have to put it under the directory "syntax" too, if you don't want to.

Apply the styles

You have to link to your CSS file that you've just created in your ``. There are several ways you can do so.

1. Use a `` tag and link to the URL of your CSS file, or

2. directly put the content of your file into a ``:

{{- if .Params.highlight -}}
<!--Put the code that fetches your syntax highlight CSS here-->
{{- end -}}

This tells hugo to only load the resource and put the CSS in `