-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
58 lines (48 loc) · 1.23 KB
/
index.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
const CodeMirror = require('codemirror/addon/runmode/runmode.node');
module.exports = function (code, lang, mode) {
let out = '';
lang = lang.toLowerCase();
let modeName = lang;
if (!mode) mode = lang;
require('codemirror/mode/meta');
CodeMirror.modeInfo.forEach(function (info) {
if (info.mime === lang) {
modeName = info.mode;
} else if (info.name.toLowerCase() === lang) {
modeName = info.mode;
lang = info.mime;
}
});
// TODO: We never use lang, which makes me think this is wrong?
if (!CodeMirror.modes[modeName]) {
require(`codemirror/mode/${modeName}/${modeName}.js`);
}
function esc(str) {
const map = {
'<': '<',
'/': '/',
'&': '&',
'>': '>',
};
return str.replace(/[<&/>]/g, ch => map[ch]);
}
let curStyle = null;
let accum = '';
function flush() {
accum = esc(accum);
if (curStyle) {
out += `<span class="${curStyle.replace(/(^|\s+)/g, '$1cm-')}">${accum}</span>`;
} else out += accum;
}
CodeMirror.runMode(code, mode, function (text, style) {
if (style !== curStyle) {
flush();
curStyle = style;
accum = text;
} else {
accum += text;
}
});
flush();
return out;
};