Hugo - Add syntax highlighting

By xngo on April 11, 2020

Hugo uses Chroma as its code highlighter. To enable it, you simply need to add the following lines to your config.toml file.

pygmentsCodefences = true
pygmentsCodefencesGuessSyntax = true
pygmentsStyle = "monokai"

If you want a different style than monokai, checkout the Chroma Style Gallery.

Example

Here is a code snippet example from my md file.

# Test syntax highlighting
 
{{< highlight python "linenos=table,hl_lines=3 7-9,linenostart=1">}}
my_list = [ 1, 5, 2, 4, 2, 5 ]
 
seen = set()
unique = []
duplicate = []
for x in my_list:
    if x not in seen:
        unique.append(x)
        seen.add(x)
    else:
        duplicate.append(x)
 
print(duplicate, " are duplicates.")
print(unique, " are unique.")
{{< / highlight >}}

Output

Hugo - Syntax Highlighting example

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.