Skip to content

Commit 961dd2c

Browse files
Feat: Highligh variables, objects and functions.
1 parent b6d5ee9 commit 961dd2c

2 files changed

Lines changed: 33 additions & 15 deletions

File tree

demo/main.js

Lines changed: 24 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -39,19 +39,30 @@ const TOKEN_RE = /(#[^\n]*)|((?:\b[fFrRbBuU]{1,2})?(?:"""[\s\S]*?"""|'''[\s\S]*?
3939

4040
const esc = (s) => s.replace(/[&<>]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' }[c]));
4141

42-
const highlight = (src) => esc(src).replace(TOKEN_RE, (m, com, str, num, word) => {
43-
if (com) return `<span class="tk-com">${com}</span>`;
44-
if (str) return `<span class="tk-str">${str}</span>`;
45-
if (num) return `<span class="tk-num">${num}</span>`;
46-
if (word) {
47-
if (KW.has(word)) return `<span class="tk-kw">${word}</span>`;
48-
if (LIT.has(word)) return `<span class="tk-lit">${word}</span>`;
49-
if (BI.has(word)) return `<span class="tk-bi">${word}</span>`;
50-
return word;
51-
}
52-
return m;
53-
});
54-
42+
const highlight = (src) => {
43+
const escaped = esc(src);
44+
return escaped.replace(TOKEN_RE, (m, com, str, num, word, offset, fullStr) => {
45+
if (com) return `<span class="tk-com">${com}</span>`;
46+
if (str) return `<span class="tk-str">${str}</span>`;
47+
if (num) return `<span class="tk-num">${num}</span>`;
48+
if (word) {
49+
const isEntity = fullStr[offset - 1] === '&' && fullStr[offset + word.length] === ';';
50+
if (isEntity) return word;
51+
52+
if (KW.has(word)) return `<span class="tk-kw">${word}</span>`;
53+
if (LIT.has(word)) return `<span class="tk-lit">${word}</span>`;
54+
if (BI.has(word)) return `<span class="tk-bi">${word}</span>`;
55+
56+
const isFunction = /^\s*\(/.test(fullStr.slice(offset + word.length));
57+
if (isFunction) {
58+
return `<span class="tk-func">${word}</span>`;
59+
} else {
60+
return `<span class="tk-var">${word}</span>`;
61+
}
62+
}
63+
return m;
64+
});
65+
};
5566
const jar = CodeJar(ed, (editor) => {
5667
editor.innerHTML = highlight(editor.textContent);
5768
}, {

demo/style.css

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,18 @@
66
line-height: 1.625;
77
}
88

9-
#ed { tab-size: 4; }
9+
#ed {
10+
tab-size: 4;
11+
white-space: pre;
12+
outline: none;
13+
font-variant-ligatures: none;
14+
}
1015

1116
.tk-kw { color: #c586c0; }
1217
.tk-lit { color: #569cd6; }
1318
.tk-bi { color: #4ec9b0; }
1419
.tk-num { color: #b5cea8; }
1520
.tk-str { color: #ce9178; }
16-
.tk-com { color: #6a9955; font-style: italic; }
21+
.tk-com { color: #6a9955; font-style: italic; }
22+
.tk-var { color: #9cdcfe; }
23+
.tk-func { color: #dcdcaa; }

0 commit comments

Comments
 (0)