-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrehype-starry-night.js
78 lines (64 loc) · 2.07 KB
/
rehype-starry-night.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
* @typedef {import('hast').Root} Root
* @typedef {import('hast').ElementContent} ElementContent
* @typedef {import('@wooorm/starry-night').Grammar} Grammar
*
* @typedef Options
* Configuration (optional)
* @property {Array<Grammar>} [grammars]
* Grammars to support (defaults: `common`).
*/
import { createStarryNight, common } from "@wooorm/starry-night";
import { visit } from "unist-util-visit";
import { toString } from "hast-util-to-string";
/**
* Plugin to highlight code with `starry-night`.
*
* @type {import('unified').Plugin<[Options?], Root>}
*/
export default function rehypeStarryNight(options = {}) {
const grammars = options.grammars || common;
const starryNightPromise = createStarryNight(grammars);
const prefix = "language-";
return async function (tree) {
const starryNight = await starryNightPromise;
visit(tree, "element", function (node, index, parent) {
if (!parent || index === null || node.tagName !== "pre") {
return;
}
const head = node.children[0];
if (
!head ||
head.type !== "element" ||
head.tagName !== "code" ||
!head.properties
) {
return;
}
const classes = head.properties.className;
if (!Array.isArray(classes)) return;
const language = classes.find(
(d) => typeof d === "string" && d.startsWith(prefix)
);
if (typeof language !== "string") return;
const scope = starryNight.flagToScope(language.slice(prefix.length));
// Maybe warn?
if (!scope) return;
const fragment = starryNight.highlight(toString(head), scope);
const children = /** @type {Array<ElementContent>} */ (fragment.children);
parent.children.splice(index, 1, {
type: "element",
tagName: "div",
properties: {
className: [
"highlight",
"highlight-" + scope.replace(/^source\./, "").replace(/\./g, "-"),
],
},
children: [
{ type: "element", tagName: "pre", properties: {}, children },
],
});
});
};
}