Adding Terraform Syntax Highlighting to rehype-highlight
12/28/2021
rehype-highlight uses lowlight, which has only 35 languages by default. You can add additional languages, but this is not an entirely obvious process when you are using rehype-highlight as a plugin for next-mdx-remote
, like I am.
Get Terraform Highlighting Definition
There is a highlight.js definition file for Terraform available in this GitHub project. I downloaded the terraform.js
file and put it in my app root as highlightjs-terraform.js
.
To use it, I added this line to my [post].js
file:
import {definer as terraform} from '../../highlightjs-terraform';
Modify It
The terraform.js
file, at present, needs this adjustment made to it:
@@ -13,8 +13,6 @@
* Category: scripting
*/
-var module = module ? module : {}; // shim for browser use
-
function hljsDefineTerraform(hljs) {
var NUMBERS = {
className: 'number',
Pass Options to rehype-highlight
Not finding an example of this elsewhere, this one was a bit harder to piece together. Here is the trail of breadcrumbs I followed:
This blog post says that you can add a language to rehype-highlight, which was encouraging.
Documentation for MDX on using plugins says options.remarkPlugins
are of the form [plugin, options]
.
The options for rehypePlugins
are documented here with an example like this:
rehypePlugins: [[rehypeKatex, {throwOnError: true, strict: true}]]
rehype-highlight uses lowlight, which has 35 of the languages that highlight.js has. The documentation for retype-highlight mentions registering additional languages. But the example provided doesn't help.
It does, however, mention options.languages
as:
Register more languages
(Record<string, Function>, default: {})
. Each key/value pair passed as arguments to lowlight.registerLanguage.
The documentation for lowlight shows how to register a language, like this:
lowlight.registerLanguage('xml', xml)
So, whatever we pass in plugins
to rehype-highlight is going to get used in a call to lowlight.registerLanguage()
. That's all I needed. Here's the resulting line with some context:
mdxOptions: {
rehypePlugins: [[rehypeHighlight, {languages: {'tf': terraform}}]],
},