2022-09-04 20:40:58 +02:00
|
|
|
import type { Plugin, Transformer } from 'unified'
|
|
|
|
import type { Literal } from 'unist'
|
2022-02-23 00:38:50 +01:00
|
|
|
import { visit } from 'unist-util-visit'
|
2022-09-04 20:40:58 +02:00
|
|
|
import type { Highlighter } from 'shiki'
|
2022-02-23 00:38:50 +01:00
|
|
|
|
|
|
|
export interface RemarkSyntaxHighlightingPluginOptions {
|
|
|
|
highlighter: Highlighter
|
|
|
|
}
|
|
|
|
|
|
|
|
export type RemarkSyntaxHighlightingNode = Literal<string> & {
|
|
|
|
lang: string
|
|
|
|
meta: string
|
|
|
|
children: undefined
|
|
|
|
}
|
|
|
|
|
|
|
|
export const remarkSyntaxHighlightingPlugin: Plugin<
|
|
|
|
[RemarkSyntaxHighlightingPluginOptions],
|
|
|
|
Literal<string, RemarkSyntaxHighlightingNode>
|
|
|
|
> = (options) => {
|
|
|
|
const transformer: Transformer<RemarkSyntaxHighlightingNode> = (tree) => {
|
|
|
|
visit<RemarkSyntaxHighlightingNode, string>(tree, 'code', (node) => {
|
|
|
|
node.type = 'html'
|
|
|
|
node.children = undefined
|
|
|
|
node.value = options.highlighter.codeToHtml(node.value, {
|
|
|
|
lang: node.lang
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
return transformer
|
|
|
|
}
|