graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(tui): grok-build UI parity — fence syntax highlighting, sticky prompt header, auto light/dark, synchronized paints
Rach Pradhan1e0da4f9e0dd
diff --git a/TUI/app.zig b/TUI/app.zigindex 3476d688..e31826b9 100644--- a/TUI/app.zig+++ b/TUI/app.zig@@ -41,6 +41,8 @@ pub const Model = struct {slash_sel: usize = 0,theme_id: theme_mod.Id = .night,+ /// Set once the user picks a theme; blocks the OSC-11 auto polarity.+ theme_explicit: bool = false,mode: AgentMode = .normal,effort: engine.Effort = .medium,fast: bool = false,diff --git a/TUI/dispatch.zig b/TUI/dispatch.zigindex e25bf04a..193c2e3f 100644--- a/TUI/dispatch.zig+++ b/TUI/dispatch.zig@@ -69,6 +69,7 @@ pub fn runCommand(self: *Model, line: []const u8) Effect {self.openOverlay(.theme);} else if (theme_mod.parse(arg)) |id| {self.theme_id = id;+ self.theme_explicit = true;self.pushFmt(.system, "theme: {s}", .{id.label()}) catch {};} else {self.pushFmt(.err, "unknown theme '{s}' — night|day|tokyo|rose|oscura", .{arg}) catch {};diff --git a/TUI/key.zig b/TUI/key.zigindex a0ee5461..95fb544c 100644--- a/TUI/key.zig+++ b/TUI/key.zig@@ -10,6 +10,8 @@ pub const Key = union(enum) {char: u8,/// Non-ASCII codepoint delivered via kitty CSI-u (é and friends).codepoint: u21,+ /// OSC 11 reply: the terminal's background RGB (auto light/dark).+ bg_report: [3]u8,ctrl: u8,ignore,enter,@@ -141,17 +143,24 @@ fn escapeSeq(bytes: []const u8, i: *usize) ?Key {/// OSC/DCS/APC/PM/SOS reply on stdin (e.g. a color query answer) — consume/// through BEL or ST so the payload is never typed into the prompt.fn stringSeq(bytes: []const u8, i: *usize) ?Key {+ const start = i.*; // bytes[start] is ']' for OSCvar j = i.* + 1;while (j < bytes.len) : (j += 1) {if (bytes[j] == 0x07) {+ const body = bytes[start + 1 .. j];i.* = j + 1;- return .ignore;+ return oscReply(bytes[start], body);}if (bytes[j] == 0x1b) {if (j + 1 < bytes.len) {// ST (ESC \) ends the string; any other ESC starts a new// sequence — leave it for the next parse.- i.* = if (bytes[j + 1] == '\\') j + 2 else j;+ if (bytes[j + 1] == '\\') {+ const body = bytes[start + 1 .. j];+ i.* = j + 2;+ return oscReply(bytes[start], body);+ }+ i.* = j;return .ignore;}break; // ST split across reads — wait for the backslash@@ -161,6 +170,30 @@ fn stringSeq(bytes: []const u8, i: *usize) ?Key {return null;}+/// A terminated OSC body. The only reply we act on is OSC 11 (background+/// color, answering run.zig's startup query) — everything else stays inert.+fn oscReply(kind: u8, body: []const u8) Key {+ if (kind != ']') return .ignore;+ if (!std.mem.startsWith(u8, body, "11;")) return .ignore;+ const rgb = parseXColor(body[3..]) orelse return .ignore;+ return .{ .bg_report = rgb };+}++/// `rgb:RRRR/GGGG/BBBB` (high byte) or `rgb:RR/GG/BB`.+fn parseXColor(s: []const u8) ?[3]u8 {+ if (!std.mem.startsWith(u8, s, "rgb:")) return null;+ var out: [3]u8 = undefined;+ var it = std.mem.splitScalar(u8, s[4..], '/');+ for (0..3) |n| {+ const part = it.next() orelse return null;+ if (part.len != 2 and part.len != 4) return null;+ const v = std.fmt.parseInt(u16, part, 16) catch return null;+ out[n] = if (part.len == 4) @intCast(v >> 8) else @intCast(v);+ }+ if (it.next() != null) return null;+ return out;+}+/// ESC O <final> — SS3 application keys (tmux/screen, macOS Terminal).fn ss3(bytes: []const u8, i: *usize) ?Key {if (i.* + 1 >= bytes.len) {diff --git a/TUI/key_tests.zig b/TUI/key_tests.zigindex b4878ca7..4d0eea93 100644--- a/TUI/key_tests.zig+++ b/TUI/key_tests.zig@@ -176,9 +176,15 @@ test "non-ASCII CSI-u codepoints type text instead of Escape" {test "OSC and APC replies on stdin are consumed, never typed" {var i: usize = 0;- try std.testing.expectEqual(Key.ignore, next("\x1b]11;rgb:14/14/14\x07", &i).?);+ // OSC 11 replies now carry the terminal background (auto light/dark).+ try std.testing.expectEqual(Key{ .bg_report = .{ 0x14, 0x14, 0x14 } }, next("\x1b]11;rgb:14/14/14\x07", &i).?);try std.testing.expectEqual(@as(usize, 18), i);i = 0;+ // 4-digit form takes the high byte; other OSC bodies stay inert.+ try std.testing.expectEqual(Key{ .bg_report = .{ 0xf6, 0xf6, 0xf6 } }, next("\x1b]11;rgb:f6f6/f6f6/f6f6\x1b\\", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.ignore, next("\x1b]10;rgb:14/14/14\x07", &i).?);+ i = 0;try std.testing.expectEqual(Key.ignore, next("\x1b_Gi=1;OK\x1b\\", &i).?);try std.testing.expectEqual(@as(usize, 11), i);i = 0;diff --git a/TUI/keys.zig b/TUI/keys.zigindex b558c052..652993ab 100644--- a/TUI/keys.zig+++ b/TUI/keys.zig@@ -23,6 +23,15 @@ pub fn handle(self: *Model, k: Key) Effect {if (self.input.undo()) self.setToast("undone");return .stay;}+ if (k == .bg_report) {+ // Startup OSC 11 reply: adopt the terminal's polarity unless the user+ // explicitly picked a theme. Fixed palettes, 1-bit decision (grok).+ if (!self.theme_explicit) {+ const want: @import("theme.zig").Id = if (@import("theme.zig").classifyLight(k.bg_report[0], k.bg_report[1], k.bg_report[2])) .day else .night;+ self.theme_id = want;+ }+ return .stay;+ }if (k == .mouse) return mouseKey(self, k.mouse);if (k == .paste_start) {self.pasting = true;diff --git a/TUI/markdown.zig b/TUI/markdown.zigindex a73e778a..98d633f7 100644--- a/TUI/markdown.zig+++ b/TUI/markdown.zig@@ -2,12 +2,87 @@const std = @import("std");const theme_mod = @import("theme.zig");+const syntax = @import("syntax.zig");/// Headers, fences, bullets, `code`, **bold**, and `/slash` tokens.pub fn render(a: std.mem.Allocator, src: []const u8, accent: []const u8) ![]const u8 {return renderTinted(a, src, accent, theme_mod.zinc400, theme_mod.zinc200);}+/// Theme-aware render: grok-style code fences — markers hidden behind a blank+/// separator row, a full-width background band (clear-to-EOL under the code+/// bg), and token colors from syntax.zig in the theme's polarity. Everything+/// else matches renderTinted.+pub fn renderThemed(a: std.mem.Allocator, src: []const u8, th: theme_mod.Theme) ![]const u8 {+ const light = th.id == .day;+ var lines = std.array_list.Managed([]const u8).init(a);+ defer lines.deinit();+ var split = std.mem.splitScalar(u8, src, '\n');+ while (split.next()) |line| try lines.append(line);++ var out = std.array_list.Managed(u8).init(a);+ var in_fence = false;+ var lang: ?*const syntax.Lang = null;+ var lex: syntax.State = .{};+ var first = true;+ var i: usize = 0;+ while (i < lines.items.len) {+ const line = lines.items[i];+ if (!first) try out.append('\n');+ first = false;+ const t = std.mem.trimStart(u8, line, " ");+ if (std.mem.startsWith(u8, t, "```")) {+ in_fence = !in_fence;+ if (in_fence) {+ lang = syntax.resolve(t[3..]);+ lex = .{};+ }+ // Hidden fence markers; the empty row is the grok separator.+ i += 1;+ continue;+ }+ if (in_fence) {+ try out.appendSlice(syntax.codeBg(light));+ try out.appendSlice("\x1b[K");+ if (lang) |l| {+ try syntax.highlightLine(&out, line, l, &lex, light);+ } else {+ try out.appendSlice(th.text);+ try out.appendSlice(line);+ }+ try out.appendSlice(theme_mod.reset);+ i += 1;+ continue;+ }+ if (tableLen(lines.items[i..])) |n| {+ try emitTable(&out, a, lines.items[i .. i + n], th.accent, th.muted, th.text);+ i += n;+ continue;+ }+ if (std.mem.startsWith(u8, t, "#")) {+ var h = t;+ while (h.len > 0 and h[0] == '#') h = h[1..];+ try out.appendSlice(theme_mod.bold);+ try out.appendSlice(th.accent);+ try out.appendSlice(std.mem.trimStart(u8, h, " "));+ try out.appendSlice(theme_mod.reset);+ i += 1;+ continue;+ }+ try out.appendSlice(th.text);+ var rest = line;+ if (std.mem.startsWith(u8, t, "- ") or std.mem.startsWith(u8, t, "* ")) {+ try out.appendSlice(th.accent);+ try out.appendSlice(" • ");+ try out.appendSlice(th.text);+ rest = t[2..];+ }+ try inlineSpans(&out, rest, th.accent, th.text);+ i += 1;+ }+ return out.toOwnedSlice();+}+pub fn renderTinted(a: std.mem.Allocator, src: []const u8, accent: []const u8, muted: []const u8, text: []const u8) ![]const u8 {var lines = std.array_list.Managed([]const u8).init(a);defer lines.deinit();diff --git a/TUI/render.zig b/TUI/render.zigindex 36cfce83..2c9d911b 100644--- a/TUI/render.zig+++ b/TUI/render.zig@@ -8,6 +8,7 @@ const app = @import("app.zig");const chrome = @import("chrome.zig");const engine = @import("engine.zig");const scrollback = @import("scrollback.zig");+const theme_mod = @import("theme.zig");const welcome = @import("welcome.zig");const Model = app.Model;@@ -79,7 +80,31 @@ pub fn render(self: *Model, gpa: std.mem.Allocator, width: usize, height: usize,if (self.scroll > max_scroll) self.scroll = max_scroll;const start = max_scroll - self.scroll;self.mid_skip = start;- for (mid_lines.items[start .. start + view_h]) |ln| {+ // grok sticky header (minimal single slot): once the last user prompt+ // scrolls past the viewport top, its first line stays pinned as row 0+ // with a blank separator row under it. The two chrome rows OCCLUDE the+ // two top content lines instead of shifting them, so the row↔line map+ // for everything below is unchanged and the bottom line stays put.+ var chrome_rows: usize = 0;+ if (view_h >= 5) {+ if (scrollback.stickyUserAbove(self, start, width)) |utext| {+ const th = self.theme();+ var head = std.array_list.Managed(u8).init(a);+ try head.appendSlice(th.accent);+ try head.appendSlice("\u{276F} ");+ try head.appendSlice(th.text);+ var one = utext;+ if (std.mem.indexOfScalar(u8, utext, '\n')) |nl| one = utext[0..nl];+ try head.appendSlice(one);+ const cols = if (width > 2) width - 2 else 1;+ try out.appendSlice(theme_mod.takeCols(head.items, cols));+ try out.appendSlice(theme_mod.reset);+ try out.append('\n');+ try out.append('\n');+ chrome_rows = 2;+ }+ }+ for (mid_lines.items[start + chrome_rows .. start + view_h]) |ln| {try out.appendSlice(ln);try out.append('\n');}@@ -228,3 +253,31 @@ test "debug overlay keeps the observability HUD and adds layout" {try std.testing.expect(std.mem.indexOf(u8, text, "images") != null);try std.testing.expect(std.mem.indexOf(u8, text, "pending") != null);}++test "sticky header pins the last scrolled-past user prompt with a blank separator" {+ var m: Model = undefined;+ m.setup(std.testing.allocator);+ defer m.deinit();+ try m.push(.user, "how do I frobnicate the widget?");+ var i: usize = 0;+ while (i < 40) : (i += 1) try m.push(.assistant, "a long explanation line that fills the scrollback with content");+ // follow-mode bottom: prompt is far above, so it pins.+ const frame = try render(&m, std.testing.allocator, 80, 24, 0);+ defer std.testing.allocator.free(frame);+ var it = std.mem.splitScalar(u8, frame, '\n');+ var row: usize = 0;+ var pin_row: ?usize = null;+ while (it.next()) |ln| : (row += 1) {+ if (std.mem.indexOf(u8, ln, "\u{276F} ") != null and std.mem.indexOf(u8, ln, "frobnicate") != null) {+ pin_row = row;+ break;+ }+ }+ try std.testing.expect(pin_row != null);+ // scrolled fully back to the top, the prompt is inline: no pin.+ m.follow = false;+ m.scroll = 100000;+ const top_frame = try render(&m, std.testing.allocator, 80, 24, 0);+ defer std.testing.allocator.free(top_frame);+ try std.testing.expect(std.mem.indexOf(u8, top_frame, "\u{276F} ") == null);+}diff --git a/TUI/root.zig b/TUI/root.zigindex 76f3e706..27f0a251 100644--- a/TUI/root.zig+++ b/TUI/root.zig@@ -45,6 +45,7 @@ test {_ = @import("chrome.zig");_ = @import("models.zig");_ = @import("markdown.zig");+ _ = @import("syntax.zig");_ = @import("dump.zig");_ = @import("effort.zig");_ = @import("sim.zig");diff --git a/TUI/run.zig b/TUI/run.zigindex e54754dd..3c036dea 100644--- a/TUI/run.zig+++ b/TUI/run.zig@@ -72,6 +72,7 @@ pub fn run(var stdout = Io.File.stdout().writer(io, &out_buf);const w = &stdout.interface;w.writeAll(enable_seq) catch {};+ w.writeAll("\x1b]11;?\x07") catch {}; // background query -> auto light/dark (key.zig bg_report)w.flush() catch {};traj.open(io);defer {@@ -106,8 +107,15 @@ pub fn run(const full = prev.len == 0 or rows != prev_rows or saw_gfx or has_gfx;// Kitty images sit above the cell grid and survive \x1b[K / dirty// paints — delete before every redraw that might have shown one.+ // ?2026 synchronized output: the terminal buffers everything+ // between begin/end and swaps atomically, so a diff paint can+ // never show a half-updated frame (grok-build does the same).+ // Terminals without it ignore the pair — strictly no worse.+ w.writeAll("\x1b[?2026h") catch {};if (saw_gfx or has_gfx) w.writeAll("\x1b_Ga=d,d=A,q=2\x1b\\") catch {};paint(w, frame, rows, cols, if (full) &.{} else prev, m.theme().bg) catch {};+ w.writeAll("\x1b[?2026l") catch {};+ w.flush() catch {};if (prev.len != 0) gpa.free(prev);prev = gpa.dupe(u8, frame) catch &.{};prev_rows = rows;@@ -180,6 +188,7 @@ fn parkToShell(io: Io, w: *Io.Writer, raw: *tty.RawState) void {}raw.* = tty.enterRaw() orelse raw.*;w.writeAll(enable_seq) catch {};+ w.writeAll("\x1b]11;?\x07") catch {}; // background query -> auto light/dark (key.zig bg_report)w.flush() catch {};_ = io;}diff --git a/TUI/scrollback.zig b/TUI/scrollback.zigindex cb2926c0..f7d2c591 100644--- a/TUI/scrollback.zig+++ b/TUI/scrollback.zig@@ -134,6 +134,40 @@ pub fn visualOfIndex(self: *const Model, idx: usize, width: usize) ?usize {return null;}+/// The last user prompt whose first visual row sits strictly above+/// `top_line` — the grok sticky-header candidate. Same row math as+/// visualOfIndex so the pin agrees with what the viewport actually shows.+pub fn stickyUserAbove(self: *const Model, top_line: usize, width: usize) ?[]const u8 {+ if (top_line == 0) return null;+ var arena = std.heap.ArenaAllocator.init(self.alloc);+ defer arena.deinit();+ const a = arena.allocator();+ var best: ?[]const u8 = null;+ var v: usize = 0;+ var i: usize = 0;+ while (i < self.history.items.len and v < top_line) {+ const e = self.history.items[i];+ if (e.kind == .tool) {+ const run = self.toolRun(i);+ if (self.history.items[run.start].folded) {+ v += lineCount(summary(self, a, run.start, run.end, false) catch "");+ } else {+ var t = run.start;+ while (t < run.end) {+ v += lineCount(toolVisual(self, a, t, run.end, width, self.now_ms, false) catch "");+ t = nextTool(self, t, run.end);+ }+ }+ i = run.end;+ continue;+ }+ if (e.kind == .user and v < top_line) best = e.text;+ v += lineCount(row(self, a, i, e, width, self.now_ms, false) catch "");+ i += 1;+ }+ return best;+}+fn lineCount(s: []const u8) usize {if (s.len == 0) return 1;return std.mem.count(u8, s, "\n") + 1;@@ -213,7 +247,7 @@ fn row(self: *const Model, a: std.mem.Allocator, idx: usize, e: app.Entry, widthelsee.text;const body = switch (e.kind) {- .assistant => try @import("markdown.zig").renderTinted(a, raw, th.accent, th.muted, th.text),+ .assistant => try @import("markdown.zig").renderThemed(a, raw, th),.user => try @import("markdown.zig").renderUser(a, raw, th.accent, th.text),else => raw,};diff --git a/TUI/syntax.zig b/TUI/syntax.zignew file mode 100644index 00000000..9a3276ee--- /dev/null+++ b/TUI/syntax.zig@@ -0,0 +1,347 @@+//! Code-fence syntax highlighting — grok-build's token classes and colors+//! (grok-night / grok-day tmThemes), driven by a small line-resumable lexer+//! instead of syntect. One `State` threads across a fence's lines so block+//! comments and multiline strings survive line breaks; clone it for a+//! streaming tail the way grok's open-fence cache does.++const std = @import("std");++pub const Class = enum { text, comment, string, escape, number, keyword, type_name, builtin, function, operator, bracket, property };++/// grok-night (dark) token colors, verbatim from the tmTheme.+fn darkColor(c: Class) []const u8 {+ return switch (c) {+ .text => "\x1b[38;2;200;200;200m", // #c8c8c8+ .comment => "\x1b[38;2;81;89;125m", // #51597d+ .string => "\x1b[38;2;158;206;106m", // #9ece6a+ .escape => "\x1b[38;2;137;221;255m", // #89ddff+ .number => "\x1b[38;2;255;158;100m", // #ff9e64+ .keyword => "\x1b[38;2;187;154;247m", // #bb9af7+ .type_name => "\x1b[38;2;13;185;215m", // #0db9d7+ .builtin => "\x1b[38;2;13;185;215m", // #0db9d7+ .function => "\x1b[38;2;122;162;247m", // #7aa2f7+ .operator => "\x1b[38;2;137;221;255m", // #89ddff+ .bracket => "\x1b[38;2;154;189;245m", // #9abdf5+ .property => "\x1b[38;2;125;207;255m", // #7dcfff+ };+}++/// grok-day (light) token colors, verbatim from the tmTheme.+fn lightColor(c: Class) []const u8 {+ return switch (c) {+ .text => "\x1b[38;2;68;68;68m", // #444444+ .comment => "\x1b[38;2;144;144;144m", // #909090+ .string => "\x1b[38;2;55;142;35m", // #378E23+ .escape => "\x1b[38;2;85;128;168m", // #5580A8+ .number => "\x1b[38;2;195;105;30m", // #C3691E+ .keyword => "\x1b[38;2;125;75;198m", // #7D4BC6+ .type_name => "\x1b[38;2;15;135;162m", // #0F87A2+ .builtin => "\x1b[38;2;15;135;162m", // #0F87A2+ .function => "\x1b[38;2;47;100;210m", // #2F64D2+ .operator => "\x1b[38;2;85;128;168m", // #5580A8+ .bracket => "\x1b[38;2;74;114;176m", // #4A72B0+ .property => "\x1b[38;2;0;130;170m", // #0082AA+ };+}++pub fn color(c: Class, light: bool) []const u8 {+ return if (light) lightColor(c) else darkColor(c);+}++/// Code-block background band (grok `md_code_bg`): #1c1c1c dark / #e4e4e4 light.+pub fn codeBg(light: bool) []const u8 {+ return if (light) "\x1b[48;2;228;228;228m" else "\x1b[48;2;28;28;28m";+}++pub const Lang = struct {+ names: []const []const u8, // fence tokens AND file extensions+ line_comment: []const u8,+ block_open: []const u8 = "",+ block_close: []const u8 = "",+ keywords: []const []const u8,+ types: []const []const u8,+ builtins: []const []const u8 = &.{},+ hash_types_upper: bool = false, // Capitalized identifiers are types (Zig/Rust/Go style)+};++const zig_lang: Lang = .{+ .names = &.{ "zig", "ziglang" },+ .line_comment = "//",+ .keywords = &.{ "const", "var", "fn", "pub", "return", "if", "else", "while", "for", "switch", "defer", "errdefer", "try", "catch", "orelse", "break", "continue", "struct", "enum", "union", "error", "test", "comptime", "inline", "export", "extern", "and", "or", "unreachable", "usingnamespace", "async", "await", "threadlocal", "packed", "volatile", "align", "callconv", "noalias" },+ .types = &.{ "u8", "u16", "u32", "u64", "usize", "i8", "i16", "i32", "i64", "isize", "f32", "f64", "bool", "void", "type", "anytype", "anyerror", "noreturn", "u21", "c_int", "null", "undefined", "true", "false" },+ .hash_types_upper = true,+};+const rust_lang: Lang = .{+ .names = &.{ "rust", "rs" },+ .line_comment = "//",+ .block_open = "/*",+ .block_close = "*/",+ .keywords = &.{ "fn", "let", "mut", "pub", "use", "mod", "struct", "enum", "impl", "trait", "return", "if", "else", "while", "for", "loop", "match", "break", "continue", "move", "ref", "where", "async", "await", "dyn", "unsafe", "extern", "crate", "self", "Self", "super", "static", "const", "type", "in", "as" },+ .types = &.{ "u8", "u16", "u32", "u64", "usize", "i8", "i16", "i32", "i64", "isize", "f32", "f64", "bool", "str", "String", "Vec", "Option", "Result", "Box", "true", "false", "None", "Some", "Ok", "Err" },+ .hash_types_upper = true,+};+const py_lang: Lang = .{+ .names = &.{ "python", "py", "python3" },+ .line_comment = "#",+ .keywords = &.{ "def", "class", "return", "if", "elif", "else", "while", "for", "in", "import", "from", "as", "with", "try", "except", "finally", "raise", "pass", "break", "continue", "lambda", "yield", "global", "nonlocal", "assert", "del", "not", "and", "or", "is", "async", "await", "match", "case" },+ .types = &.{ "int", "float", "str", "bool", "list", "dict", "set", "tuple", "bytes", "None", "True", "False", "self", "object" },+ .builtins = &.{ "print", "len", "range", "open", "enumerate", "zip", "map", "filter", "sorted", "isinstance", "super", "type", "getattr", "setattr", "hasattr" },+};+const js_lang: Lang = .{+ .names = &.{ "javascript", "js", "typescript", "ts", "jsx", "tsx", "mjs", "cjs" },+ .line_comment = "//",+ .block_open = "/*",+ .block_close = "*/",+ .keywords = &.{ "function", "const", "let", "var", "return", "if", "else", "while", "for", "of", "in", "class", "extends", "new", "import", "export", "from", "default", "async", "await", "try", "catch", "finally", "throw", "switch", "case", "break", "continue", "typeof", "instanceof", "delete", "yield", "static", "get", "set", "interface", "implements", "enum", "declare", "readonly", "as", "satisfies" },+ .types = &.{ "string", "number", "boolean", "object", "any", "unknown", "never", "undefined", "null", "true", "false", "this", "void", "Promise", "Array", "Map", "Set" },+ .builtins = &.{ "console", "require", "module", "process", "JSON", "Math", "Object", "window", "document" },+ .hash_types_upper = true,+};+const go_lang: Lang = .{+ .names = &.{ "go", "golang" },+ .line_comment = "//",+ .block_open = "/*",+ .block_close = "*/",+ .keywords = &.{ "func", "var", "const", "type", "struct", "interface", "map", "chan", "return", "if", "else", "for", "range", "switch", "case", "default", "break", "continue", "go", "defer", "select", "package", "import", "fallthrough", "goto" },+ .types = &.{ "string", "int", "int8", "int16", "int32", "int64", "uint", "uint8", "uint16", "uint32", "uint64", "byte", "rune", "float32", "float64", "bool", "error", "any", "nil", "true", "false", "iota" },+ .builtins = &.{ "make", "len", "cap", "append", "copy", "new", "delete", "panic", "recover", "print", "println" },+ .hash_types_upper = true,+};+const c_lang: Lang = .{+ .names = &.{ "c", "h", "cpp", "cc", "cxx", "hpp", "c++" },+ .line_comment = "//",+ .block_open = "/*",+ .block_close = "*/",+ .keywords = &.{ "if", "else", "while", "for", "return", "break", "continue", "switch", "case", "default", "struct", "enum", "union", "typedef", "static", "extern", "const", "inline", "sizeof", "goto", "do", "class", "public", "private", "protected", "template", "typename", "namespace", "using", "new", "delete", "virtual", "override", "nullptr", "auto", "constexpr" },+ .types = &.{ "int", "char", "long", "short", "unsigned", "signed", "float", "double", "void", "bool", "size_t", "uint8_t", "uint16_t", "uint32_t", "uint64_t", "int8_t", "int16_t", "int32_t", "int64_t", "true", "false", "NULL" },+ .hash_types_upper = true,+};+const sh_lang: Lang = .{+ .names = &.{ "bash", "sh", "shell", "zsh", "console" },+ .line_comment = "#",+ .keywords = &.{ "if", "then", "else", "elif", "fi", "for", "while", "do", "done", "case", "esac", "function", "return", "local", "export", "source", "in", "select", "until", "declare", "readonly", "shift", "exit", "set", "unset", "trap" },+ .types = &.{"true"},+ .builtins = &.{ "echo", "cd", "ls", "grep", "sed", "awk", "cat", "curl", "git", "rm", "cp", "mv", "mkdir", "printf", "read", "test", "which", "find", "xargs", "sort", "head", "tail" },+};+const json_lang: Lang = .{+ .names = &.{"json"},+ .line_comment = "",+ .keywords = &.{},+ .types = &.{ "true", "false", "null" },+};+const yaml_lang: Lang = .{+ .names = &.{ "yaml", "yml" },+ .line_comment = "#",+ .keywords = &.{},+ .types = &.{ "true", "false", "null", "yes", "no" },+};+const sql_lang: Lang = .{+ .names = &.{ "sql", "sqlite", "postgres", "mysql" },+ .line_comment = "--",+ .block_open = "/*",+ .block_close = "*/",+ .keywords = &.{ "select", "from", "where", "insert", "into", "values", "update", "set", "delete", "create", "table", "index", "join", "left", "right", "inner", "outer", "on", "group", "by", "order", "having", "limit", "offset", "as", "and", "or", "not", "in", "is", "like", "between", "union", "all", "distinct", "primary", "key", "foreign", "references", "drop", "alter", "add", "SELECT", "FROM", "WHERE", "INSERT", "INTO", "VALUES", "UPDATE", "SET", "DELETE", "CREATE", "TABLE", "INDEX", "JOIN", "LEFT", "RIGHT", "INNER", "OUTER", "ON", "GROUP", "BY", "ORDER", "HAVING", "LIMIT", "AS", "AND", "OR", "NOT", "IN", "IS", "LIKE", "UNION", "PRIMARY", "KEY", "DROP", "ALTER", "ADD" },+ .types = &.{ "integer", "text", "real", "blob", "varchar", "boolean", "date", "timestamp", "INTEGER", "TEXT", "REAL", "BLOB", "VARCHAR", "BOOLEAN", "NULL" },+};++const langs = [_]*const Lang{ &zig_lang, &rust_lang, &py_lang, &js_lang, &go_lang, &c_lang, &sh_lang, &json_lang, &yaml_lang, &sql_lang };++/// Fence-info resolution, grok order: `start:end:path` citation form first+/// (extension lookup), then the whole info string as a token. Unknown → null+/// (the fence still gets the background band, just uncolored text).+pub fn resolve(fence_info: []const u8) ?*const Lang {+ const info = std.mem.trim(u8, fence_info, " \t");+ if (info.len == 0) return null;+ blk: {+ var it = std.mem.splitScalar(u8, info, ':');+ const a = it.next() orelse break :blk;+ const b = it.next() orelse break :blk;+ const path = it.rest();+ if (a.len == 0 or b.len == 0 or path.len == 0) break :blk;+ for (a) |ch| if (!std.ascii.isDigit(ch)) break :blk;+ for (b) |ch| if (!std.ascii.isDigit(ch)) break :blk;+ const dot = std.mem.lastIndexOfScalar(u8, path, '.') orelse break :blk;+ if (byName(path[dot + 1 ..])) |l| return l;+ break :blk;+ }+ return byName(info);+}++fn byName(token: []const u8) ?*const Lang {+ var buf: [24]u8 = undefined;+ if (token.len == 0 or token.len > buf.len) return null;+ const lower = std.ascii.lowerString(&buf, token);+ for (&langs) |l| {+ for (l.names) |n| if (std.mem.eql(u8, lower, n)) return l;+ }+ return null;+}++/// Lexer state threaded across a fence's lines.+pub const State = struct {+ in_block_comment: bool = false,+};++fn isIdent(c: u8) bool {+ return std.ascii.isAlphanumeric(c) or c == '_' or c == '@';+}++fn listHas(list: []const []const u8, word: []const u8) bool {+ for (list) |w| if (std.mem.eql(u8, w, word)) return true;+ return false;+}++/// Highlight one line into `out` as SGR spans. Emits fg colors only — the+/// caller owns the background band and the trailing reset.+pub fn highlightLine(out: *std.array_list.Managed(u8), line: []const u8, lang: *const Lang, st: *State, light: bool) !void {+ var i: usize = 0;+ var cls: ?Class = null;+ while (i < line.len) {+ if (st.in_block_comment) {+ const close = std.mem.indexOf(u8, line[i..], lang.block_close);+ const end = if (close) |c| i + c + lang.block_close.len else line.len;+ try emit(out, &cls, .comment, line[i..end], light);+ if (close != null) st.in_block_comment = false;+ i = end;+ continue;+ }+ const c = line[i];+ // comments+ if (lang.line_comment.len > 0 and std.mem.startsWith(u8, line[i..], lang.line_comment)) {+ try emit(out, &cls, .comment, line[i..], light);+ break;+ }+ if (lang.block_open.len > 0 and std.mem.startsWith(u8, line[i..], lang.block_open)) {+ st.in_block_comment = true;+ try emit(out, &cls, .comment, line[i .. i + lang.block_open.len], light);+ i += lang.block_open.len;+ continue;+ }+ // strings (single-line; escapes highlighted inside)+ if (c == '"' or c == '\'' or c == '`') {+ const quote = c;+ var j = i + 1;+ try emit(out, &cls, .string, line[i .. i + 1], light);+ while (j < line.len) {+ if (line[j] == '\\' and j + 1 < line.len) {+ try emit(out, &cls, .escape, line[j .. j + 2], light);+ j += 2;+ continue;+ }+ if (line[j] == quote) break;+ const k = std.mem.indexOfAnyPos(u8, line, j, &.{ '\\', quote }) orelse line.len;+ try emit(out, &cls, .string, line[j..k], light);+ j = k;+ }+ if (j < line.len) {+ try emit(out, &cls, .string, line[j .. j + 1], light);+ j += 1;+ }+ i = j;+ continue;+ }+ // numbers+ if (std.ascii.isDigit(c)) {+ var j = i + 1;+ while (j < line.len and (std.ascii.isHex(line[j]) or line[j] == '.' or line[j] == 'x' or line[j] == '_' or line[j] == 'o' or line[j] == 'b')) j += 1;+ try emit(out, &cls, .number, line[i..j], light);+ i = j;+ continue;+ }+ // identifiers+ if (std.ascii.isAlphabetic(c) or c == '_' or c == '@') {+ var j = i + 1;+ while (j < line.len and isIdent(line[j])) j += 1;+ const word = line[i..j];+ const wc: Class = if (listHas(lang.keywords, word))+ .keyword+ else if (listHas(lang.types, word))+ .type_name+ else if (listHas(lang.builtins, word))+ .builtin+ else if (word[0] == '@')+ .builtin+ else if (j < line.len and line[j] == '(')+ .function+ else if (lang.hash_types_upper and std.ascii.isUpper(word[0]))+ .type_name+ else if (j < line.len and line[j] == ':' and lang == &json_lang)+ .property+ else+ .text;+ try emit(out, &cls, wc, word, light);+ i = j;+ continue;+ }+ // brackets vs operators vs plain+ const oc: Class = switch (c) {+ '(', ')', '[', ']', '{', '}' => .bracket,+ '+', '-', '*', '/', '=', '<', '>', '!', '&', '|', '^', '%', '~', '?', ';', ':', ',', '.' => .operator,+ else => .text,+ };+ try emit(out, &cls, oc, line[i .. i + 1], light);+ i += 1;+ }+}++fn emit(out: *std.array_list.Managed(u8), current: *?Class, cls: Class, text: []const u8, light: bool) !void {+ if (text.len == 0) return;+ if (current.* != cls) {+ try out.appendSlice(color(cls, light));+ current.* = cls;+ }+ try out.appendSlice(text);+}++test "zig line: keywords, types, strings, numbers, comment take grok-night colors" {+ var out = std.array_list.Managed(u8).init(std.testing.allocator);+ defer out.deinit();+ var st: State = .{};+ try highlightLine(&out, "const x: u32 = 0x1f; // note \"quoted\"", &zig_lang, &st, false);+ const s = out.items;+ try std.testing.expect(std.mem.indexOf(u8, s, "\x1b[38;2;187;154;247mconst") != null); // keyword+ try std.testing.expect(std.mem.indexOf(u8, s, "\x1b[38;2;13;185;215mu32") != null); // type+ try std.testing.expect(std.mem.indexOf(u8, s, "\x1b[38;2;255;158;100m0x1f") != null); // number+ try std.testing.expect(std.mem.indexOf(u8, s, "\x1b[38;2;81;89;125m// note \"quoted\"") != null); // comment eats the rest+}++test "block comment state survives across lines" {+ var out = std.array_list.Managed(u8).init(std.testing.allocator);+ defer out.deinit();+ var st: State = .{};+ try highlightLine(&out, "let a = 1; /* open", &js_lang, &st, false);+ try std.testing.expect(st.in_block_comment);+ out.clearRetainingCapacity();+ try highlightLine(&out, "still comment */ let b = 2;", &js_lang, &st, false);+ try std.testing.expect(!st.in_block_comment);+ try std.testing.expect(std.mem.indexOf(u8, out.items, "\x1b[38;2;81;89;125mstill comment */") != null);+ try std.testing.expect(std.mem.indexOf(u8, out.items, "\x1b[38;2;187;154;247mlet") != null);+}++test "fence info resolution: token, citation path, unknown" {+ try std.testing.expect(resolve("rust") == &rust_lang);+ try std.testing.expect(resolve("py") == &py_lang);+ try std.testing.expect(resolve("37:65:crates/foo/src/bar.rs") == &rust_lang);+ try std.testing.expect(resolve("rust title=x") == null); // whole-string token, grok semantics+ try std.testing.expect(resolve("") == null);+ try std.testing.expect(resolve("madeuplang") == null);+}++test "light polarity swaps to grok-day colors" {+ var out = std.array_list.Managed(u8).init(std.testing.allocator);+ defer out.deinit();+ var st: State = .{};+ try highlightLine(&out, "def f():", &py_lang, &st, true);+ try std.testing.expect(std.mem.indexOf(u8, out.items, "\x1b[38;2;125;75;198mdef") != null); // #7D4BC6+}++test "strings color their escapes separately" {+ var out = std.array_list.Managed(u8).init(std.testing.allocator);+ defer out.deinit();+ var st: State = .{};+ try highlightLine(&out, "s = \"a\\nb\"", &py_lang, &st, false);+ try std.testing.expect(std.mem.indexOf(u8, out.items, "\x1b[38;2;137;221;255m\\n") != null);+ // the opening quote and 'a' share one string span; 'b' re-opens it after the escape+ try std.testing.expect(std.mem.indexOf(u8, out.items, "\x1b[38;2;158;206;106m\"a") != null);+ try std.testing.expect(std.mem.indexOf(u8, out.items, "\x1b[38;2;158;206;106mb") != null);+}diff --git a/TUI/theme.zig b/TUI/theme.zigindex f4ff387d..a7f5f699 100644--- a/TUI/theme.zig+++ b/TUI/theme.zig@@ -94,6 +94,25 @@ pub fn next(id: Id) Id {return @enumFromInt((@intFromEnum(id) + 1) % all.len);}+/// grok's polarity test: BT.709 luminance over sRGB-linearized channels,+/// light at >= 0.5. Only the 1-bit answer is kept — the palette stays fixed.+pub fn classifyLight(r: u8, g: u8, b: u8) bool {+ const lum = 0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b);+ return lum >= 0.5;+}++fn linear(c: u8) f64 {+ const s = @as(f64, @floatFromInt(c)) / 255.0;+ return if (s <= 0.04045) s / 12.92 else std.math.pow(f64, (s + 0.055) / 1.055, 2.4);+}++test "classifyLight: grok-night bg is dark, grok-day bg is light" {+ try std.testing.expect(!classifyLight(0x14, 0x14, 0x14));+ try std.testing.expect(!classifyLight(0x24, 0x28, 0x3b)); // tokyo storm+ try std.testing.expect(classifyLight(0xf6, 0xf6, 0xf6));+ try std.testing.expect(classifyLight(0xee, 0xee, 0xee));+}+/// Index just past the escape sequence starting at `start` (s[start] == 0x1b)./// Skips CSI, OSC/DCS/APC/PM/SOS (to BEL or ST), SS3, and ESC+char — a/// truncation mid-sequence would emit broken escapes into the frame.