2023-10-23 23:11:59 +02:00
|
|
|
import type { Plugin, Transformer } from "unified"
|
|
|
|
import type { Literal, Node } from "unist"
|
|
|
|
import { visit } from "unist-util-visit"
|
|
|
|
import type { Highlighter } from "shiki"
|
2022-02-23 00:38:50 +01:00
|
|
|
|
|
|
|
export interface RemarkSyntaxHighlightingPluginOptions {
|
|
|
|
highlighter: Highlighter
|
|
|
|
}
|
|
|
|
|
2023-07-14 23:50:20 +02:00
|
|
|
export interface RemarkSyntaxHighlightingNode extends Node {
|
2022-02-23 00:38:50 +01:00
|
|
|
lang: string
|
|
|
|
meta: string
|
|
|
|
children: undefined
|
2023-07-14 23:50:20 +02:00
|
|
|
value: string
|
|
|
|
data: Record<string, unknown>
|
2022-02-23 00:38:50 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
export const remarkSyntaxHighlightingPlugin: Plugin<
|
|
|
|
[RemarkSyntaxHighlightingPluginOptions],
|
2023-07-14 23:50:20 +02:00
|
|
|
Literal
|
2022-02-23 00:38:50 +01:00
|
|
|
> = (options) => {
|
|
|
|
const transformer: Transformer<RemarkSyntaxHighlightingNode> = (tree) => {
|
2023-10-23 23:11:59 +02:00
|
|
|
visit<RemarkSyntaxHighlightingNode, string>(tree, "code", (node) => {
|
|
|
|
node.type = "html"
|
2022-02-23 00:38:50 +01:00
|
|
|
node.children = undefined
|
|
|
|
node.value = options.highlighter.codeToHtml(node.value, {
|
2023-10-23 23:11:59 +02:00
|
|
|
lang: node.lang,
|
2022-02-23 00:38:50 +01:00
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
return transformer
|
|
|
|
}
|