saturn
- 187 commits
- 2 branches
- 0 tags
- updated
- CI 2/2
highlight.mjs
6.1 KB · 136 lines
1// Build-time syntax highlighting for code blocks. No runtime JS and no inline styles, so the2// CSP holds. Colors live in global.css (--syn-* per theme), the same roles as the Zed, Helix3// and Warp themes.4//5// mise run highlight blog/some-post/index.html highlight every6// <pre><code class="language-X"> block in the file(s), in place7// node scripts/highlight.mjs go < snippet.go print highlighted HTML for a snippet8//9// Shiki lives in scripts/node_modules (npm ci --prefix scripts); scripts/ is never deployed.10//11// Blocks that already contain hl- spans, or any other tag, are left alone, so it is safe to12// run again. "text" and "plaintext" blocks are skipped.13//14// How it works: a TextMate theme whose colors are role markers (#000001, #000002, ...).15// Shiki tokenizes with VS Code's grammars; each token's marker becomes a class.16import { createHighlighter } from "shiki";17import { readFileSync, writeFileSync } from "node:fs";1819// role -> TextMate scopes (the most specific selector wins, as in any TextMate theme)20const ROLES = {21 comment: ["comment", "punctuation.definition.comment"],22 variable: [23 "variable", "variable.other", "variable.parameter", "variable.other.property",24 "variable.other.object.property", "variable.other.member", "meta.object-literal.key",25 "support.type.property-name", "entity.other.attribute-name", "entity.name.tag",26 "punctuation.definition.variable", "meta.definition.variable",27 ],28 self: ["variable.language"],29 string: ["string", "string punctuation.definition.string", "markup.raw", "markup.inline.raw"],30 escape: ["constant.character.escape", "string.regexp", "constant.other.placeholder"],31 constant: [32 "constant.numeric", "constant.language", "constant.other", "support.constant",33 "variable.other.constant", "variable.parameter.option", "entity.name.function.decorator",34 "meta.decorator", "meta.annotation",35 ],36 keyword: [37 "keyword", "storage.type", "storage.modifier", "keyword.control", "keyword.declaration",38 "punctuation.definition.template-expression", "punctuation.section.embedded",39 ],40 type: [41 "entity.name.type", "entity.name.class", "support.type", "support.class",42 "entity.other.inherited-class", "source.go storage.type", "source.go entity.name.type",43 ],44 function: [45 "entity.name.function", "support.function", "meta.function-call entity.name.function",46 "variable.function", "meta.function-call.generic",47 ],48 builtin: ["support.function.builtin", "entity.name.function.support.builtin"],49 punct: ["keyword.operator", "punctuation", "meta.brace", "punctuation.separator"],50 heading: ["markup.heading", "entity.name.section"],51 added: ["markup.inserted"],52 removed: ["markup.deleted"],53 changed: ["markup.changed"],54 link: ["markup.underline.link", "string.other.link"],55};56// word operators (and, in, typeof, new) stay keywords; shell builtins read as commands57const OVERRIDES = [58 ["keyword", ["keyword.operator.word", "keyword.operator.expression", "keyword.operator.new"]],59 ["function", ["source.shell support.function"]],60];6162const names = Object.keys(ROLES);63const marker = (i) => "#0000" + (i + 1).toString(16).padStart(2, "0");64const theme = {65 name: "roles",66 type: "dark",67 colors: { "editor.foreground": "#000000", "editor.background": "#ffffff" },68 tokenColors: [69 { settings: { foreground: "#000000" } },70 ...names.map((n, i) => ({ scope: ROLES[n], settings: { foreground: marker(i) } })),71 ...OVERRIDES.map(([n, scope]) => ({ scope, settings: { foreground: marker(names.indexOf(n)) } })),72 ],73};74const roleOf = Object.fromEntries(names.map((n, i) => [marker(i).toUpperCase(), n]));7576const escape = (s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");77const unescape = (s) =>78 s79 .replace(/&#x([0-9a-f]+);/gi, (_, h) => String.fromCodePoint(parseInt(h, 16)))80 .replace(/&#(\d+);/g, (_, d) => String.fromCodePoint(Number(d)))81 .replace(/"/g, '"').replace(/'/g, "'")82 .replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&");8384const PLAIN = new Set(["text", "plaintext", "txt", "plain"]);85let highlighter;86async function load(langs) {87 highlighter ??= await createHighlighter({ themes: [theme], langs: [] });88 for (const lang of langs) {89 if (!highlighter.getLoadedLanguages().includes(lang)) await highlighter.loadLanguage(lang);90 }91 return highlighter;92}9394export async function highlight(code, lang) {95 const hl = await load([lang]);96 return hl97 .codeToTokensBase(code.replace(/\n$/, ""), { lang, theme: "roles" })98 .map((line) =>99 line100 .map((t) => {101 const role = roleOf[(t.color || "").toUpperCase()];102 return role ? `<span class="hl-${role}">${escape(t.content)}</span>` : escape(t.content);103 })104 .join(""),105 )106 .join("\n");107}108109const BLOCK = /(<pre[^>]*>\s*<code\b[^>]*\bclass="[^"]*\blanguage-([\w+#-]+)[^"]*"[^>]*>)([\s\S]*?)(<\/code>\s*<\/pre>)/g;110111export async function highlightFile(path) {112 const html = readFileSync(path, "utf8");113 const jobs = [];114 for (const m of html.matchAll(BLOCK)) {115 const [whole, open, lang, body, close] = m;116 if (PLAIN.has(lang) || /</.test(body)) continue; // plain, already highlighted, or hand-marked117 jobs.push({ whole, html: open + (await highlight(unescape(body), lang)) + close });118 }119 let out = html;120 for (const j of jobs) out = out.replace(j.whole, () => j.html);121 if (out !== html) writeFileSync(path, out);122 console.error(`${path}: ${jobs.length} block(s) highlighted`);123}124125if (import.meta.url === `file://${process.argv[1]}`) {126 const args = process.argv.slice(2);127 if (!args.length) {128 console.error("usage: node scripts/highlight.mjs <lang> < file\n node scripts/highlight.mjs page.html [...]");129 process.exit(1);130 }131 if (args.every((a) => a.endsWith(".html"))) {132 for (const f of args) await highlightFile(f);133 } else {134 process.stdout.write((await highlight(readFileSync(0, "utf8"), args[0])) + "\n");135 }136}