@@ -0,0 +1,240 @@
1+import { readFileSync } from "node:fs";
2+import { createRequire } from "node:module";
3+import { dirname, join } from "node:path";
4+import Parser from "tree-sitter";
5+import JavaScript from "tree-sitter-javascript";
6+import TypeScript from "tree-sitter-typescript";
7+import Markdown from "@tree-sitter-grammars/tree-sitter-markdown";
8+
9+/**
10+ * Syntax highlighting for committed scrollback, once, over the whole block.
11+ * Grammar queries ship with the grammar packages and are consumed as data, so
12+ * a capture name is the only thing that reaches the palette. Colors are the
13+ * TokyoNight `moon` palette, mapped the way `folke/tokyonight.nvim` maps
14+ * capture names to highlight groups. Truecolor only.
15+ */
16+
17+interface Style {
18+ fg?: string;
19+ bg?: string;
20+ bold?: boolean;
21+ italic?: boolean;
22+ underline?: boolean;
23+}
24+
25+/**
26+ * Headings take their level's color from TokyoNight's rainbow, over a 10%
27+ * tint of it, as `@markup.heading.N.markdown` does. The grammar's own query
28+ * names one heading color for all levels, so the level comes from the marker.
29+ */
30+const HEADINGS: Style[] = [
31+ { fg: "#82aaff", bg: "#2c314a" },
32+ { fg: "#ffc777", bg: "#38343c" },
33+ { fg: "#c3e88d", bg: "#32383f" },
34+ { fg: "#4fd6be", bg: "#263644" },
35+ { fg: "#c099ff", bg: "#32304a" },
36+ { fg: "#fca7ea", bg: "#383148" },
37+].map((style) => ({ ...style, bold: true }));
38+
39+/** Inline code: Helix's `@markup.raw.markdown_inline`, not Neovim's plain one. */
40+const INLINE_CODE: Style = { fg: "#82aaff", bg: "#444a73" };
41+
42+/** Capture name to color. A dotted name falls back to its parent. */
43+const STYLES: Record<string, Style | undefined> = {
44+ comment: { fg: "#636da6" },
45+ constant: { fg: "#ff966c" },
46+ "constant.builtin": { fg: "#65bcff" },
47+ constructor: { fg: "#c099ff" },
48+ escape: { fg: "#c099ff" },
49+ function: { fg: "#82aaff" },
50+ "function.builtin": { fg: "#65bcff" },
51+ "function.method": { fg: "#82aaff" },
52+ keyword: { fg: "#fca7ea" },
53+ number: { fg: "#ff966c" },
54+ operator: { fg: "#89ddff" },
55+ property: { fg: "#4fd6be" },
56+ "punctuation.bracket": { fg: "#828bb8" },
57+ "punctuation.delimiter": { fg: "#89ddff" },
58+ "punctuation.special": { fg: "#89ddff" },
59+ string: { fg: "#c3e88d" },
60+ "string.special": { fg: "#65bcff" },
61+ type: { fg: "#65bcff" },
62+ "type.builtin": { fg: "#589ed7" },
63+ variable: { fg: "#c8d3f5" },
64+ "variable.builtin": { fg: "#ff757f" },
65+ "variable.parameter": { fg: "#ffc777" },
66+ // Markdown's queries predate the `@markup` rename; these are the old names.
67+ "text.emphasis": { italic: true },
68+ "text.strong": { bold: true },
69+ "text.literal": { fg: "#c3e88d" },
70+ "text.uri": { underline: true },
71+ "text.reference": { fg: "#65bcff" },
72+};
73+
74+function styleFor(capture: string): Style | undefined {
75+ for (let name = capture; ; name = name.slice(0, name.lastIndexOf("."))) {
76+ const style = STYLES[name];
77+ if (style !== undefined) return style;
78+ if (!name.includes(".")) return undefined;
79+ }
80+}
81+
82+const require = createRequire(import.meta.url);
83+
84+/** A grammar package keeps its queries next to its sources. */
85+function querySource(pkg: string, ...path: string[]): string {
86+ return readFileSync(join(dirname(require.resolve(`${pkg}/package.json`)), ...path), "utf8");
87+}
88+
89+interface Syntax {
90+ parser: Parser;
91+ query: Parser.Query;
92+}
93+
94+function syntax(language: Parser.Language, ...sources: string[]): Syntax {
95+ const parser = new Parser();
96+ parser.setLanguage(language);
97+ return { parser, query: new Parser.Query(language, sources.join("\n")) };
98+}
99+
100+const JS_QUERIES = querySource("tree-sitter-javascript", "queries", "highlights.scm");
101+const TS_QUERIES = querySource("tree-sitter-typescript", "queries", "highlights.scm");
102+
103+const JAVASCRIPT = syntax(JavaScript, JS_QUERIES);
104+/** TypeScript's own query only covers what it adds to JavaScript. */
105+const TYPESCRIPT = syntax(TypeScript.typescript, JS_QUERIES, TS_QUERIES);
106+const TSX = syntax(TypeScript.tsx, JS_QUERIES, TS_QUERIES);
107+
108+/** Fence info string to grammar, for the languages we carry. */
109+const CODE: Record<string, Syntax | undefined> = {
110+ js: JAVASCRIPT,
111+ javascript: JAVASCRIPT,
112+ jsx: JAVASCRIPT,
113+ ts: TYPESCRIPT,
114+ typescript: TYPESCRIPT,
115+ tsx: TSX,
116+};
117+
118+const MARKDOWN = syntax(
119+ Markdown,
120+ querySource("@tree-sitter-grammars/tree-sitter-markdown", "tree-sitter-markdown", "queries", "highlights.scm"),
121+);
122+const MARKDOWN_INLINE = syntax(
123+ Markdown.inline,
124+ querySource(
125+ "@tree-sitter-grammars/tree-sitter-markdown",
126+ "tree-sitter-markdown-inline",
127+ "queries",
128+ "highlights.scm",
129+ ),
130+);
131+
132+/** One styled range of a line, in byte offsets into that line. */
133+interface Span {
134+ start: number;
135+ end: number;
136+ style: Style;
137+}
138+
139+function spansOf(syntax: Syntax, node: Parser.SyntaxNode, offset = 0): Span[] {
140+ const spans: Span[] = [];
141+ for (const capture of syntax.query.captures(node)) {
142+ const style = styleFor(capture.name);
143+ if (style === undefined) continue;
144+ spans.push({ start: offset + capture.node.startIndex, end: offset + capture.node.endIndex, style });
145+ }
146+ return spans;
147+}
148+
149+function parse(syntax: Syntax, text: string): Parser.SyntaxNode {
150+ return syntax.parser.parse(text).rootNode;
151+}
152+
153+function sgr(style: Style): string {
154+ const channel = (code: number, hex: string): string =>
155+ `${code};2;${[1, 3, 5].map((i) => Number.parseInt(hex.slice(i, i + 2), 16)).join(";")};`;
156+ let out = "\x1b[";
157+ if (style.bold) out += "1;";
158+ if (style.italic) out += "3;";
159+ if (style.underline) out += "4;";
160+ if (style.fg !== undefined) out += channel(38, style.fg);
161+ if (style.bg !== undefined) out += channel(48, style.bg);
162+ return `${out.slice(0, -1)}m`;
163+}
164+
165+/**
166+ * Wraps every span in its color. Spans nest, so the innermost one wins; text
167+ * outside any span is reset to plain. The trailing reset closes the whole text,
168+ * so a span may cross a line break and the last line still ends plain.
169+ */
170+function paint(text: string, spans: Span[]): string {
171+ const events: { at: number; open: boolean; span: Span }[] = [];
172+ for (const span of spans) {
173+ if (span.end <= span.start) continue;
174+ events.push({ at: span.start, open: true, span }, { at: span.end, open: false, span });
175+ }
176+ events.sort((a, b) => a.at - b.at || Number(a.open) - Number(b.open));
177+
178+ const active: Span[] = [];
179+ let out = "";
180+ let plain = true;
181+ let at = 0;
182+ const emit = (end: number): void => {
183+ if (end <= at) return;
184+ const style = active.length === 0 ? undefined : active[active.length - 1].style;
185+ if (style === undefined) {
186+ if (!plain) out += "\x1b[0m";
187+ plain = true;
188+ } else {
189+ out += sgr(style);
190+ plain = false;
191+ }
192+ out += text.slice(at, end);
193+ at = end;
194+ };
195+ for (const event of events) {
196+ emit(event.at);
197+ if (event.open) active.push(event.span);
198+ else active.splice(active.indexOf(event.span), 1);
199+ }
200+ emit(text.length);
201+ return plain ? out : `${out}\x1b[0m`;
202+}
203+
204+/**
205+ * Colors one committed block of Markdown. Inline markup is a separate grammar,
206+ * run over the ranges the block grammar hands over, as its injections do.
207+ */
208+export function highlightMarkdown(text: string): string {
209+ const root = parse(MARKDOWN, text);
210+ let spans = spansOf(MARKDOWN, root);
211+ // Two things the grammar's queries predate: a whole heading is colored by its
212+ // level, and inline code carries a background. Both replace what covers them.
213+ for (const inline of root.descendantsOfType("inline")) {
214+ const inlineRoot = parse(MARKDOWN_INLINE, inline.text);
215+ spans.push(...spansOf(MARKDOWN_INLINE, inlineRoot, inline.startIndex));
216+ for (const code of inlineRoot.descendantsOfType("code_span")) {
217+ spans = recolor(spans, code, INLINE_CODE, inline.startIndex);
218+ }
219+ }
220+ for (const heading of root.descendantsOfType(["atx_heading", "setext_heading"])) {
221+ const marker = heading.namedChildren.find((child) => /^(atx|setext)_h/.test(child.type))?.type;
222+ const level = marker === undefined ? 1 : Number(marker.replace(/\D/g, ""));
223+ spans = recolor(spans, heading, HEADINGS[Math.min(level, HEADINGS.length) - 1]);
224+ }
225+ return paint(text, spans);
226+}
227+
228+/** Replaces every span inside `node` with one span covering the whole node. */
229+function recolor(spans: Span[], node: Parser.SyntaxNode, style: Style, offset = 0): Span[] {
230+ const start = offset + node.startIndex;
231+ const end = offset + node.endIndex;
232+ const kept = spans.filter((span) => span.start < start || span.end > end);
233+ return [...kept, { start, end, style }];
234+}
235+
236+/** Colors a fenced code block's body, by its fence info string. */
237+export function highlightCode(info: string, text: string): string {
238+ const grammar = CODE[info.trim().toLowerCase()];
239+ return grammar === undefined ? text : paint(text, spansOf(grammar, parse(grammar, text)));
240+}