rehype plugin to highlight code blocks in HTML with Prism
npm install @mapbox/rehype-prism
rehype plugin to highlight code blocks in HTML with [Prism] (via [refractor]).
(If you would like to highlight code blocks with highlight.js, instead, check out rehype-highlight.)
Best suited for usage in Node.
If you would like to perform syntax highlighting in the browser, you should look into less heavy ways to use refractor.
```
npm install @mapbox/rehype-prism
rehype().use(rehypePrism, [options])
Syntax highlights pre > code.
Under the hood, it uses [refractor], which is a virtual version of [Prism].
The code language is configured by setting a language-{name} class on the element.
You can use any [language supported by refractor].
If no language-{name} class is found on a element, it will be skipped.
#### options.ignoreMissing
Type: boolean.false
Default: .
By default, if {name} does not correspond to a [language supported by refractor] an error will be thrown.
If you would like to silently skip elements with invalid languages, set this option to true.
#### options.alias
Type: Record.undefined
Default: .
Provide [aliases] to refractor to register as alternative names for a language.
Use this package as a rehype plugin.
Some examples of how you might do that:
`js
const rehype = require('rehype');
const rehypePrism = require('@mapbox/rehype-prism');
rehype()
.use(rehypePrism)
.process(/ some html /);
`
`js
const unified = require('unified');
const rehypeParse = require('rehype-parse');
const rehypePrism = require('@mapbox/rehype-prism');
unified()
.use(rehypeParse)
.use(rehypePrism)
.processSync(/ some html /);
`
If you'd like to get syntax highlighting in Markdown, parse the Markdown (with remark-parse), convert it to rehype, then use this plugin.
`js
const unified = require('unified');
const remarkParse = require('remark-parse');
const remarkRehype = require('remark-rehype');
const rehypePrism = require('@mapbox/rehype-prism');
unified()
.use(remarkParse)
.use(remarkRehype)
.use(rehypePrism)
.process(/ some markdown /);
`
Why does rehype-prism copy the
language- class to the <pre> tag?
Prism recommends adding the language- class to the tag like this:
`html`
p { color: red }
It bases this recommendation on the HTML5 spec. However, an undocumented behavior of their JavaScript is that, in the process of highlighting the code, they also copy the language- class to the
tag:`
html`
p { color: red }
pre[class*="language-"]`. So in order for people using rehype-prism to get the most out of these themes, we decided to do the same.This resulted in many Prism themes relying on this behavior by using CSS selectors like
[Prism]: http://prismjs.com/
[refractor]: https://github.com/wooorm/refractor
[language supported by refractor]: https://github.com/wooorm/refractor#syntaxes
[aliases]: https://github.com/wooorm/refractor#refractoraliasname-alias