xonecas.io
79113
Ma

mini-coding-agent / commit 95dbd0a

feat: slimming down on dependencies and zig 0.17.0

- Since tree-sitter is out, we now do a light approach to themes, mostly
  using the host terminals colors.

xonecas2026-10-25 95dbd0a4659ed1150a5beb1ba9904f50a3e053af parent 43445d9

20 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

README.md+1−9
@@ -2,15 +2,9 @@
22
33 A fast, transparent, config-first terminal coding agent.
44
5-<p align="center">
6- <img src="preview.png" alt="mini TUI: an edit diff, a streamed answer, and the three themes" width="931">
7- <br>
8- <a href="preview.mp4">10-second demo (mp4, 1.4 MB)</a>
9-</p>
10-
115 ## Build
126
13-Requires Zig 0.16.0.
7+Requires Zig 0.17.0.
148
159 zig build
1610
@@ -104,7 +98,6 @@ A full example:
10498 "provider": "opencode",
10599 "model": "deepseek-v4.1-flash",
106100 "thinkingEffort": "medium",
107- "theme": "tokyonight",
108101 "showImages": false,
109102 "systemPrompt": "Be terse.",
110103 "sessionsDir": "/home/me/.local/state/mini-coding-agent/sessions",
@@ -154,7 +147,6 @@ Keys:
154147 | `provider` | unset | provider id; built-ins are `opencode`, `opencode-go` and `openai` (after `mini login`), or a `customProviders` id |
155148 | `model` | unset | model id |
156149 | `thinkingEffort` | unset | one of `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max`; unset sends no reasoning parameter and clamps to what the model accepts |
157-| `theme` | `tokyonight` | TUI palette: `tokyonight`, `oxocarbon`, or `kanagawa`. Read at startup; there is no live reload |
158150 | `showImages` | `false` | display PNGs the `read` tool returns inline using the kitty graphics protocol; requires kitty 0.28+ |
159151 | `systemPrompt` | `""` | prepended to the system prompt |
160152 | `sessionsDir` | `$XDG_STATE_HOME/mini-coding-agent/sessions`, else `$HOME/.local/state/mini-coding-agent/sessions`, else `sessions` | where JSONL session logs go |
build.zig+3−57
@@ -1,19 +1,8 @@
11 const std = @import("std");
2-const builtin = @import("builtin");
32 const zon = @import("build.zig.zon");
43
5-// A native query makes Zig link the system CRT, and GCC 16's `crt1.o` carries
6-// `.sframe` relocations that Zig 0.16's linker rejects. Pinning linux-gnu keeps
7-// the native CPU but uses Zig's bundled glibc CRT.
8-const host_query: std.Target.Query = if (builtin.os.tag == .linux and builtin.abi == .gnu) .{
9- .cpu_arch = builtin.cpu.arch,
10- .os_tag = .linux,
11- .abi = .gnu,
12- .cpu_model = .native,
13-} else .{};
14-
154 pub fn build(b: *std.Build) void {
16- const target = b.standardTargetOptions(.{ .default_target = host_query });
5+ const target = b.standardTargetOptions(.{});
176 const optimize = b.standardOptimizeOption(.{});
187
198 const exe = b.addExecutable(.{
@@ -29,55 +18,12 @@ pub fn build(b: *std.Build) void {
2918 const options = b.addOptions();
3019 options.addOption([]const u8, "version", zon.version);
3120 exe.root_module.addOptions("build_options", options);
32-
33- const tree_sitter = b.dependency("tree_sitter", .{ .target = target, .optimize = optimize });
34- exe.root_module.addImport("tree-sitter", tree_sitter.module("tree_sitter"));
35-
36- const js = b.dependency("tree_sitter_javascript", .{ .target = target, .optimize = optimize });
37- const ts = b.dependency("tree_sitter_typescript", .{ .target = target, .optimize = optimize });
38- const md = b.dependency("tree_sitter_markdown", .{ .target = target, .optimize = optimize });
39- const py = b.dependency("tree_sitter_python", .{ .target = target, .optimize = optimize });
40- const go = b.dependency("tree_sitter_go", .{ .target = target, .optimize = optimize });
41- const zig = b.dependency("tree_sitter_zig", .{ .target = target, .optimize = optimize });
42- const bash = b.dependency("tree_sitter_bash", .{ .target = target, .optimize = optimize });
43- const diff = b.dependency("tree_sitter_diff", .{ .target = target, .optimize = optimize });
44-
21+ // `platform.zig` reads the passwd entry through `std.c`, which needs libc.
4522 exe.root_module.link_libc = true;
46- addGrammar(exe, js, "src", &.{ "parser.c", "scanner.c" });
47- addGrammar(exe, ts, "typescript/src", &.{ "parser.c", "scanner.c" });
48- addGrammar(exe, ts, "tsx/src", &.{ "parser.c", "scanner.c" });
49- addGrammar(exe, md, "tree-sitter-markdown/src", &.{ "parser.c", "scanner.c" });
50- addGrammar(exe, md, "tree-sitter-markdown-inline/src", &.{ "parser.c", "scanner.c" });
51- addGrammar(exe, py, "src", &.{ "parser.c", "scanner.c" });
52- addGrammar(exe, go, "src", &.{"parser.c"});
53- addGrammar(exe, zig, "src", &.{"parser.c"});
54- addGrammar(exe, bash, "src", &.{ "parser.c", "scanner.c" });
55- addGrammar(exe, diff, "src", &.{"parser.c"});
56-
57- exe.root_module.addAnonymousImport("js_highlights", .{ .root_source_file = js.path("queries/highlights.scm") });
58- exe.root_module.addAnonymousImport("ts_highlights", .{ .root_source_file = ts.path("queries/highlights.scm") });
59- exe.root_module.addAnonymousImport("md_highlights", .{ .root_source_file = md.path("tree-sitter-markdown/queries/highlights.scm") });
60- exe.root_module.addAnonymousImport("md_inline_highlights", .{ .root_source_file = md.path("tree-sitter-markdown-inline/queries/highlights.scm") });
61- exe.root_module.addAnonymousImport("md_tables", .{ .root_source_file = b.path("src/tui/markdown_tables.scm") });
62- exe.root_module.addAnonymousImport("py_highlights", .{ .root_source_file = py.path("queries/highlights.scm") });
63- exe.root_module.addAnonymousImport("go_highlights", .{ .root_source_file = go.path("queries/highlights.scm") });
64- exe.root_module.addAnonymousImport("zig_highlights", .{ .root_source_file = zig.path("queries/highlights.scm") });
65- exe.root_module.addAnonymousImport("bash_highlights", .{ .root_source_file = bash.path("queries/highlights.scm") });
66- exe.root_module.addAnonymousImport("diff_highlights", .{ .root_source_file = diff.path("queries/highlights.scm") });
6723
6824 const run_cmd = b.addRunArtifact(exe);
6925 run_cmd.step.dependOn(b.getInstallStep());
70- if (b.args) |args| run_cmd.addArgs(args);
26+ run_cmd.addPassthruArgs();
7127 const run_step = b.step("run", "Run mini");
7228 run_step.dependOn(&run_cmd.step);
7329 }
74-
75-fn addGrammar(exe: *std.Build.Step.Compile, dep: *std.Build.Dependency, dir: []const u8, files: []const []const u8) void {
76- const root = dep.path(dir);
77- exe.root_module.addIncludePath(root);
78- exe.root_module.addCSourceFiles(.{
79- .root = root,
80- .files = files,
81- .flags = &.{"-std=c11"},
82- });
83-}
build.zig.zon+1−42
@@ -2,48 +2,7 @@
22 .name = .mini_coding_agent,
33 .version = "0.1.0",
44 .fingerprint = 0xcd9f17f042740125,
5- .minimum_zig_version = "0.16.0",
6- .dependencies = .{
7- .tree_sitter = .{
8- .url = "git+https://github.com/tree-sitter/zig-tree-sitter#b562510b5563dcf3b7fcac4a5fe9d60834c84667",
9- .hash = "tree_sitter-0.26.0-8heIf-vDAQDh0HhAAUVwVZFmLrwSKMZl5gRaVFqtas0W",
10- },
11- .tree_sitter_javascript = .{
12- .url = "git+https://github.com/tree-sitter/tree-sitter-javascript?ref=v0.25.0#44c892e0be055ac465d5eeddae6d3e194424e7de",
13- .hash = "N-V-__8AANlfOQB4iUiSxpYjpQ5R6BBgFscc5iYIWIu-9plN",
14- },
15- .tree_sitter_typescript = .{
16- .url = "git+https://github.com/tree-sitter/tree-sitter-typescript?ref=v0.23.2#f975a621f4e7f532fe322e13c4f79495e0a7b2e7",
17- .hash = "N-V-__8AALhpIQFpocCrfuYTb_Vzvxj3QG0T-yqi9x1QNRNM",
18- },
19- .tree_sitter_markdown = .{
20- .url = "git+https://github.com/tree-sitter-grammars/tree-sitter-markdown?ref=v0.3.2#1c8dea73bc0c996d92dd9ebc30dd388716b1c5db",
21- .hash = "N-V-__8AAJvIUgBKgesFyAgIRoY2KiG9_M2zWZQ4FBvnlPmz",
22- },
23- .tree_sitter_python = .{
24- .url = "git+https://github.com/tree-sitter/tree-sitter-python?ref=v0.25.0#293fdc02038ee2bf0e2e206711b69c90ac0d413f",
25- .hash = "N-V-__8AAK21PgAb_K86C9arl06radxCV934N2VALHkf1vDH",
26- },
27- .tree_sitter_go = .{
28- .url = "git+https://github.com/tree-sitter/tree-sitter-go?ref=v0.25.0#1547678a9da59885853f5f5cc8a99cc203fa2e2c",
29- .hash = "N-V-__8AAM9cIgDSWz10pu4QwvyegGvG1p3E3KBTILC3fqGh",
30- },
31- .tree_sitter_bash = .{
32- .url = "git+https://github.com/tree-sitter/tree-sitter-bash?ref=v0.25.0#56b54c61fb48bce0c63e3dfa2240b5d274384763",
33- .hash = "N-V-__8AAMpjowDkEgxFXmUkigmd9fBEaf_9sQiXBDbjcyzt",
34- },
35- .tree_sitter_diff = .{
36- .url = "git+https://github.com/the-mikedavis/tree-sitter-diff#ada384ac7bfc1307f32de474620120add29998fb",
37- .hash = "N-V-__8AAPUcFACL4N4XTVUilDAwPIkX8066VSaipW5tYXDT",
38- },
39- // The v1.1.2 tag predates the repo's `build.zig.zon`, and Zig resolves
40- // a `?ref=` tag against the default branch when the tag has none, whose
41- // manifest lacks a `fingerprint`. The commit is pinned instead.
42- .tree_sitter_zig = .{
43- .url = "git+https://github.com/tree-sitter-grammars/tree-sitter-zig#b670c8df85a1568f498aa5c8cae42f51a90473c0",
44- .hash = "N-V-__8AAN6NXgCZxLUnqe4620P_FqHrEY8PHTA1-VlOn4yX",
45- },
46- },
5+ .minimum_zig_version = "0.17.0",
476 .paths = .{
487 "build.zig",
498 "build.zig.zon",
preview.mp4+0−0
Binary file, not shown.
preview.png+0−0
Binary file, not shown.
src/config.zig+0−4
@@ -48,7 +48,6 @@ pub const Config = struct {
4848 provider: ?[]const u8,
4949 model: ?[]const u8,
5050 thinking_effort: ?[]const u8,
51- theme: []const u8,
5251 program_status: bool,
5352 herdr: bool,
5453 show_images: bool,
@@ -74,7 +73,6 @@ const File = struct {
7473 thinkingEffort: ?[]const u8 = null,
7574 customProviders: ?[]const CustomProvider = null,
7675 mcpServers: ?std.json.ArrayHashMap(McpServer) = null,
77- theme: ?[]const u8 = null,
7876 programStatus: ?bool = null,
7977 herdr: ?bool = null,
8078 showImages: ?bool = null,
@@ -155,7 +153,6 @@ fn readInto(a: std.mem.Allocator, path: []const u8, required: bool, cfg: *Config
155153 if (file.customProviders) |v| cfg.custom_providers = v;
156154 if (file.mcpServers) |v| cfg.mcp_servers = v;
157155 if (file.thinkingEffort) |v| cfg.thinking_effort = v;
158- if (file.theme) |v| cfg.theme = v;
159156 if (file.programStatus) |v| cfg.program_status = v;
160157 if (file.herdr) |v| cfg.herdr = v;
161158 if (file.showImages) |v| cfg.show_images = v;
@@ -209,7 +206,6 @@ fn defaults(a: std.mem.Allocator) !Config {
209206 .provider = null,
210207 .model = null,
211208 .thinking_effort = null,
212- .theme = "tokyonight",
213209 .program_status = false,
214210 .herdr = false,
215211 .show_images = false,
src/headless.zig+2−2
@@ -9,7 +9,7 @@ var cancel = std.atomic.Value(bool).init(false);
99 var caught_signal = std.atomic.Value(u32).init(0);
1010
1111 fn onSignal(sig: std.posix.SIG) callconv(.c) void {
12- caught_signal.store(@intFromEnum(sig), .seq_cst);
12+ caught_signal.store(@backingInt(sig), .seq_cst);
1313 cancel.store(true, .release);
1414 }
1515
@@ -62,7 +62,7 @@ pub fn run(a: std.mem.Allocator, prompt_text: []const u8, opts: agent.Options) u
6262 agent.runTurn(o, &messages, null, .{ .ctx = &pc, .on_event = printEvent });
6363 opts.session.close();
6464 const sig = caught_signal.load(.seq_cst);
65- if (sig != 0) platform.reRaise(@enumFromInt(sig));
65+ if (sig != 0) platform.reRaise(@fromBackingInt(@intCast(sig)));
6666 if (pc.failed) return 1;
6767
6868 var i = messages.items.len;
src/http.zig+3−3
@@ -64,7 +64,7 @@ pub fn get(
6464
6565 req.sendBodiless() catch return error.RequestFailed;
6666 var response = req.receiveHead(&.{}) catch return error.RequestFailed;
67- const status = @intFromEnum(response.head.status);
67+ const status = @backingInt(response.head.status);
6868
6969 var transfer: [16 * 1024]u8 = undefined;
7070 var decompress: std.http.Decompress = undefined;
@@ -114,7 +114,7 @@ pub fn post(
114114 req.connection.?.flush() catch return error.RequestFailed;
115115
116116 var response = req.receiveHead(&.{}) catch return error.RequestFailed;
117- const status = @intFromEnum(response.head.status);
117+ const status = @backingInt(response.head.status);
118118
119119 var transfer: [16 * 1024]u8 = undefined;
120120 var decompress: std.http.Decompress = undefined;
@@ -166,7 +166,7 @@ pub fn postSse(
166166 }
167167
168168 var response = req.receiveHead(&.{}) catch return error.RequestFailed;
169- const status = @intFromEnum(response.head.status);
169+ const status = @backingInt(response.head.status);
170170
171171 var transfer: [16 * 1024]u8 = undefined;
172172 var decompress: std.http.Decompress = undefined;
src/siwc.zig+1−1
@@ -358,7 +358,7 @@ fn verifySignature(a: std.mem.Allocator, msg: []const u8, sig: []const u8, kid:
358358 fn checkRs256(comptime len: usize, sig: []const u8, msg: []const u8, key: std.crypto.Certificate.rsa.PublicKey) bool {
359359 std.crypto.Certificate.rsa.PKCS1v1_5Signature.verify(
360360 len,
361- sig[0..len].*,
361+ sig[0..len],
362362 msg,
363363 key,
364364 std.crypto.hash.sha2.Sha256,
src/tui/diff_view.zig+21−106
@@ -1,6 +1,6 @@
11 const std = @import("std");
2+const styles = @import("styles.zig");
23 const tools = @import("../tools.zig");
3-const theme = @import("theme.zig");
44 const highlight = @import("highlight.zig");
55 const render = @import("render.zig");
66
@@ -12,125 +12,40 @@ pub const Rendered = struct {
1212 removed: usize = 0,
1313 };
1414
15-fn diffHunk() theme.Style {
16- return .{ .fg = theme.current.prompt };
15+fn diffHunk() styles.Style {
16+ return .{ .fg = styles.roles.prompt };
1717 }
1818
19-const DiffKind = enum { hunk, add, del, ctx, note };
20-
21-fn diffKindOf(kind: []const u8) ?DiffKind {
22- if (std.mem.eql(u8, kind, "location")) return .hunk;
23- if (std.mem.eql(u8, kind, "addition")) return .add;
24- if (std.mem.eql(u8, kind, "deletion")) return .del;
25- if (std.mem.eql(u8, kind, "context")) return .ctx;
26- if (highlight.isDiffLineKind(kind)) return .note;
27- return null;
28-}
29-
30-fn prefixKind(line: []const u8) DiffKind {
31- if (std.mem.startsWith(u8, line, "@@")) return .hunk;
32- if (std.mem.startsWith(u8, line, "+")) return .add;
33- if (std.mem.startsWith(u8, line, "-")) return .del;
34- if (std.mem.startsWith(u8, line, " ")) return .ctx;
35- return .note;
36-}
37-
38-fn langFor(path: []const u8) []const u8 {
39- const ext = std.fs.path.extension(path);
40- const named = [_]struct { ext: []const u8, lang: []const u8 }{
41- .{ .ext = ".js", .lang = "js" },
42- .{ .ext = ".jsx", .lang = "jsx" },
43- .{ .ext = ".mjs", .lang = "js" },
44- .{ .ext = ".cjs", .lang = "js" },
45- .{ .ext = ".ts", .lang = "ts" },
46- .{ .ext = ".tsx", .lang = "tsx" },
47- .{ .ext = ".py", .lang = "py" },
48- .{ .ext = ".go", .lang = "go" },
49- .{ .ext = ".zig", .lang = "zig" },
50- };
51- for (named) |entry| {
52- if (std.ascii.eqlIgnoreCase(ext, entry.ext)) return entry.lang;
53- }
54- return "";
19+fn diffNote() styles.Style {
20+ return styles.roles.comment;
5521 }
5622
57-fn rebaseSpans(a: std.mem.Allocator, spans: []const highlight.Span, lo: u32, hi: u32) []const highlight.Span {
58- var out: std.ArrayList(highlight.Span) = .empty;
59- for (spans) |s| {
60- const start = @max(s.start, lo);
61- const end = @min(s.end, hi);
62- if (end <= start) continue;
63- out.append(a, .{ .start = start - lo, .end = end - lo, .style = s.style }) catch {};
64- }
65- return out.items;
66-}
67-
68-pub fn diffLines(a: std.mem.Allocator, path: []const u8, lines: []const []const u8, max_diff_lines: usize) Rendered {
23+pub fn diffLines(a: std.mem.Allocator, lines: []const []const u8, max_diff_lines: usize) Rendered {
6924 if (lines.len > max_diff_lines) {
7025 var warn: std.ArrayList(BodyLine) = .empty;
7126 warn.append(a, .{
7227 .text = "Diff too large to render efficiently. Full contents in session.jsonl",
73- .style = .{ .fg = theme.current.comment },
28+ .style = diffNote(),
7429 }) catch {};
7530 return .{ .lines = warn.items };
7631 }
77- var joined: std.ArrayList(u8) = .empty;
78- var starts = a.alloc(u32, lines.len) catch return .{};
79- for (lines, 0..) |l, i| {
80- if (i > 0) joined.append(a, '\n') catch {};
81- starts[i] = @intCast(joined.items.len);
82- joined.appendSlice(a, l) catch {};
83- }
84- const nodes = highlight.diffSpans(a, joined.items);
85- std.mem.sort(highlight.NodeSpan, nodes, {}, struct {
86- fn lt(_: void, x: highlight.NodeSpan, y: highlight.NodeSpan) bool {
87- return x.start < y.start;
88- }
89- }.lt);
90-
91- var code: std.ArrayList(u8) = .empty;
92- var kinds = a.alloc(DiffKind, lines.len) catch return .{};
93- var los = a.alloc(u32, lines.len) catch return .{};
94- var his = a.alloc(u32, lines.len) catch return .{};
95- var cursor: usize = 0;
96- for (lines, 0..) |l, i| {
97- while (cursor < nodes.len and nodes[cursor].end <= starts[i]) cursor += 1;
98- const parsed: ?DiffKind = if (cursor < nodes.len and nodes[cursor].start == starts[i])
99- diffKindOf(nodes[cursor].kind)
100- else
101- null;
102- const kind = parsed orelse prefixKind(l);
103- kinds[i] = kind;
104- los[i] = 0;
105- his[i] = 0;
106- if (kind != .add and kind != .del and kind != .ctx) continue;
107- const content = l[1..];
108- los[i] = @intCast(code.items.len);
109- code.appendSlice(a, content) catch {};
110- code.append(a, '\n') catch {};
111- his[i] = @intCast(code.items.len - 1);
112- }
113-
114- const spans = highlight.spansFor(a, langFor(path), code.items);
115-
11632 var out: std.ArrayList(BodyLine) = .empty;
11733 var added: usize = 0;
11834 var removed: usize = 0;
119- for (lines, 0..) |l, i| {
120- switch (kinds[i]) {
121- .hunk => out.append(a, .{ .text = l, .style = diffHunk() }) catch {},
122- .note => out.append(a, .{ .text = l, .style = .{ .fg = theme.current.comment } }) catch {},
123- .ctx => out.append(a, .{ .text = l, .style = .{ .fg = theme.current.comment } }) catch {},
35+ var in_hunk = false;
36+ for (lines) |line| {
37+ if (std.mem.startsWith(u8, line, "diff ")) in_hunk = false;
38+ const kind = highlight.diffKind(line, in_hunk);
39+ if (kind == .hunk) in_hunk = true;
40+ switch (kind) {
41+ .hunk => out.append(a, .{ .text = line, .style = diffHunk() }) catch {},
42+ .note => out.append(a, .{ .text = line, .style = diffNote() }) catch {},
43+ .ctx => out.append(a, .{ .text = line, .style = diffNote() }) catch {},
12444 .add, .del => {
125- const is_add = kinds[i] == .add;
45+ const is_add = kind == .add;
12646 if (is_add) added += 1 else removed += 1;
127- const bg = if (is_add) theme.current.diff_add else theme.current.diff_delete;
128- const content = l[1..];
129- const painted = highlight.paint(a, content, rebaseSpans(a, spans, los[i], his[i]), .{ .bg = bg });
130- out.append(a, .{
131- .text = std.fmt.allocPrint(a, "{c}{s}", .{ l[0], painted }) catch l,
132- .bg = bg,
133- }) catch {};
47+ const fg = if (is_add) styles.roles.diff_add else styles.roles.diff_delete;
48+ out.append(a, .{ .text = line, .style = .{ .fg = fg } }) catch {};
13449 },
13550 }
13651 }
@@ -143,9 +58,9 @@ pub fn diffBody(a: std.mem.Allocator, d: tools.FileDiff, max_diff_lines: usize)
14358 var it = std.mem.splitScalar(u8, trimmed, '\n');
14459 var body: std.ArrayList([]const u8) = .empty;
14560 while (it.next()) |l| body.append(a, l) catch {};
146- return diffLines(a, d.path, body.items, max_diff_lines);
61+ return diffLines(a, body.items, max_diff_lines);
14762 }
14863 var out: std.ArrayList(BodyLine) = .empty;
149- if (d.note) |note| out.append(a, .{ .text = note, .style = .{ .fg = theme.current.comment } }) catch {};
64+ if (d.note) |note| out.append(a, .{ .text = note, .style = styles.roles.comment }) catch {};
15065 return .{ .lines = out.items };
15166 }
src/tui/highlight.zig+304−439
@@ -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(&regex, pat.ptr, REG_EXTENDED) != 0) return false;
117- defer regfree(&regex);
118- return regexec(&regex, 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.
src/tui/markdown_tables.scm+0−13
Cut short: this commit's diff is over 1000 lines.
src/tui/render.zig+4−13
Cut short: this commit's diff is over 1000 lines.
src/tui/screen.zig+3−3
Cut short: this commit's diff is over 1000 lines.
src/tui/stream.zig+6−10
Cut short: this commit's diff is over 1000 lines.
src/tui/styles.zig+98−13
Cut short: this commit's diff is over 1000 lines.
src/tui/term.zig+2−2
Cut short: this commit's diff is over 1000 lines.
src/tui/theme.zig+0−276
Cut short: this commit's diff is over 1000 lines.
src/tui/tool_view.zig+5−9
Cut short: this commit's diff is over 1000 lines.
src/tui/tui.zig+10−12
Cut short: this commit's diff is over 1000 lines.