$$ \newcommand\Tr{\mathrm{Tr}} \newcommand{\braket}[2]{\langle #1 \mid #2 \rangle} \newcommand\I{\mathbb{I}} \newcommand{\avg}[1]{\left< #1 \right>} \newcommand{\RD}{D} \newcommand{\ri}{\mathrm{i}} \DeclareMathOperator{\sign}{sign} \DeclareMathOperator{\Sign}{Sign} \newcommand{\ii}{\mathrm i} \newcommand{\vv}{\mathrm v} \newcommand{\ff}{\mathrm f} \newcommand{\mm}{\mathrm m} \newcommand{\ee}{\mathrm e} \newcommand{\xx}{\mathrm x} \newcommand{\RR}{\mathrm R} \newcommand{\dd}{\mathrm d} \newcommand{\FF}{\mathrm F} \newcommand{\BB}{\mathrm B} \newcommand{\vph}{v_{\mathrm{ph}}} $$

How to Add and Modify Hugo Syntax Highlighting

This tutorial will show you how to add and modify Hugo Syntax Highlighting.

Introduction

Sometimes we have to include code snippet in our blog. However, using triple backsticks ``` is not enough because it doesn’t highlight some keywords of the code language such as bash, csharp, etc.

Requirements

This tutorial is based on ghostwriter theme. You should follow How to Create Hugo Site tutorial if you haven’t create one. You could also use other theme because the idea is the same. Below is the sample post from previous tutorial where we display code snippet.

original-syntax-highlighting

Add Syntax Highlighting

The existing ghostwriter theme already has its syntax highlighing style in themes/ghostwriter/static/dist/syntax.css. However, there are two ways to modify it. Please use either of these:

1. Highlight Markup

Modify config file config.yml, config.toml, or config.json like below.

pygmentsUseClasses: false
pygmentsCodefences: true

markup:
  highlight:
    codeFences: true
    guessSyntax: false
    hl_Lines: ""
    lineNoStart: 1
    lineNos: false
    lineNumbersInTable: true
    noClasses: true
    tabWidth: 2 
    style: "dracula"

2. pygmentsStyle

Modify config file config.yml, config.toml, or config.json like below.

pygmentsUseClasses: false
pygmentsCodefences: true
pygmentsStyle: "dracula"

markup:
  highlight:
    codeFences: true
    guessSyntax: false
    hl_Lines: ""
    lineNoStart: 1
    lineNos: false
    lineNumbersInTable: true
    noClasses: true
    tabWidth: 2

Takeaway

There are two points we should notice from above changes. Those are

  • Set pygmentsUseClasses to be false
  • Add style either in highlight markup or pygmentsStyle

Hugo uses Chroma style by default. Please see this gallery for available Chroma Styles.

Result

Result from above change:

highlighted-syntax

From above result, we need to change site.css because every line of code has background color #f1f0ea.

code { padding: 2px 4px; font-size: 90%; border-radius: 4px; background-color: #f1f0ea; }

If you remove background-color, then you will see below result.

post-code-snippet

Conclusion

Congratulations! You are now able to hightlight code snippet in your Hugo blog post using syntax highlighting feature.