The Problem
Hugo’s code fence syntax produced code blocks but didn’t produce code with syntax highlighting.
The Process
A web search for syntax highlighting in Hugo returned some Hugo documentation pages:
While these offered some background information, they didn’t help resolve the issue.
That search also returned this article, which provided an example for one solution of adding the following to the Hugo config.toml
file:
[markup.highlight]
guessSyntax = true
This succeeded in producing code with syntax highlighting, but offered less control over the outcome since it relies on Hugo correctly guessing the desired syntax.
Finding a more flexible and configurable solution required more searching.
Another web search for Hugo syntax highlighting of Bash commands returned “Displaying Shell Command Code Blocks in Hugo” by Brian P. Hogan, which pointed toward the desired solution.
The Solution
Code fences with tags
Previous uses of code fences on this site had employed bare code fences like the following:
```
<code block>
```
But appending the code name immediately after the opening code fence triggers the appropriate syntax highlighting:
```toml
<code block>
```
With this knowledge the List of Chroma Highlighting Languages provided in the Hugo documentation is helpful to determine the specific tag to use to trigger syntax highlighting for a specific language.
Searching with Regular Expressions in VS Code
This type of update needed to be applied to all previous articles. Doing that manually could take quite a while. Fortunately, this VSCode subreddit post provided the insight that regular expressions could be used in Visual Studio Code’s find/replace functionality.
The Search Pattern
Finding only the opening code fence and not the closing code fence with regular expressions relied on the insight that in nearly every case the closing code fence was followed by a blank line while the opening code fence was followed by a line with either a word character, a hashtag (#), a parenthesis ("), or an opening brace ({). That led to using the following regular expression search pattern:
```\n([#{"\w])
The Replacement Pattern
The desired replacement pattern depended on the language being used, but was typically consistent throughout an individual article. That led to using the following replacement pattern, when, for example, the article utilized Bash commands:
```bash\n$1
The process
Each article had to be worked through individually for several reasons:
- because the code language could vary between articles,
- to catch the few cases that didn’t fit the search pattern, and
- to confirm that replacements yielded expected results.
Through that process all articles on the site were updated to reflect the appropriate syntax highlighting.