@@ -1,228 +1,13 @@
11 const std = @import("std");
2-const ts = @import("tree-sitter");
2+const styles = @import("styles.zig");
33 const render = @import("render.zig");
4-const theme = @import("theme.zig");
5-
6-extern fn tree_sitter_javascript() callconv(.c) *const ts.Language;
7-extern fn tree_sitter_typescript() callconv(.c) *const ts.Language;
8-extern fn tree_sitter_tsx() callconv(.c) *const ts.Language;
9-extern fn tree_sitter_markdown() callconv(.c) *const ts.Language;
10-extern fn tree_sitter_markdown_inline() callconv(.c) *const ts.Language;
11-extern fn tree_sitter_python() callconv(.c) *const ts.Language;
12-extern fn tree_sitter_go() callconv(.c) *const ts.Language;
13-extern fn tree_sitter_zig() callconv(.c) *const ts.Language;
14-extern fn tree_sitter_bash() callconv(.c) *const ts.Language;
15-extern fn tree_sitter_diff() callconv(.c) *const ts.Language;
16-
17-const JS_QUERIES = @embedFile("js_highlights");
18-const TS_QUERIES = @embedFile("ts_highlights");
19-const MD_QUERIES = @embedFile("md_highlights");
20-const MD_TABLES = @embedFile("md_tables");
21-const MD_INLINE_QUERIES = @embedFile("md_inline_highlights");
22-const PY_QUERIES = @embedFile("py_highlights");
23-const GO_QUERIES = @embedFile("go_highlights");
24-const ZIG_QUERIES = @embedFile("zig_highlights");
25-const BASH_QUERIES = @embedFile("bash_highlights");
26-const DIFF_QUERIES = @embedFile("diff_highlights");
27-
28-const Syntax = struct {
29- parser: *ts.Parser,
30- query: *ts.Query,
31-};
32-
33-fn syntax(a: std.mem.Allocator, language: *const ts.Language, sources: []const []const u8) ?Syntax {
34- const parser = ts.Parser.create();
35- parser.setLanguage(language) catch {
36- parser.destroy();
37- return null;
38- };
39- var source: std.ArrayList(u8) = .empty;
40- for (sources, 0..) |s, i| {
41- if (i > 0) source.append(a, '\n') catch {};
42- source.appendSlice(a, s) catch {};
43- }
44- var error_offset: u32 = 0;
45- const query = ts.Query.create(language, source.items, &error_offset) catch {
46- parser.destroy();
47- return null;
48- };
49- return .{ .parser = parser, .query = query };
50-}
51-
52-var grammars: ?Grammars = null;
53-
54-const Lang = enum { javascript, typescript, tsx, markdown, markdown_inline, python, go, zig, bash, diff };
55-
56-fn load(a: std.mem.Allocator, lang: Lang) Syntax {
57- return switch (lang) {
58- .javascript => syntax(a, tree_sitter_javascript(), &.{JS_QUERIES}) orelse unreachable,
59- .typescript => syntax(a, tree_sitter_typescript(), &.{ JS_QUERIES, TS_QUERIES }) orelse unreachable,
60- .tsx => syntax(a, tree_sitter_tsx(), &.{ JS_QUERIES, TS_QUERIES }) orelse unreachable,
61- .markdown => syntax(a, tree_sitter_markdown(), &.{ MD_QUERIES, MD_TABLES }) orelse unreachable,
62- .markdown_inline => syntax(a, tree_sitter_markdown_inline(), &.{MD_INLINE_QUERIES}) orelse unreachable,
63- .python => syntax(a, tree_sitter_python(), &.{PY_QUERIES}) orelse unreachable,
64- .go => syntax(a, tree_sitter_go(), &.{GO_QUERIES}) orelse unreachable,
65- .zig => syntax(a, tree_sitter_zig(), &.{ZIG_QUERIES}) orelse unreachable,
66- .bash => syntax(a, tree_sitter_bash(), &.{BASH_QUERIES}) orelse unreachable,
67- .diff => syntax(a, tree_sitter_diff(), &.{DIFF_QUERIES}) orelse unreachable,
68- };
69-}
70-
71-const Grammars = struct {
72- slots: [@typeInfo(Lang).@"enum".fields.len]?Syntax = @splat(null),
734
74- fn get(self: *Grammars, a: std.mem.Allocator, lang: Lang) *Syntax {
75- const slot = &self.slots[@intFromEnum(lang)];
76- if (slot.* == null) slot.* = load(a, lang);
77- return &slot.*.?;
78- }
79-};
80-
81-fn getGrammars() *Grammars {
82- if (grammars == null) grammars = .{};
83- return &grammars.?;
84-}
85-
86-pub const Span = struct {
5+const Span = struct {
876 start: u32,
887 end: u32,
89- style: theme.Style,
8+ style: styles.Style,
909 };
9110
92-fn captureNode(match: ts.Query.Match, index: u32) ?ts.Node {
93- for (match.captures) |capture| {
94- if (capture.index == index) return capture.node;
95- }
96- return null;
97-}
98-
99-fn nodeText(u: Utf16, text: []const u8, node: ts.Node) []const u8 {
100- return text[byteOf(u, node.startByte() / 2)..byteOf(u, node.endByte() / 2)];
101-}
102-
103-extern fn regcomp(preg: *anyopaque, regex: [*:0]const u8, cflags: c_int) c_int;
104-extern fn regexec(preg: *const anyopaque, string: [*:0]const u8, nmatch: usize, pmatch: ?*anyopaque, eflags: c_int) c_int;
105-extern fn regfree(preg: *anyopaque) void;
106-
107-const REG_EXTENDED: c_int = 1;
108-const REG_NOMATCH: c_int = 1;
109-
110-fn matchesRegex(a: std.mem.Allocator, pattern: []const u8, text: []const u8) bool {
111- const pat = a.dupeZ(u8, pattern) catch return false;
112- defer a.free(pat);
113- const subject = a.dupeZ(u8, text) catch return false;
114- defer a.free(subject);
115- var regex: [512]u8 align(16) = undefined;
116- if (regcomp(®ex, pat.ptr, REG_EXTENDED) != 0) return false;
117- defer regfree(®ex);
118- return regexec(®ex, subject.ptr, 0, null, 0) != REG_NOMATCH;
119-}
120-
121-fn eqText(query: *const ts.Query, match: ts.Query.Match, steps: []const ts.Query.PredicateStep, u: Utf16, text: []const u8) bool {
122- if (steps.len < 2) return true;
123- const left = predicateArg(query, match, steps[0], u, text) orelse return false;
124- const right = predicateArg(query, match, steps[1], u, text) orelse return false;
125- return std.mem.eql(u8, left, right);
126-}
127-
128-fn predicateArg(query: *const ts.Query, match: ts.Query.Match, step: ts.Query.PredicateStep, u: Utf16, text: []const u8) ?[]const u8 {
129- switch (step.type) {
130- .capture => {
131- const node = captureNode(match, step.value_id) orelse return null;
132- return nodeText(u, text, node);
133- },
134- .string => return query.stringValueForId(step.value_id),
135- .done => return null,
136- }
137-}
138-
139-fn predicatesPass(a: std.mem.Allocator, query: *const ts.Query, match: ts.Query.Match, u: Utf16, text: []const u8) bool {
140- const steps = query.predicatesForPattern(match.pattern_index);
141- var i: usize = 0;
142- while (i < steps.len) {
143- if (steps[i].type == .done) {
144- i += 1;
145- continue;
146- }
147- const name = if (steps[i].type == .string) query.stringValueForId(steps[i].value_id) else null;
148- var j = i + 1;
149- while (j < steps.len and steps[j].type != .done) j += 1;
150- const args = steps[i + 1 .. j];
151- const ok = evalPredicate(a, query, match, name, args, u, text);
152- if (!ok) return false;
153- i = j + 1;
154- }
155- return true;
156-}
157-
158-fn evalPredicate(a: std.mem.Allocator, query: *const ts.Query, match: ts.Query.Match, name: ?[]const u8, args: []const ts.Query.PredicateStep, u: Utf16, text: []const u8) bool {
159- const n = name orelse return true;
160- if (std.mem.eql(u8, n, "eq?")) return eqText(query, match, args, u, text);
161- if (std.mem.eql(u8, n, "not-eq?")) return !eqText(query, match, args, u, text);
162- if (std.mem.eql(u8, n, "match?") or std.mem.eql(u8, n, "not-match?")) {
163- if (args.len < 2) return true;
164- const cap = predicateArg(query, match, args[0], u, text) orelse return false;
165- const pattern = predicateArg(query, match, args[1], u, text) orelse return false;
166- const found = matchesRegex(a, pattern, cap);
167- return if (std.mem.eql(u8, n, "match?")) found else !found;
168- }
169- if (std.mem.eql(u8, n, "any-of?") or std.mem.eql(u8, n, "not-any-of?")) {
170- if (args.len < 2) return true;
171- const cap = predicateArg(query, match, args[0], u, text) orelse return false;
172- var found = false;
173- for (args[1..]) |arg| {
174- const candidate = predicateArg(query, match, arg, u, text) orelse continue;
175- if (std.mem.eql(u8, cap, candidate)) found = true;
176- }
177- return if (std.mem.eql(u8, n, "any-of?")) found else !found;
178- }
179- return true;
180-}
181-
182-fn spansOf(a: std.mem.Allocator, syn: *Syntax, node: ts.Node, u: Utf16, text: []const u8, offset: u32) []Span {
183- var spans: std.ArrayList(Span) = .empty;
184- const cursor = ts.QueryCursor.create();
185- defer cursor.destroy();
186- cursor.exec(syn.query, node);
187- while (cursor.nextCapture()) |pair| {
188- const match = pair[1];
189- if (!predicatesPass(a, syn.query, match, u, text)) continue;
190- const capture = match.captures[pair[0]];
191- const name = syn.query.captureNameForId(capture.index) orelse continue;
192- const style = theme.styleFor(name) orelse continue;
193- if (capture.node.endByte() <= capture.node.startByte()) continue;
194- spans.append(a, .{
195- .start = offset + byteOf(u, capture.node.startByte() / 2),
196- .end = offset + byteOf(u, capture.node.endByte() / 2),
197- .style = style,
198- }) catch {};
199- }
200- return spans.toOwnedSlice(a) catch &.{};
201-}
202-
203-fn collectByKind(a: std.mem.Allocator, node: ts.Node, kinds: []const []const u8, out: *std.ArrayList(ts.Node)) void {
204- var i: u32 = 0;
205- while (i < node.childCount()) : (i += 1) {
206- const child = node.child(i) orelse continue;
207- for (kinds) |kind| {
208- if (std.mem.eql(u8, child.kind(), kind)) {
209- out.append(a, child) catch {};
210- break;
211- }
212- }
213- collectByKind(a, child, kinds, out);
214- }
215-}
216-
217-fn recolor(a: std.mem.Allocator, spans: []Span, start: u32, end: u32, style: theme.Style) []Span {
218- var kept: std.ArrayList(Span) = .empty;
219- for (spans) |span| {
220- if (span.start < start or span.end > end) kept.append(a, span) catch {};
221- }
222- kept.append(a, .{ .start = start, .end = end, .style = style }) catch {};
223- return kept.toOwnedSlice(a) catch spans;
224-}
225-
22611 const Event = struct { at: u32, open: bool, span: usize, order: usize };
22712
22813 fn eventLess(_: void, x: Event, y: Event) bool {
@@ -231,12 +16,12 @@ fn eventLess(_: void, x: Event, y: Event) bool {
23116 return x.order < y.order;
23217 }
23318
234-pub fn paint(a: std.mem.Allocator, text: []const u8, spans: []const Span, base: theme.Style) []u8 {
19+fn paint(a: std.mem.Allocator, text: []const u8, spans: []const Span, base: styles.Style) []u8 {
23520 var events: std.ArrayList(Event) = .empty;
23621 for (spans, 0..) |span, i| {
237- if (span.end <= span.start) continue;
22+ if (span.end <= span.start or span.start >= text.len) continue;
23823 events.append(a, .{ .at = span.start, .open = true, .span = i, .order = events.items.len }) catch {};
239- events.append(a, .{ .at = span.end, .open = false, .span = i, .order = events.items.len }) catch {};
24+ events.append(a, .{ .at = @min(span.end, @as(u32, @intCast(text.len))), .open = false, .span = i, .order = events.items.len }) catch {};
24025 }
24126 std.mem.sort(Event, events.items, {}, eventLess);
24227
@@ -259,16 +44,16 @@ pub fn paint(a: std.mem.Allocator, text: []const u8, spans: []const Span, base:
25944 }
26045 }
26146 emit(a, &out, &active, spans, text, @intCast(text.len), &at, &plain, base);
262- if (!plain) out.appendSlice(a, theme.sgrOn(a, .{}, base)) catch {};
47+ if (!plain) out.appendSlice(a, styles.sgrOn(a, .{}, base)) catch {};
26348 return out.items;
26449 }
26550
266-fn emit(a: std.mem.Allocator, out: *std.ArrayList(u8), active: *std.ArrayList(usize), spans: []const Span, text: []const u8, end: u32, at: *u32, plain: *bool, base: theme.Style) void {
51+fn emit(a: std.mem.Allocator, out: *std.ArrayList(u8), active: *std.ArrayList(usize), spans: []const Span, text: []const u8, end: u32, at: *u32, plain: *bool, base: styles.Style) void {
26752 if (end <= at.*) return;
268- const reset = theme.sgrOn(a, .{}, base);
269- const style: ?theme.Style = if (active.items.len == 0) null else spans[active.items[active.items.len - 1]].style;
53+ const reset = styles.sgrOn(a, .{}, base);
54+ const style: ?styles.Style = if (active.items.len == 0) null else spans[active.items[active.items.len - 1]].style;
27055 if (style) |s| {
271- const sgr = theme.sgrOn(a, s, base);
56+ const sgr = styles.sgrOn(a, s, base);
27257 out.appendSlice(a, sgr) catch {};
27358 plain.* = false;
27459 const chunk = text[at.*..end];
@@ -284,136 +69,208 @@ fn emit(a: std.mem.Allocator, out: *std.ArrayList(u8), active: *std.ArrayList(us
28469 at.* = end;
28570 }
28671
287-fn langFor(lang: []const u8) ?Lang {
288- if (std.mem.eql(u8, lang, "js") or std.mem.eql(u8, lang, "javascript") or std.mem.eql(u8, lang, "jsx")) return .javascript;
289- if (std.mem.eql(u8, lang, "ts") or std.mem.eql(u8, lang, "typescript")) return .typescript;
290- if (std.mem.eql(u8, lang, "tsx")) return .tsx;
291- if (std.mem.eql(u8, lang, "py") or std.mem.eql(u8, lang, "python")) return .python;
292- if (std.mem.eql(u8, lang, "go") or std.mem.eql(u8, lang, "golang")) return .go;
293- if (std.mem.eql(u8, lang, "zig")) return .zig;
294- if (std.mem.eql(u8, lang, "bash") or std.mem.eql(u8, lang, "sh") or std.mem.eql(u8, lang, "shell")) return .bash;
295- return null;
72+fn muted() styles.Style {
73+ return styles.roles.comment;
29674 }
29775
298-fn syntaxFor(g: *Grammars, a: std.mem.Allocator, lang: []const u8) ?*Syntax {
299- return g.get(a, langFor(lang) orelse return null);
76+fn isAlnum(c: u8) bool {
77+ return std.ascii.isAlphanumeric(c) or c == '_';
30078 }
30179
302-fn infoLang(info: []const u8) []const u8 {
303- const trimmed = std.mem.trim(u8, info, " \t\r\n");
304- var end: usize = 0;
305- while (end < trimmed.len and trimmed[end] != ' ' and trimmed[end] != '\t') end += 1;
306- return trimmed[0..end];
80+fn runLength(line: []const u8, at: usize, c: u8) usize {
81+ var n: usize = 0;
82+ while (at + n < line.len and line[at + n] == c) n += 1;
83+ return n;
30784 }
30885
309-pub fn spansFor(a: std.mem.Allocator, info: []const u8, text: []const u8) []const Span {
310- const g = getGrammars();
311- const lang = std.ascii.allocLowerString(a, infoLang(info)) catch infoLang(info);
312- const s = syntaxFor(g, a, lang) orelse return &.{};
313- const u = utf16(a, text) orelse return &.{};
314- const root = parse(s.parser, u) orelse return &.{};
315- defer root.destroy();
316- return spansOf(a, s, root.rootNode(), u, text, 0);
86+/// Closing run for `marker` repeated `count` times, ignoring empty or space-padded content.
87+fn closeRun(line: []const u8, open_at: usize, marker: u8, count: usize, limit: usize) ?usize {
88+ var i = open_at + count;
89+ while (i + count <= limit) : (i += 1) {
90+ if (line[i] != marker) continue;
91+ if (line[i - 1] == ' ' or line[i - 1] == '\t') continue;
92+ if (runLength(line, i, marker) < count) continue;
93+ return i;
94+ }
95+ return null;
31796 }
31897
319-pub fn highlightOn(a: std.mem.Allocator, info: []const u8, text: []const u8, base: theme.Style) []const u8 {
320- return paint(a, text, spansFor(a, info, text), base);
98+fn addSpan(a: std.mem.Allocator, spans: *std.ArrayList(Span), base: u32, start: usize, end: usize, style: styles.Style) void {
99+ if (end <= start) return;
100+ spans.append(a, .{ .start = base + @as(u32, @intCast(start)), .end = base + @as(u32, @intCast(end)), .style = style }) catch {};
101+}
102+
103+/// Inline markup inside one prose line. `limit` is the byte index the scan stops at.
104+fn scanInline(a: std.mem.Allocator, line: []const u8, base: u32, start: usize, limit: usize, spans: *std.ArrayList(Span)) void {
105+ var i = start;
106+ while (i < limit) {
107+ const c = line[i];
108+ if (c == '`') {
109+ const n = runLength(line, i, '`');
110+ var j = i + n;
111+ while (j + n <= limit) : (j += 1) {
112+ if (line[j] != '`') continue;
113+ if (runLength(line, j, '`') < n) continue;
114+ addSpan(a, spans, base, i, j + n, styles.roles.inline_code);
115+ i = j + n;
116+ break;
117+ } else {
118+ i += n;
119+ }
120+ continue;
121+ }
122+ if (c == '*' or c == '_') {
123+ const n = runLength(line, i, c);
124+ const count: usize = @min(n, 2);
125+ const content = i + count;
126+ // An opener needs content and, for `_`, must not sit inside a word.
127+ if (content >= limit or line[content] == ' ' or line[content] == '\t' or
128+ (c == '_' and i > start and isAlnum(line[i - 1])))
129+ {
130+ i += n;
131+ continue;
132+ }
133+ if (closeRun(line, i, c, count, limit)) |close| {
134+ const style: styles.Style = if (count == 2) .{ .bold = true } else .{ .italic = true };
135+ addSpan(a, spans, base, i, close + count, style);
136+ i = close + count;
137+ } else {
138+ i += n;
139+ }
140+ continue;
141+ }
142+ if (c == '[') {
143+ if (std.mem.indexOfScalarPos(u8, line[0..limit], i, ']')) |close| {
144+ if (close + 1 < limit and line[close + 1] == '(') {
145+ if (std.mem.indexOfScalarPos(u8, line[0..limit], close + 1, ')')) |end| {
146+ addSpan(a, spans, base, i, close + 1, styles.roles.link);
147+ addSpan(a, spans, base, close + 1, end + 1, styles.roles.uri);
148+ i = end + 1;
149+ continue;
150+ }
151+ }
152+ }
153+ i += 1;
154+ continue;
155+ }
156+ i += 1;
157+ }
321158 }
322159
323-pub const NodeSpan = struct { start: u32, end: u32, kind: []const u8 };
324-
325-const diff_line_kinds = [_][]const u8{
326- "file_change", "binary_change", "index", "similarity", "dissimilarity",
327- "old_file", "new_file", "location", "addition", "deletion",
328- "change", "context", "comment", "special", "unrecognized",
329-};
160+fn leadingSpaces(line: []const u8) usize {
161+ var i: usize = 0;
162+ while (i < line.len and i < 3 and line[i] == ' ') i += 1;
163+ return i;
164+}
165+
166+fn headingLevel(line: []const u8) ?usize {
167+ const at = leadingSpaces(line);
168+ var n: usize = 0;
169+ while (at + n < line.len and line[at + n] == '#') n += 1;
170+ if (n == 0 or n > 6) return null;
171+ if (at + n < line.len and line[at + n] != ' ' and line[at + n] != '\t') return null;
172+ return n;
173+}
174+
175+fn isFenceMarker(line: []const u8) bool {
176+ const at = leadingSpaces(line);
177+ if (at >= line.len) return false;
178+ const c = line[at];
179+ if (c != '`' and c != '~') return false;
180+ return runLength(line, at, c) >= 3;
181+}
182+
183+fn isRule(line: []const u8) bool {
184+ const at = leadingSpaces(line);
185+ if (at >= line.len) return false;
186+ const c = line[at];
187+ if (c != '-' and c != '*' and c != '_') return false;
188+ var marks: usize = 0;
189+ for (line[at..]) |ch| {
190+ if (ch == c) {
191+ marks += 1;
192+ } else if (ch != ' ' and ch != '\t' and ch != '\r') {
193+ return false;
194+ }
195+ }
196+ return marks >= 3;
197+}
330198
331-pub fn isDiffLineKind(kind: []const u8) bool {
332- for (diff_line_kinds) |k| {
333- if (std.mem.eql(u8, kind, k)) return true;
199+/// Byte offset just past a list or quote marker, or null when the line has none.
200+fn blockMarker(line: []const u8) ?usize {
201+ const at = leadingSpaces(line);
202+ if (at >= line.len) return null;
203+ const c = line[at];
204+ if (c == '>' or c == '-' or c == '*' or c == '+') {
205+ if (at + 1 < line.len and (line[at + 1] == ' ' or line[at + 1] == '\t')) return at + 1;
206+ return null;
334207 }
335- return false;
208+ var n = at;
209+ while (n < line.len and std.ascii.isDigit(line[n])) n += 1;
210+ if (n == at or n >= line.len) return null;
211+ if ((line[n] == '.' or line[n] == ')') and n + 1 < line.len and (line[n + 1] == ' ' or line[n + 1] == '\t')) return n + 1;
212+ return null;
336213 }
337214
338-fn collectDiffNodes(a: std.mem.Allocator, node: ts.Node, u: Utf16, out: *std.ArrayList(NodeSpan)) void {
339- if (isDiffLineKind(node.kind())) {
340- out.append(a, .{
341- .start = byteOf(u, node.startByte() / 2),
342- .end = byteOf(u, node.endByte() / 2),
343- .kind = node.kind(),
344- }) catch {};
215+fn markdownLine(a: std.mem.Allocator, line: []const u8, base: u32, spans: *std.ArrayList(Span)) void {
216+ const limit = line.len;
217+ if (isFenceMarker(line) or isRule(line)) {
218+ addSpan(a, spans, base, 0, limit, muted());
219+ return;
220+ }
221+ if (headingLevel(line)) |level| {
222+ const idx = @min(level, styles.roles.headings.len) - 1;
223+ addSpan(a, spans, base, 0, limit, styles.roles.headings[idx]);
345224 return;
346225 }
347- var i: u32 = 0;
348- while (i < node.childCount()) : (i += 1) {
349- const child = node.child(i) orelse continue;
350- collectDiffNodes(a, child, u, out);
226+ var start: usize = 0;
227+ if (blockMarker(line)) |after| {
228+ addSpan(a, spans, base, 0, after, muted());
229+ start = after;
351230 }
231+ scanInline(a, line, base, start, limit, spans);
352232 }
353233
354-pub fn diffSpans(a: std.mem.Allocator, text: []const u8) []NodeSpan {
355- const g = getGrammars();
356- const u = utf16(a, text) orelse return &.{};
357- const root = parse(g.get(a, .diff).parser, u) orelse return &.{};
358- defer root.destroy();
359- var out: std.ArrayList(NodeSpan) = .empty;
360- collectDiffNodes(a, root.rootNode(), u, &out);
361- return out.items;
234+pub fn highlightMarkdown(a: std.mem.Allocator, text: []const u8) []const u8 {
235+ var spans: std.ArrayList(Span) = .empty;
236+ var it = std.mem.splitScalar(u8, text, '\n');
237+ var base: u32 = 0;
238+ while (it.next()) |line| {
239+ markdownLine(a, line, base, &spans);
240+ base += @intCast(line.len + 1);
241+ }
242+ return paint(a, text, spans.items, .{});
362243 }
363244
364-pub fn highlightCode(a: std.mem.Allocator, info: []const u8, text: []const u8) []const u8 {
365- return highlightOn(a, info, text, .{});
245+/// Fenced code is styled as one muted block: token-level coloring needs a grammar, and a
246+/// hand-written approximation costs more than it shows.
247+pub fn highlightCode(a: std.mem.Allocator, text: []const u8) []const u8 {
248+ // Stop before the block's trailing newline so the style does not leak a dangling SGR.
249+ const end = if (text.len > 0 and text[text.len - 1] == '\n') text.len - 1 else text.len;
250+ const spans = [_]Span{.{ .start = 0, .end = @intCast(end), .style = .{ .fg = styles.roles.code } }};
251+ return paint(a, text, &spans, .{});
366252 }
367253
368-pub fn highlightMarkdown(a: std.mem.Allocator, text: []const u8) []const u8 {
369- const g = getGrammars();
370- const u = utf16(a, text) orelse return text;
371- const root = parse(g.get(a, .markdown).parser, u) orelse return text;
372- defer root.destroy();
373- var spans: std.ArrayList(Span) = .empty;
374- spans.appendSlice(a, spansOf(a, g.get(a, .markdown), root.rootNode(), u, text, 0)) catch {};
375-
376- var inline_nodes: std.ArrayList(ts.Node) = .empty;
377- collectByKind(a, root.rootNode(), &.{ "inline", "pipe_table_cell" }, &inline_nodes);
378- for (inline_nodes.items) |node| {
379- const start = byteOf(u, node.startByte() / 2);
380- const inline_text = text[start..byteOf(u, node.endByte() / 2)];
381- const iu = utf16(a, inline_text) orelse continue;
382- const inline_root = parse(g.get(a, .markdown_inline).parser, iu) orelse continue;
383- defer inline_root.destroy();
384- spans.appendSlice(a, spansOf(a, g.get(a, .markdown_inline), inline_root.rootNode(), iu, inline_text, start)) catch {};
385- var code_spans: std.ArrayList(ts.Node) = .empty;
386- collectByKind(a, inline_root.rootNode(), &.{"code_span"}, &code_spans);
387- for (code_spans.items) |code| spans = std.ArrayList(Span).fromOwnedSlice(recolor(
388- a,
389- spans.items,
390- start + byteOf(iu, code.startByte() / 2),
391- start + byteOf(iu, code.endByte() / 2),
392- theme.current.inline_code,
393- ));
394- }
254+pub const DiffKind = enum { hunk, add, del, ctx, note };
395255
396- var headings: std.ArrayList(ts.Node) = .empty;
397- collectByKind(a, root.rootNode(), &.{ "atx_heading", "setext_heading" }, &headings);
398- for (headings.items) |heading| {
399- var level: usize = 1;
400- var i: u32 = 0;
401- while (i < heading.childCount()) : (i += 1) {
402- const child = heading.child(i) orelse continue;
403- const kind = child.kind();
404- if (std.mem.startsWith(u8, kind, "atx_h") or std.mem.startsWith(u8, kind, "setext_h")) {
405- var digits: usize = 0;
406- for (kind) |c| {
407- if (c >= '0' and c <= '9') digits = digits * 10 + (c - '0');
408- }
409- if (digits > 0) level = digits;
410- break;
411- }
412- }
413- const idx = @min(level, theme.current.headings.len) - 1;
414- spans = std.ArrayList(Span).fromOwnedSlice(recolor(a, spans.items, byteOf(u, heading.startByte() / 2), byteOf(u, heading.endByte() / 2), theme.current.headings[idx]));
256+fn isFileHeader(line: []const u8) bool {
257+ return std.mem.startsWith(u8, line, "--- ") or std.mem.startsWith(u8, line, "+++ ");
258+}
259+
260+/// Classify one diff line by its first byte. `in_hunk` disambiguates `---`/`+++` file
261+/// headers from removed/added content once a hunk header has been seen.
262+pub fn diffKind(line: []const u8, in_hunk: bool) DiffKind {
263+ if (std.mem.startsWith(u8, line, "@@")) return .hunk;
264+ if (std.mem.startsWith(u8, line, "\\")) return .note;
265+ if (in_hunk) {
266+ if (line.len > 0 and line[0] == '+') return .add;
267+ if (line.len > 0 and line[0] == '-') return .del;
268+ return .ctx;
415269 }
416- return paint(a, text, spans.items, .{});
270+ if (isFileHeader(line)) return .note;
271+ if (line.len > 0 and line[0] == '+') return .add;
272+ if (line.len > 0 and line[0] == '-') return .del;
273+ return .note;
417274 }
418275
419276 const Align = enum { none, left, center, right };
@@ -427,70 +284,108 @@ fn alignOf(cell: []const u8) Align {
427284 return .none;
428285 }
429286
Cut short: this commit's diff is over 1000 lines.