The Problem
When posting snippets of regular expression code inside code blocks (as in this example) it would be helpful to apply syntax highlighting.
Because this site uses Hugo, which uses Chroma, which does not yet include support for highlighting regular expressions another approach is required.
The Process
A web search for regular expression syntax highlighting returned some discussions of the general question:
- Is there a good syntax highlighting hint for regular expressions?
- How to handle regex syntax highlighting?
The responses are in the specific context of Meta.StackExchange and seem to focus on displaying regular expressions on that site. Nevertheless, many of the responses seem to miss the larger point. There are cases where it would be desirable and helpful to highlight syntax and there doesn’t appear to be a direct way to do that in that or many other contexts.
Even attempting to partially highlight the regex through another language’s syntax highlighting doesn’t appear to provide any useful options.
The Solution
There is no clear solution at present.
There seems to be good options for regular expression syntax highlighting in some contexts.
For instance, Steven Levithan released a Regex Colorizer which he discusses in his Regex Syntax Highlighter post. This seems a good option for some applications, but doesn’t seem applicable for static site generation with programs like Hugo.
For use in Chroma and Hugo, a solution would likely come in the form of an update to Chroma to include support for a general regular expression syntax.
The Workaround
For now, a workround is necessary.
In this section we’ll use the example from the first linked article to explore some options.
No language tag
```\n([#{"\w])
Not providing a language tag leads to an appearance inconsistent with the rest of the site.
Some sort of language tag seems necessary.
Perl tag
```\n([#{"\w])
JavaScript tag
```\n([#{"\w])
Bash tag
```\n([#{"\w])
But, as may reasonably be expected, many language tags result in confusing and nonsensical highlighting, which is completely undesirable.
We need to use a tag that will format the code block without highlighting the text.
Text tag
```\n([#{"\w])
The text
tag causes Chroma to format the code block but leaves the text itself unhighlighted.
It is not a great option, but at least it doesn’t produce misleading or inconsistent results.