From 266515537a917154ef4736a1d6b1cc97be23fced Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 16 Nov 2026 22:17:47 -0300 Subject: mouse: no drag guides, and columns resize by their grips alone A drag draws no guide lines: the dashes where a pane or column would land, the carried column's rail and the held seam's dashes are gone, with the guide region kind, Surface.overlayDash, the rail's Region.clip and MAX_GUIDES; the gui's floating draw group is the debug box's alone. The line between two columns is no resize handle: Drag.border_v and its corner variant are gone, with clampBorderCol and the unused chromeTarget. A press there is a press in the pane under it (a sweep). A column resizes by its grip, a pane by its grip or, in a window, the rule above it (border_h, unchanged). Tests: the corner and border-drag unit tests and the cornerdrag and cornerdrag-left tty cases are deleted; windowops loses its border drag and tagalign2col widens its column by the grip; colgrip, shrinktag and windowops goldens drop the guides; a unit test pins that a press on the line between columns sweeps and resizes nothing. The cheatsheet, themes, render-pipeline notes and changelog say so. Co-Authored-By: Claude Opus 5.5 --- src/CHANGELOG.md | 7 ++ src/body_layer.zig | 2 +- src/draw.zig | 95 +------------------ src/gui/gui.zig | 14 +-- src/layout.zig | 14 +-- src/mouse.zig | 261 ++++------------------------------------------------- src/surface.zig | 18 +--- 7 files changed, 39 insertions(+), 372 deletions(-) (limited to 'src') diff --git a/src/CHANGELOG.md b/src/CHANGELOG.md index 633687e8..afc14a0c 100644 --- a/src/CHANGELOG.md +++ b/src/CHANGELOG.md @@ -2,6 +2,13 @@ ## Unreleased +- A drag draws no guide lines: no dashes where a pane or column would + land, no rail for a carried column, no dashed seam under a pane rule + held. The line between two columns no longer resizes them (nor, at a + pane's corner, the panes too): a press there is a press in the pane. + A column resizes by its box, left of its tag; a pane by its own box, + or in a window by the rule above it. + - zstbi is upstream's again (zig-gamedev/zstbi, its main): the fork pinned for Zig 0.17 was deleted, and a fresh checkout could not fetch it. diff --git a/src/body_layer.zig b/src/body_layer.zig index 76aec179..dbf0156d 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -195,7 +195,7 @@ pub fn joinBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, layer.id = @intCast(id); layer.serial = pane.serial; const body = s.region(.body, id).?; - layer.viewport = .{ .x = body.rect.x, .y = body.rect.y, .w = body.rect.w - body.clip, .h = body.rect.h }; + layer.viewport = .{ .x = body.rect.x, .y = body.rect.y, .w = body.rect.w, .h = body.rect.h }; layer.cols = width; layer.rows = @intCast(logical_rows); layer.context_rows = pane.context_rows; diff --git a/src/draw.zig b/src/draw.zig index fc90586e..4809ebd4 100644 --- a/src/draw.zig +++ b/src/draw.zig @@ -116,24 +116,6 @@ pub fn place(p: *Pardes, s: *Surface) void { } if (p.settings.workspace_tag) s.addRegion(.{ .kind = .workspace_tag, .rect = .{ .x = 0, .y = 0, .w = s.cols, .h = p.topBarHeight() } }); - // A column carried to the window's right edge shows where it lands as a - // rail in the last cell: the layers under it stop a cell short. - if (v.drag == .column_move) rail: { - const d = v.drag.column_move; - const source = layout.columnBySerial(p, d.serial) orelse break :rail; - const edge: u16 = switch (layout.columnDrop(p, source, d.cur_x, d.grab)) { - .stay => break :rail, - .reorder => |target| if (target < source) v.col_x[target] else v.col_x[target] + v.col_w[target], - .edge => |x| x, - }; - if (edge != s.cols) break :rail; - for (s.regions[0..s.nregions]) |*region| switch (region.kind) { - .body, .tag, .notice, .column_tag => if (region.rect.x + region.rect.w == s.cols) { - region.clip = 1; - }, - else => {}, - }; - } } /// A pane's grip in the grid: `box` focused, else halfway between its ring @@ -252,8 +234,6 @@ fn joinNotice(p: *Pardes, s: *Surface, arena: std.mem.Allocator, region: Region) if (layer.cursor) |caret| { if (caret.x >= skip) s.cursor = .{ .x = region.rect.x + caret.x - @as(u16, @intCast(skip)), .y = region.rect.y, .bar = caret.bar }; } - // Laid out at its full width; only shown short of the rail. - layer.viewport.w -|= region.clip; } pub fn render(p: *Pardes, arena: std.mem.Allocator) !*Surface { @@ -327,77 +307,6 @@ pub fn render(p: *Pardes, arena: std.mem.Allocator) !*Surface { try paintHeaders(p, s); - switch (v.drag) { - .border_v => |d| { - if (d.cur_x < s.cols) { - var row: u16 = p.topBarHeight(); - while (row < s.rows) : (row += 1) s.overlayDash(d.cur_x, row, "╎"); - s.addRegion(.{ .kind = .guide, .rect = .{ .x = d.cur_x, .y = p.topBarHeight(), .w = 1, .h = s.rows -| p.topBarHeight() } }); - } - if (d.corner) |k| if (d.cur_y < s.rows) { - const first = if (k.col == d.left_col) v.col_x[k.col] else d.cur_x +| 1; - const end = if (k.col == d.left_col) d.cur_x else v.col_x[k.col] +| v.col_w[k.col] -| 1; - var col = first; - while (col <= end and col < s.cols) : (col += 1) s.overlayDash(col, d.cur_y, "╌"); - if (col > first) s.addRegion(.{ .kind = .guide, .rect = .{ .x = first, .y = d.cur_y, .w = col - first, .h = 1 } }); - }; - }, - // A column that went away mid-drag has nothing to guide. - .border_h => |d| if (d.cur_y < s.rows and d.col < v.ncol and v.col_x[d.col] < s.cols) { - const end = @min(s.cols, v.col_x[d.col] + v.col_w[d.col]); - var col = v.col_x[d.col]; - while (col < end) : (col += 1) s.overlayDash(col, d.cur_y, "╌"); - s.addRegion(.{ .kind = .guide, .rect = .{ .x = v.col_x[d.col], .y = d.cur_y, .w = end - v.col_x[d.col], .h = 1 } }); - }, - .column_move => |d| rail: { - const source = layout.columnBySerial(p, d.serial) orelse break :rail; - if (s.cols == 0) break :rail; - // Where the column's left edge would land, reordered or not. - const edge: u16 = switch (layout.columnDrop(p, source, d.cur_x, d.grab)) { - .stay => break :rail, - .reorder => |target| if (target < source) v.col_x[target] else v.col_x[target] + v.col_w[target], - .edge => |x| x, - }; - // The layers under an outside rail stop a cell short of it: - // `place` clipped them. - // The rail runs in the seam cell left of the edge, where a - // border drag's does: the edge cell itself is a gutter, which - // the GUI paints as a scroll rail that swallowed the dashes. - // At the window's left edge there is no seam, so it runs just - // past that scroll rail instead. It takes the lit grip's - // color: this is where the grabbed column lands. - const x = @min(if (edge == 0) config.GUTTER - 1 else edge - 1, s.cols -| 1); - var row: u16 = p.topBarHeight(); - // A guide region for each run of it the tags do not break. - var run: u16 = row; - while (row < s.rows) : (row += 1) { - // Past the left edge's scroll rail the rail would cut - // through column 0's grip and pane boxes: leave them whole. - if (edge == 0 and s.at(x, row).style.font_role == .tagline) { - if (row > run) s.addRegion(.{ .kind = .guide, .rect = .{ .x = x, .y = run, .w = 1, .h = row - run } }); - run = row + 1; - continue; - } - s.overlayDash(x, row, "╎"); - s.at(x, row).style.fg = .{ .rgb = chrome.column_box }; - } - if (row > run) s.addRegion(.{ .kind = .guide, .rect = .{ .x = x, .y = run, .w = 1, .h = row - run } }); - }, - .move => |d| if (d.cur_x < s.cols) { - if (layout.movePlacement(p, d.id, d.cur_x, d.cur_y)) |placement| if (placement.row < s.rows and v.col_x[placement.preview_col] + v.col_w[placement.preview_col] <= s.cols) { - var col: u16 = v.col_x[placement.preview_col]; - while (col < v.col_x[placement.preview_col] + v.col_w[placement.preview_col]) : (col += 1) { - s.set(col, placement.row, "╌", .{ .fg = .{ .rgb = chrome.lineno } }); - } - s.set(d.cur_x, placement.row, "▌", .{ .fg = .{ .rgb = chrome.lineno } }); - s.addRegion(.{ .kind = .guide, .rect = .{ .x = v.col_x[placement.preview_col], .y = placement.row, .w = v.col_w[placement.preview_col], .h = 1 } }); - s.addRegion(.{ .kind = .guide, .rect = .{ .x = d.cur_x, .y = placement.row, .w = 1, .h = 1 } }); - }; - }, - // A hover draws no hint: columns resize by their grips. - .none, .select => {}, - } - // debug overlay: a small stats box drawn last, top-right ("Debug") if (p.settings.debug) if (p.panes[v.active]) |at| { var nlive: usize = 0; @@ -606,8 +515,6 @@ fn paintHeaders(p: *Pardes, s: *Surface) !void { const layer = &s.tag_layers[MAX_PANES + c]; try renderHeaderLayer(p, layer, .column, @intCast(c), region.rect, tagline.columnTag(p, c), top, bg, fg); if (v.col_x[c] < s.cols) joinHeaderRows(s, layer, fg); - // Laid out at its full width; only shown short of the rail. - layer.viewport.w -|= region.clip; }; } @@ -809,7 +716,7 @@ fn joinPaneTag(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, r layer.kind = .pane; layer.id = @intCast(id); layer.serial = pane.serial; - layer.viewport = .{ .x = region.rect.x, .y = region.rect.y, .w = region.rect.w - region.clip, .h = rows }; + layer.viewport = .{ .x = region.rect.x, .y = region.rect.y, .w = region.rect.w, .h = rows }; layer.cols = columns; layer.rows = rows; layer.context_rows = 0; diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 537271f1..120a4595 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -861,12 +861,12 @@ const Group = struct { }; /// The frame's draw groups, bottom to top: the page and the panes, the -/// notices floating over them, the guides and the debug box the core paints -/// over those, and ink (the bar cursors; the cursor's glide draws after it). +/// notices floating over them, the debug box the core paints over those, +/// and ink (the bar cursors; the cursor's glide draws after it). const Groups = struct { items: [4]Group = @splat(.{}), notices: usize = 1, - guides: usize = 2, + debug: usize = 2, ink: usize = 3, len: usize = 4, }; @@ -876,7 +876,7 @@ const Groups = struct { const Cover = packed struct(u16) { /// A layer draws it; the grid's copy is not drawn. layer: bool = false, - /// Under a guide or the debug box: drawn from the grid over the panes. + /// Under the debug box: drawn from the grid over the panes. floating: bool = false, /// In a pane's grip, `grip_offset` cells from its left: the grip's /// glyph is the cell that far to the left. @@ -943,7 +943,7 @@ fn coverFrame(cover: []Cover, cols: u16, rows: u16, body_layers: []const pardes. mark.rect(cover, cols, rows, .{ .x = region.rect.x, .y = 0, .w = 1, .h = rows }, "anchor", true); if (region.active) if (bar) |b| mark.rect(cover, cols, rows, .{ .x = region.rect.x, .y = b.y, .w = region.rect.w, .h = b.h }, "focus", true); }, - .guide, .debug => mark.rect(cover, cols, rows, region.rect, "floating", true), + .debug => mark.rect(cover, cols, rows, region.rect, "floating", true), else => {}, }; } @@ -4548,7 +4548,7 @@ fn renderFrame( while (col < surface.cols) : (col += 1) { const at = @as(usize, row) * surface.cols + col; if (covered[at].layer and !covered[at].floating) continue; - const group_index = if (covered[at].floating) groups.guides else 0; + const group_index = if (covered[at].floating) groups.debug else 0; groups.items[group_index].cell_count = std.math.add(u32, groups.items[group_index].cell_count, cellInstanceCount(&surface.cells[at])) catch return error.GpuCapacity; } } @@ -4597,7 +4597,7 @@ fn renderFrame( while (col < surface.cols) : (col += 1) { const at = @as(usize, row) * surface.cols + col; if (covered[at].layer and !covered[at].floating) continue; - const group_index = if (covered[at].floating) groups.guides else 0; + const group_index = if (covered[at].floating) groups.debug else 0; emitSurfaceCell( g, chrome, diff --git a/src/layout.zig b/src/layout.zig index fca4c846..0cfbf04a 100644 --- a/src/layout.zig +++ b/src/layout.zig @@ -180,8 +180,8 @@ pub fn columnDrop(p: *const Pardes, source: usize, x: u16, grab: u16) ColumnDrop } /// Share out the width of columns `left` and `left + 1` so the left one is -/// `left_width` cells, neither below MINW. A border drag and a column grip -/// dropped inside its own place both end here. +/// `left_width` cells, neither below MINW. A column grip dropped inside its +/// own place ends here. pub fn setColumnPairWidth(p: *Pardes, left: usize, left_width: u64) void { const v = p.view(); if (left + 1 >= v.ncol) return; @@ -2099,15 +2099,7 @@ test "repeated non-dyadic column splits preserve every unrelated boundary" { try std.testing.expect(splitColumn(p, 0, 1, false)); p.sync(); - const handle = p.view().col_x[0] + p.view().col_w[0] - 1; - const untouched = weightsOf(p); - p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = handle, .row = TOPBAR_H + 1 } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = handle, .row = TOPBAR_H + 1 } }); - try std.testing.expectEqual(untouched, weightsOf(p)); - - p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = handle, .row = TOPBAR_H + 1 } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = 417, .row = TOPBAR_H + 1 } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = 417, .row = TOPBAR_H + 1 } }); + setColumnPairWidth(p, 0, 418); p.sync(); try std.testing.expectEqual(@as(u16, 418), p.view().rects[0].w); diff --git a/src/mouse.zig b/src/mouse.zig index 783b12b7..2ca984ba 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -1,6 +1,5 @@ //! The mouse: what a pointer is over, the three buttons' presses, drags and -//! releases (acme's chords, border and seam drags, gestures), and the -//! chrome targets a shell asks about. +//! releases (acme's chords, grip and seam drags, gestures). const pardes = @import("pardes.zig"); const tagline = @import("tagline.zig"); const exec = @import("exec.zig"); @@ -19,7 +18,6 @@ const Pane = panes.Pane; const MAX_PANES = pardes.MAX_PANES; const Layer = @import("Layer.zig"); const Jump = @import("Jump.zig"); -const TOPBAR_H = pardes.TOPBAR_H; const BOX_H = pardes.BOX_H; const TAG_TEXT_INSET = pardes.TAG_TEXT_INSET; const Builtin = pardes.Builtin; @@ -29,7 +27,6 @@ const Pardes = pardes.Pardes; pub const Drag = union(enum) { none, - border_v: struct { left_col: usize, cur_x: u16, corner: ?struct { col: usize, idx: usize } = null, cur_y: u16 = 0 }, border_h: struct { col: usize, top_idx: usize, cur_y: u16 }, move: struct { id: usize, cur_x: u16, cur_y: u16 }, /// `grab`: how far into the grip it was pressed, so the column's left @@ -58,7 +55,7 @@ pub const Drag = union(enum) { fn button(drag: Drag) ?Mouse.Button { return switch (drag) { .none => null, - .border_v, .border_h, .move, .column_move => config.select_button, + .border_h, .move, .column_move => config.select_button, .select => |selection| selection.button, }; } @@ -126,38 +123,6 @@ fn seamRowOf(p: *const Pardes, c: usize, k: usize) u16 { return r.y + r.h -| 1; } -pub const ChromeTarget = struct { col: u16, row: u16 }; - -/// The chrome a press at `col`, `row` takes: the tag rows; then, -/// on the cell, a pane's grip, a column's handle or a seam; then a cell -/// away, any of a pane's tag, a handle or a seam. -pub fn chromeTarget(p: *const Pardes, col: u16, row: u16) ?ChromeTarget { - const v = p.view(); - if (row < p.topBarHeight() + layout.columnBarHeight(p)) return .{ .col = col, .row = row }; - for ([_]u16{ 0, 1 }) |slack| { - for (p.panes, 0..) |slot, id| { - const pane = slot orelse continue; - const rect = v.rects[id]; - const tag = p.tagTop(pane, rect); - const edge = if (slack == 0) rect.x + config.GUTTER else rect.x + rect.w; - if (row >= tag and row < tag + pane.tag_rows and col >= rect.x and col < rect.x + rect.w and col < edge) - return .{ .col = col, .row = row }; - } - for (0..p.view().ncol -| 1) |column| { - const handle = v.col_x[column] + v.col_w[column] -| 1; - if (@max(col, handle) - @min(col, handle) == slack) return .{ .col = handle, .row = row }; - } - for (0..p.view().ncol) |column| { - if (col < v.col_x[column] or col >= v.col_x[column] + v.col_w[column]) continue; - for (0..p.view().cols[column].n -| 1) |index| { - const seam = seamRowOf(p, column, index); - if (@max(row, seam) - @min(row, seam) == slack) return .{ .col = col, .row = seam }; - } - } - } - return null; -} - pub fn paneAt(p: *const Pardes, col: u16, row: u16) ?usize { for (p.panes, 0..) |slot, id| { if (slot == null) continue; @@ -781,18 +746,6 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void { return; } } - for (0..p.view().ncol -| 1) |c| { - if (mcol == v.col_x[c] + v.col_w[c] -| 1) { - const corner: @FieldType(@FieldType(Drag, "border_v"), "corner") = if (seamIdxAt(p, c, mrow)) |k| - .{ .col = c, .idx = k } - else if (seamIdxAt(p, c + 1, mrow)) |k| - .{ .col = c + 1, .idx = k } - else - null; - v.drag = .{ .border_v = .{ .left_col = c, .cur_x = mcol, .corner = corner, .cur_y = mrow } }; - return; - } - } // Two panes are resized on the rule between them, never on a // row of text; with no rule, by the grip, as acme moves a // window by its button. @@ -923,12 +876,6 @@ fn seamIdxAt(p: *const Pardes, c: usize, mrow: u16) ?usize { return null; } -fn clampBorderCol(lx: u16, lw: u16, rw: u16, mcol: u16) u16 { - const lo = lx + config.MINW; - const hi = lx +| lw +| rw -| config.MINW; - return if (lo <= hi) std.math.clamp(mcol, lo, hi) else mcol; -} - fn clampBorderRow(ay: u16, ah: u16, bh: u16, mrow: u16) u16 { const lo = ay + BOX_H - 1; const hi = ay +| ah +| bh -| (BOX_H + 1); @@ -938,20 +885,6 @@ fn clampBorderRow(ay: u16, ah: u16, bh: u16, mrow: u16) u16 { pub fn dragUpdate(p: *Pardes, mcol: u16, mrow: u16, body_hit: ?Mouse.BodyHit) void { const v = p.view(); switch (v.drag) { - .border_v => |*d| { - const c = d.left_col; - d.cur_x = if (c + 1 < v.ncol) - clampBorderCol(v.col_x[c], v.col_w[c], v.col_w[c + 1], mcol) - else - mcol; - if (d.corner) |k| if (k.idx + 1 < v.cols[k.col].n) { - const a = v.rects[v.cols[k.col].panes[k.idx]]; - const b = v.rects[v.cols[k.col].panes[k.idx + 1]]; - d.cur_y = clampBorderRow(a.y, a.h, b.h, mrow); - } else { - d.cur_y = mrow; - }; - }, .border_h => |*d| { const cc = d.col; const k = d.top_idx; @@ -1239,18 +1172,6 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { defer v.drag = .none; defer v.chord_hold = false; switch (v.drag) { - .border_v => |d| { - const c = d.left_col; - const old_seam = v.col_x[c] + v.col_w[c] -| 1; - // the handle is the left pane's LAST column (inclusive), so - // the new width includes it — a no-drag click changes nothing - if (c + 1 < v.ncol and d.cur_x != old_seam) - layout.setColumnPairWidth(p, c, (d.cur_x + 1) -| v.col_x[c]); - if (d.corner) |k| { - if (d.cur_y != seamRowOf(p, k.col, k.idx)) - layout.applyRowSplit(p, k.col, k.idx, d.cur_y); - } - }, .border_h => |d| if (d.cur_y != seamRowOf(p, d.col, d.top_idx)) layout.applyRowSplit(p, d.col, d.top_idx, d.cur_y), .column_move => |d| if (layout.columnBySerial(p, d.serial)) |column| switch (layout.columnDrop(p, column, d.cur_x, d.grab)) { @@ -1391,7 +1312,7 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { const test_metrics: pardes.RowMetrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 6, .tagline_h = 12 }; -fn cornerFixture(gpa: std.mem.Allocator) !*Pardes { +fn twoColumns(gpa: std.mem.Allocator) !*Pardes { const p = try Pardes.init(gpa, .{ .cols = 100, .rows = 30, .shells = 3 }); p.update(.{ .resize = .{ .cols = 100, .rows = 30 } }); p.view().active = p.view().cols[1].panes[0]; @@ -1463,7 +1384,7 @@ fn layerCenter(layer: *const Layer, col: u16, comptime tag: bool) [2]f32 { } test "a pane's last row of text is no resize handle; the rule over the next pane is" { - const p = try cornerFixture(std.testing.allocator); + const p = try twoColumns(std.testing.allocator); defer p.deinit(); const seam = seamRowOf(p, 1, 0); const inside = p.view().col_x[1] + p.view().col_w[1] / 2; @@ -1473,8 +1394,22 @@ test "a pane's last row of text is no resize handle; the rule over the next pane try std.testing.expect(nudgeRightSeam(p, 2) == seam + 2); } +test "the line between two columns is no resize handle: a press there is a sweep in the pane" { + const p = try twoColumns(std.testing.allocator); + defer p.deinit(); + const line = p.view().col_x[0] + p.view().col_w[0] - 1; + const row = p.view().rects[p.view().cols[0].panes[0]].y + BOX_H + 1; + const weight = p.view().cols[0].weight; + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = line, .row = row } }); + try std.testing.expect(p.view().drag == .select); + p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = line + 8, .row = row } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = line + 8, .row = row } }); + p.sync(); + try std.testing.expectEqual(weight, p.view().cols[0].weight); +} + test "a pane's grip dragged up or down its own column moves its top, down to the floor of the pane above" { - const p = try cornerFixture(std.testing.allocator); + const p = try twoColumns(std.testing.allocator); defer p.deinit(); const upper = p.view().cols[1].panes[0]; const lower = p.view().cols[1].panes[1]; @@ -1499,26 +1434,6 @@ test "a pane's grip dragged up or down its own column moves its top, down to the try std.testing.expectEqual(to, p.view().rects[lower].y); } -test "a press near chrome takes it: the tag rows, a column's handle or a seam on its cell or a cell away, a pane's tag; nothing in a body" { - const p = try cornerFixture(std.testing.allocator); - defer p.deinit(); - // Column 0's two panes share its rows evenly; column 1's lower one is - // tall, its middle a body row. - const handle = p.view().col_x[0] + p.view().col_w[0] - 1; - const seam = seamRowOf(p, 0, 0); - const mid = p.view().col_x[0] + p.view().col_w[0] / 2; - const top = p.view().rects[p.view().cols[0].panes[0]].y; - const low = p.view().rects[p.view().cols[1].panes[1]]; - const body = low.y + low.h / 2; - try std.testing.expectEqual(ChromeTarget{ .col = 5, .row = 0 }, chromeTarget(p, 5, 0).?); - try std.testing.expectEqual(ChromeTarget{ .col = handle, .row = body }, chromeTarget(p, handle, body).?); - try std.testing.expectEqual(ChromeTarget{ .col = handle, .row = body }, chromeTarget(p, handle + 1, body).?); - try std.testing.expectEqual(ChromeTarget{ .col = mid, .row = seam }, chromeTarget(p, mid, seam).?); - try std.testing.expectEqual(ChromeTarget{ .col = mid, .row = seam }, chromeTarget(p, mid, seam - 1).?); - try std.testing.expectEqual(ChromeTarget{ .col = mid, .row = top }, chromeTarget(p, mid, top).?); - try std.testing.expect(chromeTarget(p, mid, seam - 3) == null); -} - test "plain left click clears explicit modal selection" { const gpa = std.testing.allocator; // Wide enough for the tag on one row: the body starts under it. @@ -1558,144 +1473,6 @@ test "a selection drag and its release leave the selection done" { try std.testing.expectEqual(.done, pane.sel[sel_slot].state); } -test "a corner drag's two axes clamp independently" { - // a 100-wide window split 50/50, and a 30-row column split 15/14 under the - // topbar: the shape windowops.snap drives - const lx: u16 = 0; - const lw: u16 = 50; - const rw: u16 = 50; - const ay: u16 = TOPBAR_H; - const ah: u16 = 15; - const bh: u16 = 14; - const row_lo: u16 = ay + BOX_H - 1; - const row_hi: u16 = ay + ah + bh - (BOX_H + 1); - - // each axis alone, at both walls - try std.testing.expectEqual(@as(u16, config.MINW), clampBorderCol(lx, lw, rw, 0)); - try std.testing.expectEqual(@as(u16, 100 - config.MINW), clampBorderCol(lx, lw, rw, 999)); - try std.testing.expectEqual(row_lo, clampBorderRow(ay, ah, bh, 0)); - try std.testing.expectEqual(row_hi, clampBorderRow(ay, ah, bh, 999)); - - // THE corner property: drag off the right edge while staying mid-height — - // x sits at its wall, y still tracks the mouse row exactly - try std.testing.expectEqual(@as(u16, 100 - config.MINW), clampBorderCol(lx, lw, rw, 999)); - try std.testing.expectEqual(@as(u16, 12), clampBorderRow(ay, ah, bh, 12)); - // and the mirror: pinned at the bottom, x still free - try std.testing.expectEqual(row_hi, clampBorderRow(ay, ah, bh, 999)); - try std.testing.expectEqual(@as(u16, 40), clampBorderCol(lx, lw, rw, 40)); - // both pinned at once is just both walls, not a stuck gesture - try std.testing.expectEqual(@as(u16, config.MINW), clampBorderCol(lx, lw, rw, 0)); - try std.testing.expectEqual(row_hi, clampBorderRow(ay, ah, bh, 999)); - - // degenerate pairs pass through untouched, each on its own terms: a pane - // pair with no room stays draggable even when the column pair has room - try std.testing.expectEqual(@as(u16, 7), clampBorderCol(0, 5, 5, 7)); - try std.testing.expectEqual(@as(u16, 40), clampBorderCol(lx, lw, rw, 40)); - try std.testing.expectEqual(@as(u16, 9), clampBorderRow(TOPBAR_H, 1, 0, 9)); -} - -test "a v-handle press at the RIGHT column's seam drags both boundaries" { - const p = try cornerFixture(std.testing.allocator); - defer p.deinit(); - try std.testing.expectEqual(@as(usize, 2), p.view().cols[1].n); - - const handle = p.view().col_x[0] + p.view().col_w[0] - 1; - const right_seam = nudgeRightSeam(p, 3); - try std.testing.expect(right_seam != seamRowOf(p, 0, 0)); - - const w0 = p.view().cols[0].weight; - const v_left = p.panes[p.view().cols[0].panes[0]].?.vweight; - const v_right = p.panes[p.view().cols[1].panes[0]].?.vweight; - - p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = handle, .row = right_seam } }); - try std.testing.expect(p.view().drag == .border_v); - const corner = p.view().drag.border_v.corner orelse return error.NoCorner; - try std.testing.expectEqual(@as(usize, 1), corner.col); - try std.testing.expectEqual(@as(usize, 0), corner.idx); - - p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = handle + 8, .row = right_seam - 4 } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = handle + 8, .row = right_seam - 4 } }); - p.sync(); - - // both halves committed: the column pair widened, and the RIGHT column's - // pane pair reweighted — while the left column's panes stayed put - try std.testing.expect(p.view().cols[0].weight > w0); - try std.testing.expect(p.panes[p.view().cols[1].panes[0]].?.vweight != v_right); - try std.testing.expectEqual(v_left, p.panes[p.view().cols[0].panes[0]].?.vweight); -} - -test "a tie row still moves the LEFT column's pane pair only" { - const p = try cornerFixture(std.testing.allocator); - defer p.deinit(); - - // put column 1's seam exactly on column 0's, the row the eye reads as one - // line across the whole window - const left_seam = seamRowOf(p, 0, 0); - _ = nudgeRightSeam(p, @as(i32, left_seam) - @as(i32, seamRowOf(p, 1, 0))); - try std.testing.expectEqual(left_seam, seamRowOf(p, 1, 0)); - - const handle = p.view().col_x[0] + p.view().col_w[0] - 1; - const v_left = p.panes[p.view().cols[0].panes[0]].?.vweight; - const v_right = p.panes[p.view().cols[1].panes[0]].?.vweight; - - p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = handle, .row = left_seam } }); - const corner = p.view().drag.border_v.corner orelse return error.NoCorner; - try std.testing.expectEqual(@as(usize, 0), corner.col); - - p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = handle, .row = left_seam - 4 } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = handle, .row = left_seam - 4 } }); - p.sync(); - try std.testing.expect(p.panes[p.view().cols[0].panes[0]].?.vweight != v_left); - try std.testing.expectEqual(v_right, p.panes[p.view().cols[1].panes[0]].?.vweight); -} - -test "a v-handle press at nobody's seam is still a plain edge drag" { - const p = try cornerFixture(std.testing.allocator); - defer p.deinit(); - const right_seam = nudgeRightSeam(p, 3); - const left_seam = seamRowOf(p, 0, 0); - - const handle = p.view().col_x[0] + p.view().col_w[0] - 1; - var row: u16 = TOPBAR_H + 1; - while (row == left_seam or row == right_seam) row += 1; - - const w0 = p.view().cols[0].weight; - const v_left = p.panes[p.view().cols[0].panes[0]].?.vweight; - const v_right = p.panes[p.view().cols[1].panes[0]].?.vweight; - p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = handle, .row = row } }); - try std.testing.expect(p.view().drag == .border_v); - try std.testing.expect(p.view().drag.border_v.corner == null); - p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = handle + 8, .row = row + 5 } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = handle + 8, .row = row + 5 } }); - p.sync(); - // exactly ONE boundary moved - try std.testing.expect(p.view().cols[0].weight > w0); - try std.testing.expectEqual(v_left, p.panes[p.view().cols[0].panes[0]].?.vweight); - try std.testing.expectEqual(v_right, p.panes[p.view().cols[1].panes[0]].?.vweight); -} - -test "a RIGHT-column corner's two axes clamp independently" { - const p = try cornerFixture(std.testing.allocator); - defer p.deinit(); - const right_seam = nudgeRightSeam(p, 3); - const handle = p.view().col_x[0] + p.view().col_w[0] - 1; - p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = handle, .row = right_seam } }); - try std.testing.expectEqual(@as(usize, 1), (p.view().drag.border_v.corner orelse return error.NoCorner).col); - - // off the right edge at mid-height: x parks at its MINW wall, y is the mouse - p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = 999, .row = right_seam } }); - try std.testing.expectEqual(@as(u16, 100 - config.MINW), p.view().drag.border_v.cur_x); - try std.testing.expectEqual(right_seam, p.view().drag.border_v.cur_y); - - // and the mirror: below the bottom at mid-width. y parks, x tracks again - p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = handle, .row = 999 } }); - try std.testing.expectEqual(handle, p.view().drag.border_v.cur_x); - const a = p.view().rects[p.view().cols[1].panes[0]]; - const b = p.view().rects[p.view().cols[1].panes[1]]; - try std.testing.expectEqual(clampBorderRow(a.y, a.h, b.h, 999), p.view().drag.border_v.cur_y); - p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = handle, .row = 999 } }); -} - test "mouse thumb buttons navigate once and clear selection gestures" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 60, .rows = 12 }); defer p.deinit(); diff --git a/src/surface.zig b/src/surface.zig index 9333a75e..ca517d3b 100644 --- a/src/surface.zig +++ b/src/surface.zig @@ -205,8 +205,6 @@ pub const Region = struct { /// A column below the workspace tag, its bar and panes: its left /// edge is the spine a pixel shell rules down it. column, - /// A drag's guide or a seam's hover hint, drawn over the panes. - guide, /// The debug stats box, drawn over the panes. debug, }; @@ -244,15 +242,9 @@ pub const Region = struct { /// it shows, in pixels. Its placements are laid at the whole pixel; a /// pixel frontend draws them the fraction higher. scroll_px: f64 = 0, - /// Cells the column-move rail takes off the right edge while it runs - /// there: layers and pixel shells stop short of them, the grid does not. - clip: u16 = 0, }; -/// Guides a frame can draw: a run of a column-move rail per pane it skips -/// the tags of, and a handful of border and hover dashes. -pub const MAX_GUIDES = MAX_PANES + 4; -pub const MAX_REGIONS = 1 + MAX_PANES * (4 + panes.Pane.Notices.max) + pardes.MAX_COLS * 3 + 1 + MAX_GUIDES + 1; +pub const MAX_REGIONS = 1 + MAX_PANES * (4 + panes.Pane.Notices.max) + pardes.MAX_COLS * 3 + 1 + 1; /// The colours a pixel shell draws its chrome in (rules, rails, grips, the /// tag underlay), resolved by the core each frame, so a frontend attached @@ -470,14 +462,6 @@ pub const Surface = struct { while (xx < x + w) : (xx += 1) s.at(xx, yy).* = .{}; } } - - /// swap ONLY the glyph, keeping the cell's colors — the resize-handle hint - pub fn overlayDash(s: *Surface, x: u16, y: u16, glyph: []const u8) void { - const c = s.at(x, y); - @memcpy(c.text[0..glyph.len], glyph); - c.len = @intCast(glyph.len); - c.default = false; - } }; test "cell visual equality ignores dead grapheme tail bytes" { -- cgit v1.3 From c50226bdad46ed69643079e7c6f3e8ade3a034a1 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 17 Nov 2026 00:05:09 -0300 Subject: colors: a style byte's four high bits are grounds a theme resolves, not a diff's: syntax.ground_add and ground_del (a row's hue), ground_emph (the stronger ground), ground_line (the faint one), the byte as it was; DiffTints moves from File.zig to colors.zig as Grounds (an add and a del Ground: row, emph, line, ink), the same Oklab mixes and marker contrast; the painter has one rule, a row's first byte says its ground (emph the stronger to the pane's edge, line the faint, neither none, its marker in the hue) and a later byte's emph is its cell's, so it stops asking the pane's colour algorithm (`row_tint = algo == .diff`) and works the grounds out once a frame only for a row that names a hue; highlightDiff marks an added or removed line's first byte emph, the strong row a .diff's rows always had; recolorDiffOutput reads the same Grounds; goldens unchanged (diffview, pagercolor, diffstack), render of the 50k-line file 11,723,421 user instructions a frame before and 11,724,208 after (+0.007%, perf stat over ReleaseFast pardes-perf, 210 frames less 10) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- src/File.zig | 97 +++++++++++++--------------------------------------------- src/colors.zig | 37 ++++++++++++++++++++++ src/hunks.zig | 24 +++++++-------- src/syntax.zig | 57 +++++++++++++++++++--------------- 4 files changed, 102 insertions(+), 113 deletions(-) (limited to 'src') diff --git a/src/File.zig b/src/File.zig index 5150f1cd..1988fb89 100644 --- a/src/File.zig +++ b/src/File.zig @@ -1835,59 +1835,6 @@ fn fillBody(dst: ?[]u8, pane: *Pane, f: *State, width: usize, record_wrap: bool) const SynStyle = struct { fg: [3]u8, bold: bool }; -/// How added and removed diff lines are told apart in every theme: a row -/// ground a little way from the page toward green or red (the theme's own -/// ANSI green and red where it has a palette), and the prefix column in -/// that hue, pushed toward the ink until it reads on that ground. The -/// syntax colours are drawn over the ground unchanged. -pub const DiffTints = struct { - added_bg: [3]u8, - removed_bg: [3]u8, - /// The words a changed line changed (hunks.zig), on a stronger ground. - added_emph_bg: [3]u8, - removed_emph_bg: [3]u8, - /// A +Diff line added or removed whole: a faint ground. - added_line_bg: [3]u8, - removed_line_bg: [3]u8, - added_fg: [3]u8, - removed_fg: [3]u8, - - pub fn of(p: *Pardes) DiffTints { - const th = p.theme(); - const page = th.bg orelse th.tag_bg; - const ink = th.fg orelse th.tag_fg; - const green: [3]u8 = if (th.palette) |pal| pal[2] else .{ 0x2e, 0xa0, 0x43 }; - const red: [3]u8 = if (th.palette) |pal| pal[1] else .{ 0xcf, 0x22, 0x2e }; - const added_bg = Colors.mixOklab(page, green, 0.18); - const removed_bg = Colors.mixOklab(page, red, 0.18); - return .{ - .added_bg = added_bg, - .removed_bg = removed_bg, - .added_emph_bg = Colors.mixOklab(page, green, 0.28), - .removed_emph_bg = Colors.mixOklab(page, red, 0.28), - .added_line_bg = Colors.mixOklab(page, green, 0.07), - .removed_line_bg = Colors.mixOklab(page, red, 0.07), - .added_fg = legible(green, ink, added_bg), - .removed_fg = legible(red, ink, removed_bg), - }; - } - - fn legible(hue: [3]u8, ink: [3]u8, ground: [3]u8) [3]u8 { - var fg = hue; - var step: usize = 0; - while (step < 4 and Colors.contrast(fg, ground) < 3) : (step += 1) fg = Colors.mixOklab(fg, ink, 0.4); - return fg; - } - - /// The row ground and prefix ink for a line's style byte, if it is an - /// added or removed line. - pub fn forStyle(t: *const DiffTints, style: u8) ?struct { bg: [3]u8, fg: [3]u8, emph_bg: [3]u8, line_bg: [3]u8 } { - if (style & syntax.diff_added != 0) return .{ .bg = t.added_bg, .fg = t.added_fg, .emph_bg = t.added_emph_bg, .line_bg = t.added_line_bg }; - if (style & syntax.diff_removed != 0) return .{ .bg = t.removed_bg, .fg = t.removed_fg, .emph_bg = t.removed_emph_bg, .line_bg = t.removed_line_bg }; - return null; - } -}; - fn synStyle(p: *Pardes, sy: syntax.Syn) ?SynStyle { return .{ .fg = Colors.synInk(p.theme(), sy) orelse return null, .bold = false }; } @@ -1902,12 +1849,9 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. const prefix_width = gutterWidth(pane); const tz_recolor = tracy.zone(@src(), "synRecolor"); defer tz_recolor.end(); - // A diff's rows, and a +Diff's (hunks.zig): their markers coloured. - // A diff's whole row is tinted; a +Diff tints only the words a - // changed line changed. - const algo = pane.colorAlgo(); - const tints: ?DiffTints = if ((algo == .diff or algo == .locations) and highlights.len > 0) DiffTints.of(p) else null; - const row_tint = algo == .diff; + // A row whose first byte names a hue (syntax.ground_add, _del): its + // grounds, the theme's, worked out once a frame and only for one. + var grounds: ?Colors.Grounds = null; var filtered_storage: terminal.FilteredColors = undefined; const filtered: ?*terminal.FilteredColors = if (pane.tty_filter and spans.len > 0) blk: { filtered_storage = .init(p, null); @@ -1945,19 +1889,20 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. const metadata: ?locations.Row = if (row_index < f.location_rows.len) f.location_rows[row_index] else null; const decoration = Output.decorateRow(f.output, line, metadata); const chrome: ?*const pardes.ChromeTheme = if (decoration.plain()) null else p.bodyChrome(); - // An added or removed line's row, every wrapped row of it, is tinted. - const tint = if (tints) |*t| if (base >= highlight_start and base - highlight_start < highlights.len) - t.forStyle(highlights[base - highlight_start]) - else - null else null; + // The row's first byte: its hue and its ground, on every wrapped + // row of it (syntax.ground_add). + const lead: u8 = if (base >= highlight_start and base - highlight_start < highlights.len) highlights[base - highlight_start] else 0; + const tint: ?Colors.Grounds.Ground = if (lead & (syntax.ground_add | syntax.ground_del) == 0) null else (grounds orelse ground: { + grounds = .of(p.theme()); + break :ground grounds.?; + }).forStyle(lead); if (tint) |t| if (prefix_width < tw) { - // A +Diff line added or removed whole: faintly (hunks.zig). - const whole = highlights[base - highlight_start] & syntax.diff_whole != 0; - if (row_tint or whole) s.tint(tx + @as(u16, @intCast(prefix_width)), body_y + vr, tw -| @as(u16, @intCast(prefix_width)), if (row_tint) t.bg else t.line_bg, null); + const ground: ?[3]u8 = if (lead & syntax.ground_emph != 0) t.row else if (lead & syntax.ground_line != 0) t.line else null; + if (ground) |g| s.tint(tx + @as(u16, @intCast(prefix_width)), body_y + vr, tw -| @as(u16, @intCast(prefix_width)), g, null); }; - // A +Pager's own colours (pager.zig) on every row but one the diff - // look tints: an added or removed line is drawn as pardes draws a - // diff, and git's red and green on it would only fight the tint. + // A +Pager's own colours (pager.zig) on every row but one in a hue: + // an added or removed line is drawn as pardes draws a diff, and + // git's red and green on it would only fight the tint. var span_at = if (tint != null) spans.len else std.sort.partitionPoint(pardes.pager.Span, spans, base + hs, struct { fn before(at: usize, span: pardes.pager.Span) bool { return span.end <= at; @@ -1991,7 +1936,7 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. const hidx = idx - highlight_start; if (hidx < highlights.len) { if (if (tint != null and hs + c == 0) - SynStyle{ .fg = tint.?.fg, .bold = true } + SynStyle{ .fg = tint.?.ink, .bold = true } else synStyle(p, @fromBackingInt(@intCast(highlights[hidx] & syntax.syn_bits)))) |ss| { @@ -2003,10 +1948,10 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. cell.style.bold = ss.bold; } } - if (tint) |t| if (highlights[hidx] & syntax.diff_emph != 0) { + if (tint) |t| if (highlights[hidx] & syntax.ground_emph != 0 and hs + c > 0) { var fill: usize = 0; while (fill < cells and prefix_width + screen_c + fill < tw) : (fill += 1) - s.at(tx + @as(u16, @intCast(prefix_width + screen_c + fill)), body_y + vr).style.bg = .{ .rgb = t.emph_bg }; + s.at(tx + @as(u16, @intCast(prefix_width + screen_c + fill)), body_y + vr).style.bg = .{ .rgb = t.emph }; }; } } @@ -2175,7 +2120,7 @@ pub fn recolorDiffOutput(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, t } if (lo > hi) return; const styles = syntax.highlightDiffRows(arena, flat, lo, hi, true) catch return; - const tints = DiffTints.of(p); + const tints: Colors.Grounds = .of(p.theme()); const ink = p.theme().fg orelse p.theme().tag_fg; const body_y = p.bodyTop(pane, r); shown = std.mem.splitScalar(u8, body, '\n'); @@ -2184,7 +2129,7 @@ pub fn recolorDiffOutput(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, t const view = maybe orelse continue; const base = @intFromPtr(rows[view.row].ptr) - flat_start - lo; const tint = if (base < styles.len) tints.forStyle(styles[base]) else null; - if (tint) |t| s.tint(tx, body_y + @as(u16, @intCast(vr)), tw, t.bg, null); + if (tint) |t| s.tint(tx, body_y + @as(u16, @intCast(vr)), tw, t.row, null); var c: usize = 0; var screen_c: usize = 0; while (c < line.len and screen_c < tw) { @@ -2196,7 +2141,7 @@ pub fn recolorDiffOutput(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, t // On an added or removed line, what the program coloured red or // green is the tint's to say now: its code takes the page's ink. const paint: ?SynStyle = if (tint != null and prefix) - .{ .fg = tint.?.fg, .bold = true } + .{ .fg = tint.?.ink, .bold = true } else if (synStyle(p, @fromBackingInt(@intCast(style & syntax.syn_bits)))) |ss| ss else if (tint != null) diff --git a/src/colors.zig b/src/colors.zig index 1713ba24..e2e00ea8 100644 --- a/src/colors.zig +++ b/src/colors.zig @@ -322,6 +322,43 @@ pub fn synInk(th: *const Theme, sy: @import("syntax.zig").Syn) ?[3]u8 { }; } +/// The grounds a style byte's high bits name (syntax.ground_add and the +/// rest) in a theme: a row added or removed on a ground a little way from +/// the page toward the theme's green or red (its own ANSI ones where it has +/// a palette), a stronger one, a faint one, and the row's marker in that +/// hue, pushed toward the ink until it reads on the row's ground. Syntax +/// colours are drawn over a ground unchanged. +pub const Grounds = struct { + add: Ground, + del: Ground, + + pub const Ground = struct { row: [3]u8, emph: [3]u8, line: [3]u8, ink: [3]u8 }; + + pub fn of(th: *const Theme) Grounds { + const page = th.bg orelse th.tag_bg; + const ink = th.fg orelse th.tag_fg; + const green: [3]u8 = if (th.palette) |pal| pal[2] else .{ 0x2e, 0xa0, 0x43 }; + const red: [3]u8 = if (th.palette) |pal| pal[1] else .{ 0xcf, 0x22, 0x2e }; + return .{ .add = ground(page, ink, green), .del = ground(page, ink, red) }; + } + + fn ground(page: [3]u8, ink: [3]u8, hue: [3]u8) Ground { + const row = mixOklab(page, hue, 0.18); + var marker = hue; + var step: usize = 0; + while (step < 4 and contrast(marker, row) < 3) : (step += 1) marker = mixOklab(marker, ink, 0.4); + return .{ .row = row, .emph = mixOklab(page, hue, 0.28), .line = mixOklab(page, hue, 0.07), .ink = marker }; + } + + /// The ground of a byte's hue, if it has one. + pub fn forStyle(g: *const Grounds, style: u8) ?Ground { + const syntax = @import("syntax.zig"); + if (style & syntax.ground_add != 0) return g.add; + if (style & syntax.ground_del != 0) return g.del; + return null; + } +}; + /// One family, its twelve backgrounds a theme each (`curated`). const seoul256 = @import("themes/seoul256.zig"); diff --git a/src/hunks.zig b/src/hunks.zig index 8f4b4233..19246392 100644 --- a/src/hunks.zig +++ b/src/hunks.zig @@ -331,10 +331,10 @@ fn flush(out: *Out, hunk: *Hunk, memo: *SourceMemo, dir: []const u8) !void { // has it: the marker coloured, the line as its file's. for (lines) |line| { const flag: u8 = switch (line.kind) { - .added => syntax.diff_added, - .removed => syntax.diff_removed, + .added => syntax.ground_add, + .removed => syntax.ground_del, else => 0, - } | @as(u8, if (line.kind != .context and !line.paired) syntax.diff_whole else 0); + } | @as(u8, if (line.kind != .context and !line.paired) syntax.ground_line else 0); const text = try std.fmt.allocPrint(arena, "{c}{s}", .{ @as(u8, switch (line.kind) { .added => '+', .removed => '-', @@ -389,10 +389,10 @@ fn inferEdits(arena: std.mem.Allocator, minus: []HunkLine, plus: []HunkLine) !vo const marks = annotate(pair, &alignment, m.code, plus[j].code) catch continue; if (marks.distance > max_line_distance) continue; for (marks.minus) |r| for (m.styles[r[0]..r[1]]) |*b| { - b.* |= syntax.diff_emph; + b.* |= syntax.ground_emph; }; for (marks.plus) |r| for (plus[j].styles[r[0]..r[1]]) |*b| { - b.* |= syntax.diff_emph; + b.* |= syntax.ground_emph; }; m.paired = true; plus[j].paired = true; @@ -583,7 +583,7 @@ const testing = std.testing; fn emphasised(line: HunkLine) ![]const u8 { var out: std.ArrayList(u8) = .empty; - for (line.code, line.styles) |c, s| try out.append(testing.allocator, if (s & syntax.diff_emph != 0) c else '.'); + for (line.code, line.styles) |c, s| try out.append(testing.allocator, if (s & syntax.ground_emph != 0) c else '.'); return out.toOwnedSlice(testing.allocator); } @@ -653,13 +653,13 @@ test "a diff stacks to a label a hunk and its lines, markers gone, tinted and st try testing.expectEqual(@as(usize, "nowhere/x.txt:2".len), result.rows[0].location_end); try testing.expect(result.rows[1].declaration); const removed = result.rows[3]; - try testing.expect(removed.colors[0] & syntax.diff_removed != 0); + try testing.expect(removed.colors[0] & syntax.ground_del != 0); // Paired with the line it changed: no whole-line tint. - try testing.expect(removed.colors[0] & syntax.diff_whole == 0); - try testing.expect(removed.colors[1] & syntax.diff_emph != 0); - try testing.expect(removed.colors[5] & syntax.diff_emph == 0); - try testing.expect(result.rows[4].colors[0] & syntax.diff_added != 0); - try testing.expect(result.rows[2].colors[0] & (syntax.diff_added | syntax.diff_removed) == 0); + try testing.expect(removed.colors[0] & syntax.ground_line == 0); + try testing.expect(removed.colors[1] & syntax.ground_emph != 0); + try testing.expect(removed.colors[5] & syntax.ground_emph == 0); + try testing.expect(result.rows[4].colors[0] & syntax.ground_add != 0); + try testing.expect(result.rows[2].colors[0] & (syntax.ground_add | syntax.ground_del) == 0); } test "a hunk the file has moved since is found where it went, inside its declaration" { diff --git a/src/syntax.zig b/src/syntax.zig index 8533aaa9..70399bf7 100644 --- a/src/syntax.zig +++ b/src/syntax.zig @@ -933,16 +933,17 @@ fn childOfKind(node: ts.Node, kind: []const u8) ?ts.Node { return null; } -/// A diff line's style byte carries whether the line was added or removed -/// over its syntax style (the low bits), so the painter can tint its row -/// and mark its prefix; Diff marks the words a changed line changed -/// (hunks.zig), drawn on a stronger tint. -pub const diff_added: u8 = 0x80; -pub const diff_removed: u8 = 0x40; -pub const diff_emph: u8 = 0x20; -/// A +Diff line added or removed whole, paired with no line it changed: -/// its row takes a faint tint, on its marker's byte. -pub const diff_whole: u8 = 0x10; +/// A style byte: a Syn in its low bits (syn_bits), and over them the +/// grounds a theme resolves (colors.Grounds): `ground_add` or `ground_del`, +/// a row added or removed (its hue); `ground_emph`, the stronger ground; +/// `ground_line`, the faint one. A row's first byte says its row's ground: +/// emph the stronger to the pane's edge, line the faint one, neither none +/// (only its marker in the hue). Any later byte's emph is its own cell's +/// ground: the words a changed line changed (hunks.zig). +pub const ground_add: u8 = 0x80; +pub const ground_del: u8 = 0x40; +pub const ground_emph: u8 = 0x20; +pub const ground_line: u8 = 0x10; pub const syn_bits: u8 = 0x0f; /// A file section's hunks are parsed together, each side as one text, in @@ -967,7 +968,8 @@ var diff_clock: u64 = 0; /// the file its section names. A hunk's old side (context and removed /// lines) and new side (context and added lines) are each parsed whole, so /// a string or comment that spans lines colours as it does in the file. -/// Added and removed lines carry `diff_added`/`diff_removed`. A file in no +/// Added and removed lines carry `ground_add`/`ground_del`, the first byte +/// the strong row ground too (`ground_emph`). A file in no /// language pardes knows keeps the plain colours: added lines as strings, /// removed ones as numbers. pub fn highlightDiff(gpa: std.mem.Allocator, content: []const u8, start_raw: usize, end_raw: usize) ![]u8 { @@ -1082,13 +1084,14 @@ fn paintDiffPiece(gpa: std.mem.Allocator, window: DiffWindow, bytes: []const u8, for (kinds) |kind| { const line = lines.next() orelse break; const style: u8 = switch (kind) { - .added => @backingInt(Syn.string) | diff_added, - .removed => @backingInt(Syn.number) | diff_removed, + .added => @backingInt(Syn.string) | ground_add, + .removed => @backingInt(Syn.number) | ground_del, .no_newline => @backingInt(Syn.comment), .hunk => @backingInt(Syn.keyword), else => 0, }; if (style != 0) window.fill(at + offset, line.len, style); + if (style & (ground_add | ground_del) != 0 and line.len > 0) window.fill(at + offset, 1, style | ground_emph); offset += line.len + 1; } } @@ -1170,13 +1173,14 @@ fn paintHunk(gpa: std.mem.Allocator, out: []u8, bytes: []const u8, kinds: []cons if (kind == .context or kind == .removed) old_at += code_len + 1; if (kind == .context or kind == .added) new_at += code_len + 1; const flag: u8 = switch (kind) { - .added => diff_added, - .removed => diff_removed, + .added => ground_add, + .removed => ground_del, else => 0, }; if (flag != 0) for (out[offset..][0..line.len]) |*b| { b.* |= flag; }; + if (flag != 0 and line.len > 0) out[offset] |= ground_emph; } } @@ -1577,9 +1581,12 @@ test "syntax highlightDiff colors unified diff lines by prefix" { // A file in no known language: each line in one colour, and tinted. try std.testing.expectEqual(Syn.number, diffSynAt(styles, diff_text, "-old line", 0)); try std.testing.expectEqual(Syn.string, diffSynAt(styles, diff_text, "+new line", 0)); - try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "-old line").?] & diff_removed != 0); - try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "+new line").? + 4] & diff_added != 0); - try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, " context").?] & (diff_added | diff_removed) == 0); + try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "-old line").?] & ground_del != 0); + try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "+new line").? + 4] & ground_add != 0); + try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, " context").?] & (ground_add | ground_del) == 0); + // The row's ground on its first byte: the strong one, its other bytes none. + try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "-old line").?] & ground_emph != 0); + try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "+new line").? + 4] & (ground_emph | ground_line) == 0); } test "syntax a Zig hunk is coloured as Zig, each side parsed whole" { @@ -1611,9 +1618,9 @@ test "syntax a Zig hunk is coloured as Zig, each side parsed whole" { try std.testing.expectEqual(Syn.string, diffSynAt(styles, diff_text, "new words defer", 10)); // The prefix is no code: it carries the tint alone. const added = std.mem.indexOf(u8, diff_text, "+ side").?; - try std.testing.expectEqual(diff_added, styles[added]); - try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "42").?] & diff_added != 0); - try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "7,").?] & diff_removed != 0); + try std.testing.expectEqual(ground_add | ground_emph, styles[added]); + try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "42").?] & ground_add != 0); + try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "7,").?] & ground_del != 0); try std.testing.expectEqual(Syn.comment, diffSynAt(styles, diff_text, "index 111", 0)); // A window in the middle is coloured as the whole is. @@ -1660,7 +1667,7 @@ test "syntax a deleted file's lines are coloured in its language" { defer std.testing.allocator.free(styles); try std.testing.expectEqual(Syn.keyword, diffSynAt(styles, diff_text, "enum", 0)); try std.testing.expectEqual(Syn.comment, diffSynAt(styles, diff_text, "// the end", 3)); - try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "enum").?] & diff_removed != 0); + try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "enum").?] & ground_del != 0); try std.testing.expectEqual(Syn.comment, diffSynAt(styles, diff_text, "deleted file", 0)); } @@ -1709,9 +1716,9 @@ test "syntax git diff output in a command pane is told and coloured by its rows" try std.testing.expectEqual(Syn.keyword, diffSynAt(styles, text, "fn main", 0)); try std.testing.expectEqual(Syn.number, diffSynAt(styles, text, "42", 0)); // The wrapped row stays an added line, and inside the comment. - try std.testing.expect(styles[std.mem.indexOf(u8, text, "wrapped rest").?] & diff_added != 0); + try std.testing.expect(styles[std.mem.indexOf(u8, text, "wrapped rest").?] & ground_add != 0); try std.testing.expectEqual(Syn.comment, diffSynAt(styles, text, "wrapped rest", 0)); - try std.testing.expect(styles[std.mem.indexOf(u8, text, "return").?] & diff_removed != 0); + try std.testing.expect(styles[std.mem.indexOf(u8, text, "return").?] & ground_del != 0); } test "syntax a section's small hunks share one parse" { @@ -1733,7 +1740,7 @@ test "syntax a section's small hunks share one parse" { try std.testing.expectEqual(@as(usize, 2), cached); // x.zig's three hunks, and y.zig's try std.testing.expectEqual(Syn.keyword, diffSynAt(styles, diff_text, "@@ -10", 0)); try std.testing.expectEqual(Syn.number, diffSynAt(styles, diff_text, "2;\n@@ -20", 0)); - try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "@@ -10").?] & (diff_added | diff_removed) == 0); + try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "@@ -10").?] & (ground_add | ground_del) == 0); } test "syntax a hunk painted once is kept, and a long one is parsed in pieces" { -- cgit v1.3 From 5caef6d571f51e98eab3a48c063678ad35e09cce Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 17 Nov 2026 00:25:19 -0300 Subject: hunks: format stacks for a narrow Ctx, not a *Pardes: its two allocators, `source(dir, path)` (a file as a look from dir finds it), `declarations(path, bytes)` and the one setting, tslocations; Output.openDiff gives the editor's, its reads the same taped sites as before (locations.sourceText: an open pane's text, else fs.read) and its declarations the locations cache's, so a replica still replays the authority's bytes; displayWidth from File.zig itself; the four format tests read the disk through a Ctx of their own and stop booting a whole Pardes (the look and refill tests still drive the editor); goldens unchanged Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- src/Output.zig | 29 ++++++++++- src/hunks.zig | 151 ++++++++++++++++++++++++++++++++++++++------------------- 2 files changed, 128 insertions(+), 52 deletions(-) (limited to 'src') diff --git a/src/Output.zig b/src/Output.zig index 0c6fdfc2..d4be640c 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -490,8 +490,33 @@ pub fn fillRows(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: []con /// NoHunks when there is none in it. pub fn openDiff(p: *Pardes, id: usize, path: []const u8, content: []const u8) !usize { const dir = std.Io.Dir.path.dirname(path) orelse p.sessionDir(); - const root = hunks.sourceRoot(p, dir, content); - const result = try hunks.format(p, root, content); + // Each file read is a site of the step's tape (fs.zig): a replica + // replays the authority's bytes and reads no disk of its own. + const Read = struct { + fn source(ctx: *const hunks.Ctx, from: []const u8, name: []const u8) ?hunks.Source { + const pp: *Pardes = @ptrCast(@alignCast(ctx.host)); + const text = locations.sourceText(pp, ctx.arena, from, name) orelse return null; + return .{ .path = text.path, .bytes = text.bytes }; + } + fn declarations(ctx: *const hunks.Ctx, name: []const u8, bytes: []const u8) error{OutOfMemory}![]const @import("syntax.zig").ContextDeclaration { + const pp: *Pardes = @ptrCast(@alignCast(ctx.host)); + var hit = pp.locations_cache.get(pp.tree_sitter_gpa, name, bytes, true, false) catch + locations.Cache.Hit{ .analysis = @import("syntax.zig").analyzeSource(ctx.arena, name, bytes, true, false) catch .{} }; + defer hit.deinit(pp.tree_sitter_gpa); + // The cache's may go at its next use: kept for the call. + return ctx.arena.dupe(@import("syntax.zig").ContextDeclaration, hit.analysis.declarations); + } + }; + const ctx: hunks.Ctx = .{ + .gpa = p.gpa, + .arena = p.scratch.allocator(), + .source = Read.source, + .declarations = Read.declarations, + .host = p, + .tslocations = p.locations_config.tslocations, + }; + const root = hunks.sourceRoot(&ctx, dir, content); + const result = try hunks.format(&ctx, root, content); errdefer { p.gpa.free(result.content); locations.freeRows(p.gpa, result.rows); diff --git a/src/hunks.zig b/src/hunks.zig index 19246392..28fffa38 100644 --- a/src/hunks.zig +++ b/src/hunks.zig @@ -6,21 +6,43 @@ //! a tinted ground as delta emphasises them (its edits.rs and align.rs, here as `inferEdits` //! and `Alignment`). const std = @import("std"); -const pardes = @import("pardes.zig"); const diff = @import("diff.zig"); const syntax = @import("syntax.zig"); const locations = @import("locations.zig"); -const Pardes = pardes.Pardes; const Row = locations.Row; +/// What `format` takes of the editor it stacks for: its allocators, the +/// files a diff names read as the editor reads them (in pardes an open +/// pane's text, else the disk's, each read a site of the step's tape: +/// Output.openDiff), their declarations, and one setting. +pub const Ctx = struct { + /// The text and rows made, the caller's. + gpa: std.mem.Allocator, + /// All else, the call's. + arena: std.mem.Allocator, + /// `path` as a look from `dir` finds it, its text the arena's (or the + /// editor's, good for the call); null when it is not there. + source: *const fn (ctx: *const Ctx, dir: []const u8, path: []const u8) ?Source, + /// The declarations of `bytes`, the file at `path`, outermost first + /// (syntax.analyzeSource's), the arena's. + declarations: *const fn (ctx: *const Ctx, path: []const u8, bytes: []const u8) error{OutOfMemory}![]const syntax.ContextDeclaration, + /// The two above's own. + host: *anyopaque, + /// A declaration above a hunk gets its `path:line` row too + /// (LocationsConfig's tslocations). + tslocations: bool, +}; + +/// A file's text, and its path as `dir` and the path named resolve. +pub const Source = struct { path: []const u8, bytes: []const u8 }; + /// The rows `content`, a diff, stacks to, for a pane in `dir`, with each -/// row's metadata (Output.fillRows). Text and rows are `p.gpa`'s; all else -/// is the step's scratch. -pub fn format(p: *Pardes, dir: []const u8, content: []const u8) !locations.Result { - const arena = p.scratch.allocator(); +/// row's metadata (Output.fillRows). Text and rows are `ctx.gpa`'s. +pub fn format(ctx: *const Ctx, dir: []const u8, content: []const u8) !locations.Result { + const arena = ctx.arena; const styles = try syntax.highlightDiff(arena, content, 0, content.len); - var out: Out = .{ .p = p, .text = .init(p.gpa) }; + var out: Out = .{ .gpa = ctx.gpa, .text = .init(ctx.gpa) }; errdefer out.deinit(); var walk: diff.Walk = .{}; var hunk: Hunk = .{}; @@ -46,7 +68,7 @@ pub fn format(p: *Pardes, dir: []const u8, content: []const u8) !locations.Resul // A `\ No newline` belongs to the line above, as delta shows it. .no_newline => {}, else => { - try flush(&out, &hunk, &source, dir); + try flush(ctx, &out, &hunk, &source, dir); switch (got.kind) { .hunk => hunk = .{ .path = walk.path(), @@ -69,9 +91,9 @@ pub fn format(p: *Pardes, dir: []const u8, content: []const u8) !locations.Resul } at = nl + 1; } - try flush(&out, &hunk, &source, dir); - const rows = try out.rows.toOwnedSlice(p.gpa); - errdefer locations.freeRows(p.gpa, rows); + try flush(ctx, &out, &hunk, &source, dir); + const rows = try out.rows.toOwnedSlice(ctx.gpa); + errdefer locations.freeRows(ctx.gpa, rows); return .{ .content = try out.text.toOwnedSlice(), .rows = rows, .anchor = null }; } @@ -105,13 +127,13 @@ fn gitContext(line: []const u8) []const u8 { } const Out = struct { - p: *Pardes, + gpa: std.mem.Allocator, text: std.Io.Writer.Allocating, rows: std.ArrayList(Row) = .empty, fn deinit(out: *Out) void { out.text.deinit(); - locations.freeRowList(out.p.gpa, &out.rows); + locations.freeRowList(out.gpa, &out.rows); } const Meta = struct { @@ -127,7 +149,7 @@ const Out = struct { fn row(out: *Out, text: []const u8, path: []const u8, meta: Meta) !void { try out.text.writer.writeAll(text); try out.text.writer.writeByte('\n'); - try locations.appendRow(out.p.gpa, &out.rows, .{ + try locations.appendRow(out.gpa, &out.rows, .{ .kind = meta.kind, .declaration = meta.declaration, .path = @constCast(path), @@ -153,7 +175,7 @@ const SourceMemo = struct { /// Where a +Diff of `content`, a diff in `dir`, stands: the directory its /// first file is found from (`dir` or one above it, as `findSource` looks), /// so its rows name their files as the diff does; `dir` when none is found. -pub fn sourceRoot(p: *Pardes, dir: []const u8, content: []const u8) []const u8 { +pub fn sourceRoot(ctx: *const Ctx, dir: []const u8, content: []const u8) []const u8 { var walk: diff.Walk = .{}; var lines = std.mem.splitScalar(u8, content, '\n'); const path = while (lines.next()) |line| { @@ -161,31 +183,27 @@ pub fn sourceRoot(p: *Pardes, dir: []const u8, content: []const u8) []const u8 { } else return dir; var base: []const u8 = dir; for (0..8) |_| { - if (locations.sourceText(p, p.scratch.allocator(), base, path) != null) return base; + if (ctx.source(ctx, base, path) != null) return base; base = std.Io.Dir.path.dirname(base) orelse return dir; } return dir; } -fn findSource(p: *Pardes, memo: *SourceMemo, dir: []const u8, path: []const u8) !void { +fn findSource(ctx: *const Ctx, memo: *SourceMemo, dir: []const u8, path: []const u8) !void { if (std.mem.eql(u8, memo.path, path)) return; - const arena = p.scratch.allocator(); + const arena = ctx.arena; memo.* = .{ .path = path }; // ponytail: eight directories up; a repository deeper than that under // its patch is looked for from the patch's own directory only. var base: []const u8 = dir; for (0..8) |_| { - if (locations.sourceText(p, arena, base, path)) |text| { + if (ctx.source(ctx, base, path)) |text| { memo.shown = if (base.ptr == dir.ptr) path else try std.Io.Dir.path.relativePosix(arena, "/", dir, text.path); var lines: std.ArrayList([]const u8) = .empty; var split = std.mem.splitScalar(u8, text.bytes, '\n'); while (split.next()) |line| try lines.append(arena, std.mem.trimEnd(u8, line, "\r")); memo.lines = lines.items; - var hit = p.locations_cache.get(p.tree_sitter_gpa, text.path, text.bytes, true, false) catch - locations.Cache.Hit{ .analysis = syntax.analyzeSource(arena, text.path, text.bytes, true, false) catch .{} }; - defer hit.deinit(p.tree_sitter_gpa); - // The cache's may go at its next use: kept for the section. - memo.declarations = try arena.dupe(syntax.ContextDeclaration, hit.analysis.declarations); + memo.declarations = try ctx.declarations(ctx, text.path, text.bytes); return; } base = std.Io.Dir.path.dirname(base) orelse return; @@ -251,12 +269,11 @@ fn heldAt(memo: *const SourceMemo, hunk: *const Hunk, comptime side: Side, start return .{ .held = held, .of = @max(of, 1) }; } -fn flush(out: *Out, hunk: *Hunk, memo: *SourceMemo, dir: []const u8) !void { +fn flush(ctx: *const Ctx, out: *Out, hunk: *Hunk, memo: *SourceMemo, dir: []const u8) !void { defer hunk.* = .{}; if (hunk.path.len == 0 or hunk.lines.items.len == 0) return; - const p = out.p; - const arena = p.scratch.allocator(); - try findSource(p, memo, dir, hunk.path); + const arena = ctx.arena; + try findSource(ctx, memo, dir, hunk.path); const disk = sideOnDisk(memo, hunk); const side = disk.side; // A line number of the hunk's, where the file has it now. @@ -287,7 +304,7 @@ fn flush(out: *Out, hunk: *Hunk, memo: *SourceMemo, dir: []const u8) !void { var row = declaration.start_line; while (row <= declaration.header_end_line and row < start_row) : (row += 1) { const at: @FieldType(Row, "at") = .{ .line = row + 1 }; - if (row == declaration.start_line and p.locations_config.tslocations) { + if (row == declaration.start_line and ctx.tslocations) { const label = try std.fmt.allocPrint(arena, "{s}:{d}", .{ shown, row + 1 }); try out.row(label, shown, .{ .kind = .context, .declaration = true, .at = at, .location_end = label.len, .code_start = label.len }); } @@ -574,13 +591,40 @@ fn annotate(arena: std.mem.Allocator, a: *const Alignment, minus_line: []const u } fn trimmedWidth(section: []const u8) usize { - return pardes.panes.File.displayWidth(std.mem.trim(u8, section, " \t")); + return @import("File.zig").displayWidth(std.mem.trim(u8, section, " \t")); } // ---- tests ---- const testing = std.testing; +/// A Ctx over the disk, as the editor's is without panes or a cache. +const TestCtx = struct { + arena_state: std.heap.ArenaAllocator, + ctx: Ctx, + + fn init(t: *TestCtx) void { + t.arena_state = .init(testing.allocator); + t.ctx = .{ .gpa = testing.allocator, .arena = t.arena_state.allocator(), .source = source, .declarations = declarations, .host = t, .tslocations = true }; + syntax.start(testing.allocator); + } + + fn deinit(t: *TestCtx) void { + syntax.stop(); + t.arena_state.deinit(); + } + + fn source(ctx: *const Ctx, dir: []const u8, path: []const u8) ?Source { + const full = std.Io.Dir.path.resolvePosix(ctx.arena, &.{ dir, path }) catch return null; + const bytes = std.Io.Dir.cwd().readFileAlloc(testing.io, full, ctx.arena, .limited(1 << 20)) catch return null; + return .{ .path = full, .bytes = bytes }; + } + + fn declarations(ctx: *const Ctx, path: []const u8, bytes: []const u8) error{OutOfMemory}![]const syntax.ContextDeclaration { + return (syntax.analyzeSource(ctx.arena, path, bytes, true, false) catch return &.{}).declarations; + } +}; + fn emphasised(line: HunkLine) ![]const u8 { var out: std.ArrayList(u8) = .empty; for (line.code, line.styles) |c, s| try out.append(testing.allocator, if (s & syntax.ground_emph != 0) c else '.'); @@ -631,8 +675,9 @@ test "delta's alignment: kitten to sitting, as align.rs has it" { } test "a diff stacks to a label a hunk and its lines, markers gone, tinted and stepped" { - const p = try Pardes.init(testing.allocator, .{ .tty_only = true }); - defer p.deinit(); + var t: TestCtx = undefined; + t.init(); + defer t.deinit(); const patch = \\diff --git a/nowhere/x.txt b/nowhere/x.txt \\--- a/nowhere/x.txt @@ -644,9 +689,9 @@ test "a diff stacks to a label a hunk and its lines, markers gone, tinted and st \\ tail \\ ; - const result = try format(p, "/pardes-surely-missing-dir", patch); - defer p.gpa.free(result.content); - defer locations.freeRows(p.gpa, result.rows); + const result = try format(&t.ctx, "/pardes-surely-missing-dir", patch); + defer testing.allocator.free(result.content); + defer locations.freeRows(testing.allocator, result.rows); try testing.expectEqualStrings("nowhere/x.txt:2\n section one\n keep\n-old value\n+new value\n tail\n", result.content); try testing.expectEqual(@as(usize, 6), result.rows.len); try testing.expectEqual(.match, result.rows[0].kind); @@ -664,8 +709,9 @@ test "a diff stacks to a label a hunk and its lines, markers gone, tinted and st test "a hunk the file has moved since is found where it went, inside its declaration" { if (!syntax.supportsPath("a.zig")) return error.SkipZigTest; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true }); - defer p.deinit(); + var t: TestCtx = undefined; + t.init(); + defer t.deinit(); var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); // Two lines more above it than the patch knows of. @@ -682,16 +728,17 @@ test "a hunk the file has moved since is found where it went, inside its declara \\ b(); \\ ; - const result = try format(p, dir, patch); - defer p.gpa.free(result.content); - defer locations.freeRows(p.gpa, result.rows); + const result = try format(&t.ctx, dir, patch); + defer testing.allocator.free(result.content); + defer locations.freeRows(testing.allocator, result.rows); try testing.expect(std.mem.indexOf(u8, result.content, "a.zig:3\n const S = struct {\na.zig:5 *\n") != null); try testing.expect(std.mem.indexOf(u8, result.content, "git's guess") == null); } test "a mailed patch keeps its headers, message and diffstat above its hunks" { - const p = try Pardes.init(testing.allocator, .{ .tty_only = true }); - defer p.deinit(); + var t: TestCtx = undefined; + t.init(); + defer t.deinit(); const patch = \\From 0123 Mon Sep 17 00:00:00 2001 \\Subject: [PATCH] change x @@ -709,12 +756,15 @@ test "a mailed patch keeps its headers, message and diffstat above its hunks" { \\+b \\ ; - const result = try format(p, "/pardes-surely-missing-dir", patch); - defer p.gpa.free(result.content); - defer locations.freeRows(p.gpa, result.rows); + const result = try format(&t.ctx, "/pardes-surely-missing-dir", patch); + defer testing.allocator.free(result.content); + defer locations.freeRows(testing.allocator, result.rows); try testing.expectEqualStrings("From 0123 Mon Sep 17 00:00:00 2001\nSubject: [PATCH] change x\n\nWhy it changed.\n---\n x.txt | 2 +-\n\nx.txt:1\n-a\n+b\n", result.content); } +const pardes = @import("pardes.zig"); +const Pardes = pardes.Pardes; + test "a .patch looked at opens its +Diff, and Diff goes to the text and back" { const p = try Pardes.init(testing.allocator, .{ .tty_only = true }); defer p.deinit(); @@ -755,8 +805,9 @@ test "a .patch looked at opens its +Diff, and Diff goes to the text and back" { test "a hunk edited since, beside siblings with its signature's tail, is found in its own function" { if (!syntax.supportsPath("a.rs")) return error.SkipZigTest; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true }); - defer p.deinit(); + var t: TestCtx = undefined; + t.init(); + defer t.deinit(); var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); // Three functions ending in one signature's tail; the patch is for the @@ -799,9 +850,9 @@ test "a hunk edited since, beside siblings with its signature's tail, is found i \\ c \\ ; - const result = try format(p, dir, patch); - defer p.gpa.free(result.content); - defer locations.freeRows(p.gpa, result.rows); + const result = try format(&t.ctx, dir, patch); + defer testing.allocator.free(result.content); + defer locations.freeRows(testing.allocator, result.rows); try testing.expect(std.mem.indexOf(u8, result.content, "a.rs:12\n fn three(\na.rs:15 *\n") != null); } -- cgit v1.3 From 383b60b79146937e12c82abaaca2ce213d210b7f Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 16 Nov 2026 22:43:18 -0300 Subject: syntax: the highlight queries are filtered by the build, not in every compile: colorQuery kept each grammar's patterns whose captures pardes colours by scanning the 29 highlights.scm byte by byte at comptime, a quarter of a full recompile of the core (and again in each of the ~15 artifacts that import it); build.zig's treeSitter now runs the same filter once over the query it reads (grammar_manifest.colorQuery, a plain function, with Syn and synFor's capture-to-class table beside it, the one copy both the build and syntax.zig read), so ts_queries' _highlights is the filtered query and Spec.query_src a field read; typst's supplement is the manifest's highlights_extra, appended before the filter as before; _highlights_unfiltered is the whole query, for the test that the filter keeps every colour; a package that depends on pardes gets the same through library's treeSitter, for its own grammar set; proven byte-identical before the comptime path went (29 grammars, 28,398 filtered bytes of 79,678); core-test's forced full recompile 12.7-12.9 s wall / 17.5 s CPU to 9.7-10.1 s / 14.6 s; syntax snapshots unchanged; the changelog says so --- build.zig | 8 +++- src/CHANGELOG.md | 6 +++ src/grammar_manifest.zig | 108 ++++++++++++++++++++++++++++++++++++++++++-- src/syntax.zig | 114 +++-------------------------------------------- 4 files changed, 122 insertions(+), 114 deletions(-) (limited to 'src') diff --git a/build.zig b/build.zig index 0e67b61e..c7604c62 100644 --- a/build.zig +++ b/build.zig @@ -2101,8 +2101,12 @@ fn treeSitter(b: *std.Build, io: std.Io, target: std.Build.ResolvedTarget, c_opt (tree_sitter_grammars == .zig and g.tier == .zig)) grammar: { const dep = b.lazyDependency(g.dep, .{}) orelse break :grammar; - const query = configureRead(b, io, dep.builder.root, g.query, 0x100000) catch @panic("read " ++ g.name ++ " highlights"); - ts_queries.addOption([]const u8, g.name ++ "_highlights", query); + const upstream = configureRead(b, io, dep.builder.root, g.query, 0x100000) catch @panic("read " ++ g.name ++ " highlights"); + // the patterns that colour, filtered here once and not in + // every compile, and the whole query, the filter's test's + const query = std.mem.concat(b.allocator, u8, &.{ upstream, g.highlights_extra }) catch @panic("OOM"); + ts_queries.addOption([]const u8, g.name ++ "_highlights_unfiltered", query); + ts_queries.addOption([]const u8, g.name ++ "_highlights", grammar_manifest.colorQuery(query, b.allocator.alloc(u8, query.len) catch @panic("OOM"))); // helix's textobject queries, vendored (vendor/queries); a // grammar without one gets none const objects = configureRead(b, io, b.root, "vendor/queries/" ++ g.name ++ "/textobjects.scm", 0x100000) catch ""; diff --git a/src/CHANGELOG.md b/src/CHANGELOG.md index dc130be1..3b139f00 100644 --- a/src/CHANGELOG.md +++ b/src/CHANGELOG.md @@ -2,6 +2,12 @@ ## Unreleased +- An edit to the core recompiles it about 3 s sooner (`core-test`, 13 s to + 10 s): the build keeps each grammar's highlight patterns that pardes + colours once, where every compile of every program that takes the core + did it again, a quarter of its time. A package that depends on pardes + is given the same filtered queries. + - Commit patches open as `+Diff-` and reuse only their own commit's pane, so another paged patch no longer replaces one already open. diff --git a/src/grammar_manifest.zig b/src/grammar_manifest.zig index 38c54916..711c31a4 100644 --- a/src/grammar_manifest.zig +++ b/src/grammar_manifest.zig @@ -1,6 +1,7 @@ //! Dependency-free tree-sitter grammar metadata shared by build.zig and the -//! runtime syntax registry. Keep target symbols and query values out of this -//! file: the build runner imports it as host code. +//! runtime syntax registry, and the highlight-query filter the build runs. +//! Keep target symbols and query values out of this file: the build runner +//! imports it as host code. const std = @import("std"); @@ -14,6 +15,8 @@ pub const Grammar = struct { src: []const u8 = "src", scanner: bool = false, query: []const u8 = "queries/highlights.scm", + /// Patterns appended to the highlights query before it is filtered. + highlights_extra: []const u8 = "", }; pub const all = [_]Grammar{ @@ -48,7 +51,13 @@ pub const all = [_]Grammar{ .{ .name = "ruby", .dep = "ts_ruby", .exts = &.{ ".rb", ".rake" }, .tier = .full, .scanner = true }, .{ .name = "rust", .dep = "ts_rust", .exts = &.{".rs"}, .tier = .full, .scanner = true }, .{ .name = "scala", .dep = "ts_scala", .exts = &.{ ".scala", ".sc" }, .tier = .full, .scanner = true }, - .{ .name = "typst", .dep = "ts_typst", .exts = &.{ ".typ", ".typst" }, .tier = .full, .scanner = true, .query = "queries/typst/highlights.scm" }, + .{ .name = "typst", .dep = "ts_typst", .exts = &.{ ".typ", ".typst" }, .tier = .full, .scanner = true, .query = "queries/typst/highlights.scm", .highlights_extra = + \\ + \\(call item: (ident) @keyword) + \\(call item: (field field: (ident) @keyword)) + \\"#" @keyword + \\ + }, .{ .name = "zig", .dep = "ts_zig", .exts = &.{ ".zig", ".zon" }, .tier = .zig }, }; @@ -92,3 +101,96 @@ pub fn byPath(path: []const u8) ?usize { for (all, 0..) |g, i| for (g.exts) |e| if (std.ascii.eqlIgnoreCase(ext, e)) return i; return null; } + +/// pardes's syntax classes: what a capture colours a byte as. +pub const Syn = enum(u8) { none, keyword, string, number, comment }; + +pub fn synFor(name: []const u8) Syn { + for ([_]struct { []const u8, Syn }{ + .{ "comment", .comment }, + .{ "string", .string }, + .{ "character", .string }, + .{ "number", .number }, + .{ "numeric", .number }, + .{ "float", .number }, + .{ "boolean", .number }, + .{ "keyword", .keyword }, + .{ "include", .keyword }, + .{ "conditional", .keyword }, + .{ "repeat", .keyword }, + .{ "title", .keyword }, + .{ "uri", .string }, + .{ "reference", .number }, + .{ "heading", .keyword }, + .{ "strong", .comment }, + .{ "bold", .comment }, + .{ "emphasis", .number }, + .{ "italic", .number }, + .{ "literal", .string }, + .{ "raw", .string }, + }) |m| { + if (std.mem.indexOf(u8, name, m[0]) != null) return m[1]; + } + return .none; +} + +/// The patterns of highlights query `source` that capture a class (synFor), +/// written to `out` (source.len bytes): what a grammar's query compiles to. +/// build.zig filters each one with it, ts_queries' `_highlights`. +pub fn colorQuery(source: []const u8, out: []u8) []u8 { + var written: usize = 0; + var at: usize = 0; + while (at < source.len) { + while (at < source.len) { + if (std.ascii.isWhitespace(source[at])) { + at += 1; + } else if (source[at] == ';') { + while (at < source.len and source[at] != '\n') at += 1; + } else break; + } + const begin = at; + var depth: usize = 0; + var colored = false; + var complete = false; + while (at < source.len) { + const byte = source[at]; + if (complete and (byte == '(' or byte == '[' or byte == '"')) break; + if (byte == ';') { + while (at < source.len and source[at] != '\n') at += 1; + continue; + } + if (byte == '"') { + at += 1; + while (at < source.len) : (at += 1) { + if (source[at] == '\\') { + at += 1; + } else if (source[at] == '"') { + at += 1; + break; + } + } + if (depth == 0) complete = true; + continue; + } + if (byte == '(' or byte == '[') depth += 1; + if (byte == ')' or byte == ']') { + depth -= 1; + if (depth == 0) complete = true; + } + if (byte == '@') { + const name = at + 1; + at = name; + while (at < source.len and (std.ascii.isAlphanumeric(source[at]) or + source[at] == '_' or source[at] == '.' or source[at] == '-')) at += 1; + colored = colored or synFor(source[name..at]) != .none; + continue; + } + at += 1; + } + if (colored) { + @memcpy(out[written..][0 .. at - begin], source[begin..at]); + written += at - begin; + } + } + return out[0..written]; +} diff --git a/src/syntax.zig b/src/syntax.zig index 2526e113..8533aaa9 100644 --- a/src/syntax.zig +++ b/src/syntax.zig @@ -22,7 +22,7 @@ const ts_queries = if (enabled) @import("ts_queries") else struct {}; const LanguageFn = *const fn () callconv(.c) *const ts.Language; -pub const Syn = enum(u8) { none, keyword, string, number, comment }; +pub const Syn = grammar_manifest.Syn; /// A query compiled when first asked for: "" for none, null when it fails. const Lazy = struct { src: []const u8 = "", query: ?*ts.Query = null, failed: bool = false }; @@ -55,81 +55,6 @@ fn specCount() comptime_int { } return count; } -const typst_supplement = - \\ - \\(call item: (ident) @keyword) - \\(call item: (field field: (ident) @keyword)) - \\"#" @keyword - \\ -; - -fn querySrc(comptime g: grammar_manifest.Grammar) []const u8 { - const base = @field(ts_queries, g.name ++ "_highlights"); - const source = if (comptime std.mem.eql(u8, g.name, "typst")) base ++ typst_supplement else base; - return comptime colorQuery(source); -} - -fn colorQuery(comptime source: []const u8) []const u8 { - @setEvalBranchQuota(2_000_000); - var result: [source.len]u8 = undefined; - var written: usize = 0; - var at: usize = 0; - while (at < source.len) { - while (at < source.len) { - if (std.ascii.isWhitespace(source[at])) { - at += 1; - } else if (source[at] == ';') { - while (at < source.len and source[at] != '\n') at += 1; - } else break; - } - const begin = at; - var depth: usize = 0; - var colored = false; - var complete = false; - while (at < source.len) { - const byte = source[at]; - if (complete and (byte == '(' or byte == '[' or byte == '"')) break; - if (byte == ';') { - while (at < source.len and source[at] != '\n') at += 1; - continue; - } - if (byte == '"') { - at += 1; - while (at < source.len) : (at += 1) { - if (source[at] == '\\') { - at += 1; - } else if (source[at] == '"') { - at += 1; - break; - } - } - if (depth == 0) complete = true; - continue; - } - if (byte == '(' or byte == '[') depth += 1; - if (byte == ')' or byte == ']') { - depth -= 1; - if (depth == 0) complete = true; - } - if (byte == '@') { - const name = at + 1; - at = name; - while (at < source.len and (std.ascii.isAlphanumeric(source[at]) or - source[at] == '_' or source[at] == '.' or source[at] == '-')) at += 1; - colored = colored or synFor(source[name..at]) != .none; - continue; - } - at += 1; - } - if (colored) { - @memcpy(result[written..][0 .. at - begin], source[begin..at]); - written += at - begin; - } - } - const filtered = result[0..written].*; - return &filtered; -} - fn initSpecs() [specCount()]Spec { var out: [specCount()]Spec = undefined; var i = 0; @@ -139,7 +64,7 @@ fn initSpecs() [specCount()]Spec { .name = g.name, .exts = g.exts, .language = @extern(LanguageFn, .{ .name = "tree_sitter_" ++ g.name }), - .query_src = querySrc(g), + .query_src = @field(ts_queries, g.name ++ "_highlights"), .objects = .{ .src = @field(ts_queries, g.name ++ "_textobjects") }, .indents = .{ .src = @field(ts_queries, g.name ++ "_indents") }, }; @@ -219,7 +144,7 @@ fn ensure(spec: *Spec) !Selected { const capture_styles = spec.capture_styles[0..query.captureCount()]; for (capture_styles, 0..) |*style, id| { const name = query.captureNameForId(@intCast(id)) orelse ""; - style.* = @backingInt(synFor(name)); + style.* = @backingInt(grammar_manifest.synFor(name)); if (style.* == 0) query.disableCapture(name); } const parser = ts.Parser.create(); @@ -260,34 +185,6 @@ fn runQuery(styles: []u8, sel: Selected, tree: *ts.Tree, base: usize) void { } } -fn synFor(name: []const u8) Syn { - for ([_]struct { []const u8, Syn }{ - .{ "comment", .comment }, - .{ "string", .string }, - .{ "character", .string }, - .{ "number", .number }, - .{ "numeric", .number }, - .{ "float", .number }, - .{ "boolean", .number }, - .{ "keyword", .keyword }, - .{ "include", .keyword }, - .{ "conditional", .keyword }, - .{ "repeat", .keyword }, - .{ "title", .keyword }, - .{ "uri", .string }, - .{ "reference", .number }, - .{ "heading", .keyword }, - .{ "strong", .comment }, - .{ "bold", .comment }, - .{ "emphasis", .number }, - .{ "italic", .number }, - .{ "literal", .string }, - .{ "raw", .string }, - }) |m| { - if (std.mem.indexOf(u8, name, m[0]) != null) return m[1]; - } - return .none; -} pub fn highlightFileRange(gpa: std.mem.Allocator, path: []const u8, content: []const u8, start_raw: usize, end_raw: usize) ![]u8 { const zone = tracy.zone(@src(), "highlightFileRange"); defer zone.end(); @@ -1909,8 +1806,7 @@ test "syntax query filtering preserves upstream colors" { inline for (grammar_manifest.all) |grammar| { if (comptime grammarSelected(grammar)) { const selected = (try forLang(grammar.name)).?; - const raw_source = @field(ts_queries, grammar.name ++ "_highlights") ++ - (if (comptime std.mem.eql(u8, grammar.name, "typst")) typst_supplement else ""); + const raw_source = @field(ts_queries, grammar.name ++ "_highlights_unfiltered"); var error_offset: u32 = 0; const raw_query = try ts.Query.create(selected.lang, raw_source, &error_offset); defer raw_query.destroy(); @@ -1918,7 +1814,7 @@ test "syntax query filtering preserves upstream colors" { reference.query = raw_query; reference.capture_styles = try std.testing.allocator.alloc(u8, raw_query.captureCount()); defer std.testing.allocator.free(reference.capture_styles); - for (reference.capture_styles, 0..) |*style, id| style.* = @backingInt(synFor(raw_query.captureNameForId(@intCast(id)) orelse "")); + for (reference.capture_styles, 0..) |*style, id| style.* = @backingInt(grammar_manifest.synFor(raw_query.captureNameForId(@intCast(id)) orelse "")); const tree = selected.parser.parseString(source, null) orelse return error.ParseFailed; defer tree.destroy(); var expected: [source.len]u8 = @splat(0); -- cgit v1.3 From 6d9272b83d122585ad7bbe7214c078f65351c3c0 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 17 Nov 2026 00:25:19 -0300 Subject: lib: the diff is a language of pardes-syntax: `diff` (Walk, targetAt), `highlightDiff`, the style byte's `syn_bits` and grounds and colors.Grounds, a theme's colours for them; test/lib colours a C patch through it (each side's code as C, the rows' grounds, Orchard's, and the place a `+` row names) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- src/lib_syntax.zig | 19 +++++++++++++++++++ test/lib/lib.zig | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+) (limited to 'src') diff --git a/src/lib_syntax.zig b/src/lib_syntax.zig index 395a02f0..a25af884 100644 --- a/src/lib_syntax.zig +++ b/src/lib_syntax.zig @@ -51,6 +51,25 @@ pub const SourceAnalysis = syntax.SourceAnalysis; pub const ContextDeclaration = syntax.ContextDeclaration; pub const analyzeSource = syntax.analyzeSource; +/// A unified diff as a language: `diff` walks one a line at a time +/// (`Walk`: a line's kind, the file its section names, the hunk's line +/// numbers) and says what a row of it points at (`targetAt`); +/// `highlightDiff` is a style byte for each byte of `content[start..end]`, +/// the caller's to free: headers as comments, `@@` lines as keywords, each +/// hunk's code in the language of the file its section names (old and new +/// side each parsed whole), and over that an added or removed line's +/// grounds (`ground_add`, `ground_del`; its first byte `ground_emph`, the +/// strong row). A byte's low bits (`syn_bits`) are a `Syn`; `Grounds` are +/// a theme's colours for the rest. +pub const diff = @import("diff.zig"); +pub const highlightDiff = syntax.highlightDiff; +pub const syn_bits = syntax.syn_bits; +pub const ground_add = syntax.ground_add; +pub const ground_del = syntax.ground_del; +pub const ground_emph = syntax.ground_emph; +pub const ground_line = syntax.ground_line; +pub const Grounds = colors.Grounds; + /// The tree-sitter bindings a tree is read through: `tree.rootNode()`, and /// a node's `kind()`, `startByte()`, `endByte()`, `child(i)`, `parent()`. pub const ts = syntax.ts; diff --git a/test/lib/lib.zig b/test/lib/lib.zig index a3f99b56..7e297920 100644 --- a/test/lib/lib.zig +++ b/test/lib/lib.zig @@ -102,6 +102,60 @@ test "a C and a Zig source are coloured, outlined and walked as pardes has them, try std.testing.expectEqual(null, pardes.theme("no such theme")); } +test "a diff is a language: its hunks coloured as their file's, its added and removed rows on a theme's grounds" { + const gpa = std.testing.allocator; + pardes.start(gpa); + defer pardes.stop(); + const patch = + \\diff --git a/main.c b/main.c + \\--- a/main.c + \\+++ b/main.c + \\@@ -1,3 +1,3 @@ + \\ int main(void) { + \\- return 1; + \\+ return 0; + \\ } + \\ + ; + const styles = try pardes.highlightDiff(gpa, patch, 0, patch.len); + defer gpa.free(styles); + try std.testing.expectEqual(patch.len, styles.len); + const syn = struct { + fn at(s: []const u8, text: []const u8, needle: []const u8) pardes.Syn { + return @fromBackingInt(s[std.mem.indexOf(u8, text, needle).?] & pardes.syn_bits); + } + }.at; + try std.testing.expectEqual(pardes.Syn.comment, syn(styles, patch, "--- a/main.c")); + try std.testing.expectEqual(pardes.Syn.keyword, syn(styles, patch, "@@ -1,3")); + // each side's code as C, behind its marker + try std.testing.expectEqual(pardes.Syn.keyword, syn(styles, patch, "return 1")); + try std.testing.expectEqual(pardes.Syn.keyword, syn(styles, patch, "return 0")); + try std.testing.expectEqual(pardes.Syn.number, syn(styles, patch, "0;")); + const added = std.mem.indexOf(u8, patch, "+ return 0").?; + const removed = std.mem.indexOf(u8, patch, "- return 1").?; + try std.testing.expectEqual(pardes.ground_add | pardes.ground_emph, styles[added]); + try std.testing.expect(styles[added + 5] & pardes.ground_add != 0 and styles[added + 5] & pardes.ground_emph == 0); + try std.testing.expectEqual(pardes.ground_del | pardes.ground_emph, styles[removed]); + try std.testing.expectEqual(0, styles[std.mem.indexOf(u8, patch, " int main").?] & (pardes.ground_add | pardes.ground_del)); + + // a row's hue in a theme: a ground between the page and the theme's green, a stronger and a fainter one + const th = pardes.theme("Orchard").?; + const g = pardes.Grounds.of(th); + const ground = g.forStyle(styles[added]).?; + try std.testing.expectEqual(g.add, ground); + try std.testing.expectEqual(g.del, g.forStyle(styles[removed]).?); + try std.testing.expectEqual(null, g.forStyle(@backingInt(pardes.Syn.keyword))); + try std.testing.expect(!std.mem.eql(u8, &ground.row, &pardes.page(th)) and !std.mem.eql(u8, &ground.row, &ground.emph) and !std.mem.eql(u8, &ground.row, &ground.line)); + + // what a row points at: the new line a `+` row is + var lines: std.ArrayList([]const u8) = .empty; + defer lines.deinit(gpa); + var it = std.mem.splitScalar(u8, patch, '\n'); + while (it.next()) |line| try lines.append(gpa, line); + var buf: [64]u8 = undefined; + try std.testing.expectEqualStrings("main.c:2", pardes.diff.targetAt(lines.items, 6, false).?.address(&buf).?); +} + test "every name the library has compiles outside pardes" { std.testing.refAllDecls(pardes); } -- cgit v1.3 From 218d574b59abd7fb8dd6fe027b12927fc31c3506 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 17 Nov 2026 00:25:32 -0300 Subject: output: a results pane's refill identity is its name too, so fillRows loses its diff.commitHash case: fillRows takes the name its producer gives the pane (null: its origin's own, as open names it) and refills only a pane of that name, with that origin and arg, in that directory; openDiff names a commit's +Diff `+Diff-<12 hex>` through it rather than renaming the pane after, so each commit keeps its own +Diff and the same commit refills it, as before (hunks.zig's last test); goldens unchanged Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- src/Output.zig | 37 ++++++++++++++++++++----------------- 1 file changed, 20 insertions(+), 17 deletions(-) (limited to 'src') diff --git a/src/Output.zig b/src/Output.zig index d4be640c..5bad7ab7 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -414,17 +414,19 @@ pub fn fillResults(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: [] result_rows = formatted.rows; anchor = formatted.anchor; } - _ = try fillRows(p, id, dir, from, arg, result_content, result_rows, anchor); + _ = try fillRows(p, id, dir, from, null, arg, result_content, result_rows, anchor); } /// Rows already laid out (`content`, `rows` its metadata, both taken /// when it succeeds, the caller's still when it fails) into the pane they -/// belong in: the one a run of `from` with `arg` in `dir` showed last, +/// belong in: the one named `name` (null: its origin's own name, as `open` +/// gives it) that a run of `from` with `arg` in `dir` showed last, /// refilled, else a new one placed by pane `id`. Its id. -pub fn fillRows(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: []const u8, result_content: []u8, result_rows: []locations.Row, anchor: ?usize) !usize { +pub fn fillRows(p: *Pardes, id: usize, dir: []const u8, from: Origin, name: ?[]const u8, arg: []const u8, result_content: []u8, result_rows: []locations.Row, anchor: ?usize) !usize { const pane = p.panes[id] orelse return error.MissingPane; if (arg.len > max_arg) return error.ArgumentTooLong; const by_arg = std.meta.activeTag(from) != .query; + const own = name orelse if (from == .kind) arg else traits(from).name; for (p.panes, 0..) |slot, i| { const rp = slot orelse continue; const rf = if (rp.file) |*f| f else continue; @@ -440,8 +442,7 @@ pub fn fillRows(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: []con if (!shared and !std.meta.eql(o.from, from)) continue; if (!shared and by_arg and !std.mem.eql(u8, o.arg(), arg)) continue; if (!std.mem.eql(u8, std.Io.Dir.path.dirname(rf.path) orelse "", dir)) continue; - if (std.meta.eql(from, Origin{ .cmd = .Diff }) and - !std.mem.eql(u8, diff.commitHash(rf.content) orelse "", diff.commitHash(result_content) orelse "")) continue; + if (!std.mem.eql(u8, std.Io.Dir.path.basename(rf.path), std.Io.Dir.path.basename(own))) continue; o.from = from; p.fs.refilled = rp.serial; try setArg(o, arg); @@ -470,7 +471,13 @@ pub fn fillRows(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: []con return i; } const free = p.freeSlot() orelse return error.NoPaneSlots; + const path = if (name) |named| try std.fmt.allocPrint(p.gpa, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), named }) else null; + errdefer if (path) |owned| p.gpa.free(owned); const np = try open(p, free, dir, from, arg, result_content); + if (path) |owned| { + p.gpa.free(np.file.?.path); + np.file.?.path = owned; + } np.file.?.location_rows = result_rows; layout.placeNew(p, id, id, free, .doc); p.view().active = id; @@ -486,8 +493,10 @@ pub fn fillRows(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: []con /// diff viewer shows it (hunks.zig), in a +Diff where its files are found /// (hunks.sourceRoot), placed by pane `id`, refilled when it is there. Its /// arg names the diff (its base name, or its whole path when the +Diff -/// stands elsewhere), for Diff to go back to it. The +Diff's id; -/// NoHunks when there is none in it. +/// stands elsewhere), for Diff to go back to it; a commit's (`git show`, a +/// mailed patch) is named for it too, `+Diff-<12 hex>`, so each commit +/// keeps a +Diff of its own. The +Diff's id; NoHunks when there is none in +/// it. pub fn openDiff(p: *Pardes, id: usize, path: []const u8, content: []const u8) !usize { const dir = std.Io.Dir.path.dirname(path) orelse p.sessionDir(); // Each file read is a site of the step's tape (fs.zig): a replica @@ -525,18 +534,12 @@ pub fn openDiff(p: *Pardes, id: usize, path: []const u8, content: []const u8) !u for (result.rows) |row| has_hunk = has_hunk or row.kind == .match; if (!has_hunk) return error.NoHunks; const arg = if (std.mem.eql(u8, root, dir) or path.len > max_arg) std.Io.Dir.path.basename(path) else path; - const title = if (diff.commitHash(content)) |hash| - try std.fmt.allocPrint(p.gpa, "{s}/{s}-{s}", .{ std.mem.trimEnd(u8, root, "/"), config.diff_buffer, hash[0..@min(hash.len, 12)] }) + var name_buf: [config.diff_buffer.len + 13]u8 = undefined; + const name = if (diff.commitHash(content)) |hash| + std.fmt.bufPrint(&name_buf, "{s}-{s}", .{ config.diff_buffer, hash[0..@min(hash.len, 12)] }) catch unreachable else null; - errdefer if (title) |name| p.gpa.free(name); - const hid = try fillRows(p, id, root, .{ .cmd = .Diff }, arg, result.content, result.rows, null); - if (title) |name| { - const f = &p.panes[hid].?.file.?; - p.gpa.free(f.path); - f.path = name; - } - return hid; + return fillRows(p, id, root, .{ .cmd = .Diff }, name, arg, result.content, result.rows, null); } /// Diff on a +Diff: the diff it stacks, as text. A pane holding it -- cgit v1.3 From d7b3d57ed0ba649f01559356fbf2bf89561990ca Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 17 Nov 2026 00:35:08 -0300 Subject: rows: a pane's rows from outside, one definition and two sinks: File.setRows is the one writer of a pane's rows (locations.Row, the stored form as it was: digest, dump and blobs unchanged), refusing what its text cannot hold (more rows than lines, an offset or styles past a line's end) and keeping the painting of equal rows; Output.fillRows keeps what is the editor's (the pane, its refill identity, the steps) and hands its rows to it, as the query panes' three writers do; locations.formatRows and parseRows are its text, a line a row, fields a blank apart and the path last (kind m c p with d and u, line col end_line end_col source_column location_end code_start, styles as `-` or `N:start+len=role,...` a role a syntax class and grounds joined by dots); each pane directory over 9P has `rows`, read as that text (+Search's, +Callstack's addresses as data) and written whole lines at a time, at 0 replacing and later following (a line cut by a mount waits for its open's next write; tree.writeLines passes a line on at the offset it was begun at), `>` emptying them; tests: the rows of a +Search, a +Callstack and a +Diff read back from their text equal, byte for byte, and the file read, written whole and across writes, refused and emptied; README, reference and changelog say so Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- docs/typ/reference.typ | 1 + src/CHANGELOG.md | 10 +++ src/File.zig | 23 +++++++ src/Output.zig | 17 ++--- src/Query.zig | 35 +++------- src/fs-help.txt | 4 +- src/locations.zig | 176 +++++++++++++++++++++++++++++++++++++++++++++++++ src/ninep/pane.zig | 93 +++++++++++++++++++++++++- src/ninep/pty.zig | 4 +- src/ninep/tree.zig | 14 ++-- 10 files changed, 331 insertions(+), 46 deletions(-) (limited to 'src') diff --git a/docs/typ/reference.typ b/docs/typ/reference.typ index 7360179f..637d9c72 100644 --- a/docs/typ/reference.typ +++ b/docs/typ/reference.typ @@ -64,6 +64,7 @@ pane/ the panes @pa look a #word("Look") at this pane @look-and-exec exec an #word("Exec") at this pane @look-and-exec tagexec a word clicked in this pane's tag @look-and-exec + rows a line a row: where it points, how it is coloured (README) @panes pty/ terminals only @pty ctl winsize, sig, exec @pty status cols rows busy @pty diff --git a/src/CHANGELOG.md b/src/CHANGELOG.md index da489b82..a64de8e1 100644 --- a/src/CHANGELOG.md +++ b/src/CHANGELOG.md @@ -2,6 +2,16 @@ ## Unreleased +- Each pane's directory over 9P has a `rows` file: a line a body row of a + results pane (+Search, +Callstack, +Diff, a language server's list), + where it points (`path`, line, column, the address's end, where its code + starts) and how it is coloured (runs of `keyword`, `string`, ... and the + grounds `add`, `del`, `emph`, `line`), so a 9P client reads their + addresses as data, not by parsing the text. A write at offset 0 replaces + a pane's rows, a later one adds to them; rows its text cannot hold are + refused. An edit drops them, as before. The editor's own producers set + rows the same one way. + - A drag draws no guide lines: no dashes where a pane or column would land, no rail for a carried column, no dashed seam under a pane rule held. The line between two columns no longer resizes them (nor, at a diff --git a/src/File.zig b/src/File.zig index 1988fb89..84e88dff 100644 --- a/src/File.zig +++ b/src/File.zig @@ -660,6 +660,29 @@ pub fn setContent(p: *Pardes, f: *State, new: []u8) void { setContentSpan(p, f, new, null); } +/// `rows`, a row a line of the text from its first (where each points, how +/// it is coloured: locations.Row), made the pane's, taken: the one way a +/// pane's rows are set, by a producer in the editor (Output.fillRows, a +/// query pane) or from outside (the pane's `rows` file). RowsMismatch, the +/// rows still the caller's, for rows the text cannot hold: more of them +/// than it has lines, or an offset or styles past its line's end. Rows +/// equal to the pane's keep its painting; others drop it, to be painted +/// from them. An edit of the text drops them (setContentSpan). +pub fn setRows(p: *Pardes, f: *State, rows: []locations.Row) error{RowsMismatch}!void { + var lines = std.mem.splitScalar(u8, f.content, '\n'); + for (rows) |row| { + const line = lines.next() orelse return error.RowsMismatch; + if (row.location_end > line.len or row.code_start > line.len or row.colors.len > line.len - row.code_start) return error.RowsMismatch; + } + if (locations.equalRows(f.location_rows, rows)) return locations.freeRows(p.gpa, rows); + locations.freeRows(p.gpa, f.location_rows); + f.location_rows = rows; + if (f.highlights.len > 0) p.tree_sitter_gpa.free(f.highlights); + f.highlights = &.{}; + f.highlight_start = 0; + f.syntax_dirty = true; +} + /// `setContent` for a splice that knows what it left alone at either end, /// so it is not found again by comparing the whole text. The edit is what /// lies between them, made by `edit`, which takes `new`, a whole text its diff --git a/src/Output.zig b/src/Output.zig index 5bad7ab7..3bcc3fa5 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -452,16 +452,10 @@ pub fn fillRows(p: *Pardes, id: usize, dir: []const u8, from: Origin, name: ?[]c File.setContent(p, rf, result_content); resetBody(p, rp); } - if (locations.equalRows(rf.location_rows, result_rows)) { + File.setRows(p, rf, result_rows) catch |err| { locations.freeRows(p.gpa, result_rows); - } else { - locations.freeRows(p.gpa, rf.location_rows); - rf.location_rows = result_rows; - if (rf.highlights.len > 0) p.tree_sitter_gpa.free(rf.highlights); - rf.highlights = &.{}; - rf.highlight_start = 0; - rf.syntax_dirty = true; - } + p.reportError(id, "rows", err); + }; p.view().active = id; if (traits(from).steps) { pane.search_pane = i; @@ -478,7 +472,10 @@ pub fn fillRows(p: *Pardes, id: usize, dir: []const u8, from: Origin, name: ?[]c p.gpa.free(np.file.?.path); np.file.?.path = owned; } - np.file.?.location_rows = result_rows; + File.setRows(p, &np.file.?, result_rows) catch |err| { + locations.freeRows(p.gpa, result_rows); + p.reportError(id, "rows", err); + }; layout.placeNew(p, id, id, free, .doc); p.view().active = id; if (traits(from).steps) { diff --git a/src/Query.zig b/src/Query.zig index caf64d54..c1a89164 100644 --- a/src/Query.zig +++ b/src/Query.zig @@ -859,19 +859,14 @@ fn setRows(p: *Pardes, rp: *Pane, out: *std.ArrayList(u8), rows: *std.ArrayList( if (std.mem.eql(u8, content, f.content)) { // Same text: the metadata alone, no undo step, no syntax pass. p.gpa.free(content); - if (locations.equalRows(f.location_rows, meta)) { - locations.freeRows(p.gpa, meta); - } else { - locations.freeRows(p.gpa, f.location_rows); - f.location_rows = meta; - dropHighlights(p, f); - } } else { File.setContent(p, f, content); - locations.freeRows(p.gpa, f.location_rows); - f.location_rows = meta; f.saved_revision = f.revision; } + File.setRows(p, f, meta) catch |err| { + locations.freeRows(p.gpa, meta); + if (p.paneBySerial(rp.serial)) |id| p.reportError(id, "rows", err); + }; if (f.pager_spans.len > 0) p.gpa.free(f.pager_spans); f.pager_spans = &.{}; // The cursor stays where it was typing; on a row that went, the last. @@ -996,24 +991,10 @@ pub fn recolor(p: *Pardes) void { fresh = rows; @memcpy(rows[i].colors[0..got.len], got); } - if (fresh) |rows| { - locations.freeRows(p.gpa, f.location_rows); - f.location_rows = rows; - dropHighlights(p, f); - } + if (fresh) |rows| File.setRows(p, f, rows) catch locations.freeRows(p.gpa, rows); } } -/// The pane's painted colours let go, so the next frame paints them from -/// its rows again: with its text the same, a frame would keep the old ones -/// (refreshHighlights keeps a painting that covers the view). -fn dropHighlights(p: *Pardes, f: *File.State) void { - if (f.highlights.len > 0) p.tree_sitter_gpa.free(f.highlights); - f.highlights = &.{}; - f.highlight_start = 0; - f.syntax_dirty = true; -} - /// The path a row of pane `tp`'s text says: its file's, or `@pN` for a /// text that is no file (a list, a scratch). fn addressOf(arena: std.mem.Allocator, tp: *const Pane) []const u8 { @@ -1910,8 +1891,10 @@ pub fn cancel(p: *Pardes, id: usize) void { } const f = &rp.file.?; File.setContent(p, f, s.content); - locations.freeRows(p.gpa, f.location_rows); - f.location_rows = s.rows; + File.setRows(p, f, s.rows) catch |err| { + locations.freeRows(p.gpa, s.rows); + p.reportError(id, "query", err); + }; p.gpa.free(q.asked); q.asked = s.asked; q.source = s.source; diff --git a/src/fs-help.txt b/src/fs-help.txt index bc699418..e6a48491 100644 --- a/src/fs-help.txt +++ b/src/fs-help.txt @@ -20,12 +20,12 @@ dumps the dumps the state file keeps, the newest first: