s

Hugo Syntax Highlighting



How to use syntax highlighting for code in a blog post.

The docs outline how to use Syntax Highlighting.

There is a default highlight configuration.

The docs note that if you use pygmentsUseClasses=true in your site config then you need a style sheet. You can generate a style sheet with Hugo:

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

For my site the CSS style sheets are in the assets folder so I moved the syntax.css file here. I am using Sass which is a CSS preprocessor. (The scss syntax of Sass is a superset of CSS and therefore a CSS file is already a valid Sass file. Sass allows you to break up CSS into manageable bites, define variables and perform math.)

To use a Sass file the filename has a scss extension instead of a css use the toCSS function in a pipeline in front of the minify function. I first renamed syntax.css to syntax.scss. Then in the head.html template I used


    {{ $css := resources.Get "css/syntax.scss"  | toCSS | minify | fingerprint }}
    <link rel="stylesheet" href="{{ $css.RelPermalink  }}">

instead of


       <link rel="stylesheet" href="{{ "css/syntax.css" | relURL  }}">

In the configuration file

This is the default highlight configuration:

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

To be able to use code fences (using backticks) you need to set pygmentsCodeFences = true in the site configuration file.

pygmentsCodeFences = true

Alternatively use the built in Highlight Shortcode. This takes just a single parameter for the programming language to be highlighted and requires a closing shortcode.

`

`

As I am more used to using code fences in markdown I have set `pygmentsCodeFences = true`. 


---

The syntax highlighting I am using has a very dark background. I am changing it to a lighter background.
The gallery of available styles is at <https://xyproto.github.io/splash/docs/>

Instead of using the `monokai` style I am changing to `monokailight`.
https://xyproto.github.io/splash/docs/monokailight.html


Generate a new syntax highlight sheet.  
```go
hugo gen chromastyles --style=monokailight > syntax.scss


```

Then move this to the `assets` folder of the theme directory.

`mv syntax.scss themes/mytheme/assets/css`s


Tech used:
  • Hugo
  • CSS