-
Notifications
You must be signed in to change notification settings - Fork 66.8k
Expand file tree
/
Copy pathparse-info-string.js
More file actions
32 lines (27 loc) · 982 Bytes
/
parse-info-string.js
File metadata and controls
32 lines (27 loc) · 982 Bytes
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
// Based on https://spec.commonmark.org/0.30/#info-string
// Parse out info strings on fenced code blocks, example:
// ```javascript lineNumbers:left copy:all annotate
// becomes...
// node.lang = javascript
// node.meta = { lineNumbers: 'left', copy: 'all', annotate: true }
// Also parse equals signs, where id=some-id becomes { id: 'some-id' }
import { visit } from 'unist-util-visit'
const matcher = (node) => node.type === 'code' && node.lang
export default function parseInfoString() {
return (tree) => {
visit(tree, matcher, (node) => {
node.meta = strToObj(node.meta)
// Temporary, remove {:copy} to avoid highlight parse error in translations.
node.lang = node.lang.replace('{:copy}', '')
})
}
}
function strToObj(str) {
if (!str) return {}
return Object.fromEntries(
str
.split(/\s+/g)
.map((k) => k.split(/[:=]/)) // split by colon or equals sign
.map(([k, ...v]) => [k, v.length ? v.join(':') : true]),
)
}