Syntax Highlighting in Hugo

Mainly there are two ways of syntax highlighting. One is server-side and the other is client-side. Names are already self-explanatory, client-side highlighting occurs on the user’s browser via javascript. Highlight.js is one of the popular libraries which covers crazy amount of languages. On the other hand, in server-side syntax highlighting, the styling information is already embedded in the HTML. We add syntax styling information before serving the website using some programs. Hugo’s default highlighter is Chroma which is written in Go and based on Pygments. So, I chose to go with the default option since it’s faster and I don’t like to add dependencies.

I’ve set highlight options in config.toml like this:

[markup.highlight]
      codeFences = true
      guessSyntax = true
      hl_Lines = ""
      lineNoStart = 1
      lineNos = true
      lineNumbersInTable = true
      tabWidth = 4
      noClasses = false

You can add the style option in the configuration file, e.g. style = monokai or any other preset you like. Here you can see all available styles and check out how they look.

If you want to make styling changes on inline code blocks, borders, margins, and font of code blocks etc., you’ll need a custom css file. You can generate the css file based on the existing monokai style then edit the way you like.

hugo gen chromastyles --style=monokai > highlight.css

Before editing the styling right away, you’ll need to set two more settings. These two should be top level like baseurl or title in your configuration file, do not place under markup.highlight.

Chroma uses hard-coded styling (inline CSS in HTML), to be able to edit CSS classes you need to tell chroma to use CSS classes instead of embed styling in HTML.

pygmentsUseClasses = true

Highlighting for code fences isn’t enabled by default. So, you need to add this line too in your config file.

pygmentsCodefences = true

By the way, we are still using Chroma, not Pygments. Don’t let those 2 lines confuse you. Lastly, the original docs: Hugo Docs: Syntax Highligting which I think lacks some detail.

Have Fun!

Next Episode

published on 29.08.2020

My experience with Hugo has been pretty good so far. It’s fast and flexible. Ever since I started using Hugo, I’ve been improving my website with small tweaks. In this post, I am going to share some tricks and workarounds I’ve found online while working with Hugo. Besides that, …

Previous Episode

published on 23.08.2020

In Hugo, to loop through list of items we use Range function which comes from go language. range, iterates over a map, slice or array. […] {{ range .Site.RegularPages }} {{ .Title }} {{ end }} Also, notice inside range the scope is different. .Title refers to the page in current iteration. If …

TAG CLOUD