-
Notifications
You must be signed in to change notification settings - Fork 0
/
highlight_html.js
90 lines (76 loc) · 2.87 KB
/
highlight_html.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
79
80
81
82
83
84
85
86
87
88
89
90
/// More or less straight copied from https://github.com/wooorm/starry-night, see that license here https://github.com/wooorm/starry-night/blob/c73aac7b8bff41ada86747f668dd932a791b851b/notice
import fs from 'node:fs/promises'
import remarkParse from 'remark-parse'
import remarkRehype from 'remark-rehype'
import rehypeStringify from 'rehype-stringify'
import {unified} from 'unified'
/**
* @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 {common, createStarryNight} 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>}
*/
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}]
})
})
}
}
const file_path = process.argv[2];
const file = await unified()
.use(remarkParse)
.use(remarkRehype)
.use(rehypeStarryNight)
.use(rehypeStringify)
.process(await fs.readFile(file_path))
console.log(String(file));