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.
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 befalse
- 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:
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.
Conclusion
Congratulations! You are now able to hightlight code snippet in your Hugo blog post using syntax highlighting feature.