forked from mapbox/rehype-prism
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
62 lines (50 loc) · 1.39 KB
/
index.js
File metadata and controls
62 lines (50 loc) · 1.39 KB
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
'use strict';
const visit = require('unist-util-visit');
const nodeToString = require('hast-util-to-string');
const refractor = require('refractor');
module.exports = options => {
options = options || {};
if ('registerSyntax' in options) {
if (Array.isArray(options.registerSyntax)) {
for (const syntax of options.registerSyntax) {
refractor.register(syntax);
}
} else {
throw 'options.registerSyntax should be an array of additional syntaxes';
}
}
return tree => {
visit(tree, 'element', visitor);
};
function visitor(node, index, parent) {
if (!parent || parent.tagName !== 'pre' || node.tagName !== 'code') {
return;
}
const lang = getLanguage(node);
if (lang === null) {
return;
}
let result;
try {
parent.properties.className = (parent.properties.className || []).concat(
'language-' + lang
);
result = refractor.highlight(nodeToString(node), lang);
} catch (err) {
if (options.ignoreMissing && /Unknown language/.test(err.message)) {
return;
}
throw err;
}
node.children = result;
}
};
function getLanguage(node) {
const className = node.properties.className || [];
for (const classListItem of className) {
if (classListItem.slice(0, 9) === 'language-') {
return classListItem.slice(9).toLowerCase();
}
}
return null;
}