This repository has been archived by the owner on Jan 12, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzhighlight.js
73 lines (69 loc) · 2.05 KB
/
zhighlight.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
import tokenize from "./tokenize.js"
function stringify(tok) {
if (tok.comment) {
return `<span style="color:#008000">${tok.comment}</span>`;
}
if (tok.id === "(string)") {
return `<span style="color:#a31515">"${tok.string}"</span>`;
}
if (tok.id === "(number)") {
return `<span style="color:#09885a">${tok.string}</span>`
}
if (tok.id === "(keyword)" || tok.id === "=>" || tok.id === "<-") {
return `<span style="color:#0000ff">${tok.string ? tok.string : tok.id}</span>`
}
if (tok.alphanumeric) {
if (tok.id.includes("!")) {
return `<span style="color:#267f99">${tok.id}</span>`;
}
return `<span style="color:#261069">${tok.id}</span>`;
}
if (tok.string) {
return tok.string;
}
return tok.id;
}
function len(tok) {
if (tok.comment) {
return tok.comment.length;
}
if (tok.string) {
if (tok.id === "(string)") {
return tok.string.length + 2;
}
return tok.string.length;
}
return tok.id.length;
}
/**
*
* @param {string} code The Z to highlight
*/
function syntaxHighlight(code) {
code = code.replace(/>/g, ">").replace(/</g, "<");
const tokGen = tokenize(code, true);
const res = [];
let addedLength = 0;
for (let tok, prevTok = {};
(tok = tokGen()) !== undefined;) {
if (prevTok.lineNumber !== tok.lineNumber) {
addedLength = 0;
}
if (typeof res[tok.lineNumber] !== "string") {
res[tok.lineNumber] = "";
}
const old = res[tok.lineNumber];
res[tok.lineNumber] = old.padEnd(tok.columnNumber + addedLength) + stringify(tok);
addedLength += stringify(tok).length - len(tok);
prevTok = tok;
}
return res.join("\n");
}
function main() {
const zCodeBlocks = Array.from(document.querySelectorAll(`[lang="z"]`))
zCodeBlocks.forEach(codeBlock => {
const theZ = codeBlock.innerHTML;
codeBlock.innerHTML = syntaxHighlight(theZ);
})
}
export default main;