diff options
50 files changed, 5878 insertions, 280 deletions
diff --git a/abi/wire.zig b/abi/wire.zig index f558cb9a..d07e6a57 100644 --- a/abi/wire.zig +++ b/abi/wire.zig @@ -10,6 +10,10 @@ const pardes = @import("core"); const config = @import("pardes_options"); const build_info = @import("build_info"); +/// 36: a view's tag out of rest (walk UI: `View.tag_state`, its root's +/// delay, its level unrolled and that level's cursor, the leaf each group +/// ran last) in the dump and the digest; a pointer's tag hit may be on a +/// pane's band (TagKind `band`, the rows its tag unrolls into); /// 35: a view's top is a line and a row of that line's wrapped rows: a /// file's `scroll_row` (and its share's in each view) in the dump and the /// digest; a dump without it loads at its lines' first rows; @@ -76,7 +80,7 @@ const build_info = @import("build_info"); /// part B); 14: the hello names a session and /// carries the semantics hash, and a ping is answered (phase 5's /// groundwork); 13: the frames went (phase 3). -pub const version: u16 = 35; +pub const version: u16 = 36; /// The terminal's build and the window's step alike (`semantics`). const family = switch (config.platform) { diff --git a/core/Band.zig b/core/Band.zig new file mode 100644 index 00000000..5e399cba --- /dev/null +++ b/core/Band.zig @@ -0,0 +1,581 @@ +//! The band (walk UI, pick-ui SPEC.md §3.6): rows hanging under a pane's +//! tag while it is out of rest, in the tag's tint, pushing its body down: +//! the tag unrolled. Its steps stand side by side, each a column of rows +//! (a level, Help's rows, a doc; later a picker's acts and sources, a +//! prompt's history, the registers), a one-cell rule between them, right +//! of a spine under each of the head's key cells. +//! +//! Derived from the live view's state each time it is asked (`of`), never +//! stored (the coordinator's R2): the layout reads its height (`takes`, +//! Pardes.sync, layout.floorRows), the frame paints it (draw.zig +//! joinBand) as a tag layer of kind `.band`, and the mouse reads its words +//! (`line`): read-only text, which B2 executes and B3 looks at as a tag's. +//! +//! A new kind of step: a function that fills a `Step` (its `rows`, in the +//! frame's arena, as many as it shows, and whether it is a `doc`) from the +//! state that owns it, called from `of` for the tag state it belongs to, +//! with that state's rows in `height`; nothing else changes. +const Band = @This(); + +const std = @import("std"); +const pardes = @import("root.zig"); +const bindings = @import("bindings.zig"); +const tagline = @import("tagline.zig"); +const layout = @import("layout.zig"); +const modal = @import("modal.zig"); +const panes = @import("panes.zig"); +const builtins = @import("builtins.zig"); +const TagState = @import("TagState.zig"); +const Names = @import("Names.zig"); +const Pardes = pardes.Pardes; +const Pane = pardes.Pane; +const File = panes.File; + +/// One row of a step: its text, as B2 and B3 read it, and how it is drawn. +pub const Row = struct { + text: []const u8, + /// The rows' cursor: `▶` before it and the selection's tint over it. + on: bool = false, + /// Its first `key` bytes are a key: the key ink, bold. + key: u8 = 0, + dim: bool = false, + /// The leaf its group ran last. + under: bool = false, + /// The bytes a query matched: the match tint. + marks: []const u16 = &.{}, + /// Its place in the list its step shows (a level's child, a hit): what + /// a click on it moves the cursor to. + index: u16 = 0, + /// Marked in a picker's list: `•` before it. + mark: bool = false, + /// Its first `pre` bytes are a place (`file:line`, `@p3`): the name's + /// tint; the `faint` bytes after them dimmed (a path's directory). + pre: u16 = 0, + faint: u16 = 0, +}; + +/// A column of rows. A level of more than 9 rows flows into two columns +/// (`two`); a `doc` takes the width the others leave, wrapped to it, and is +/// the first to give way. +pub const Step = struct { + rows: []const Row = &.{}, + two: bool = false, + doc: bool = false, + /// Where it starts and how wide it is, in the band's columns (`place`). + x: u16 = 0, + width: u16 = 0, +}; + +pub const max_steps = 4; +pub const max_spines = 12; +/// The narrowest a step is drawn (SPEC §3.6: box, spines, one 24-cell column). +pub const min_width = 24; +/// A doc's rows, the fewest a band with one has. +const doc_rows = 4; +/// A level's rows past which it flows into two columns. +const one_column = 9; + +/// The columns of the head's key cells, in the band's columns: a spine +/// hangs under each. +spines: [max_spines]u16 = undefined, +nspines: u8 = 0, +steps: [max_steps]Step = undefined, +nsteps: u8 = 0, +height: u16 = 0, +/// The band's width at the tagline's pitch. +columns: u16 = 0, + +/// The rows the band under pane `id`'s tag takes in the live view, from +/// its state alone: the layout's term, asked before any frame is made. +pub fn takes(p: *Pardes, id: usize) u16 { + const v = p.view(); + const s = &v.tag_state; + if (TagState.hostOf(p) != id) return 0; + switch (s.kind) { + .rest => {}, + .help => return @max(doc_rows, @max(1, @min(Cursor.shown, s.nhits))), + .describe => { + if (!s.found) return 0; + var children: [bindings.max_children]bindings.Child = undefined; + return @max(doc_rows, levelRows(@intCast(bindings.level(p, s.scope_root.?, s.scope[0 .. s.scope_n - 1], &children).len))); + }, + .pick => return @import("Pick.zig").bandRows(p), + } + if (!s.unrolled) return 0; + const cur = TagState.current(p, v) orelse return 0; + var children: [bindings.max_children]bindings.Child = undefined; + const n: u16 = @intCast(bindings.level(p, cur.root, cur.path, &children).len); + return @max(doc_rows, levelRows(n)); +} + +fn levelRows(n: u16) u16 { + return if (n > one_column) (n + 1) / 2 else n; +} + +/// Pane `id`'s band as the live view's state has it, made in `arena`; +/// null when its tag has none. +pub fn of(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, id: usize) !?Band { + const rows = takes(p, id); + if (rows == 0) return null; + const v = p.view(); + const s = &v.tag_state; + var band: Band = .{ .height = rows, .columns = layout.tagCapacity(p, p.view().rects[id].w -| pardes.TAG_TEXT_INSET) }; + switch (s.kind) { + .rest => {}, + .help => { + try band.helpSteps(p, arena, s); + try band.place(p, arena, pane, id); + return band; + }, + // describe-key's leaf: its level replayed, the leaf on the cursor, + // and its doc. + .describe => { + const root = s.scope_root.?; + const path = s.scope[0 .. s.scope_n - 1]; + var children: [bindings.max_children]bindings.Child = undefined; + const level = bindings.level(p, root, path, &children); + var at: usize = 0; + for (level, 0..) |c, i| if (c.key == s.scope[s.scope_n - 1]) { + at = i; + }; + const node = bindings.nodeAt(root, path); + band.add(try levelStep(arena, pane, level, at, if (node) |n| s.used[n.group] else 0)); + band.add(try docStep(p, arena, root, path, level[at])); + try band.place(p, arena, pane, id); + return band; + }, + .pick => { + for (try @import("Pick.zig").steps(p, arena)) |step| band.add(step); + try band.place(p, arena, pane, id); + return band; + }, + } + const cur = TagState.current(p, v).?; + // The level, its cursor on the child it names, else the leaf its group + // ran last, else the first; and that child's doc beside it. + const node = bindings.nodeAt(cur.root, cur.path); + const used = if (node) |n| s.used[n.group] else 0; + var children: [bindings.max_children]bindings.Child = undefined; + const level = bindings.level(p, cur.root, cur.path, &children); + var at: usize = 0; + for (level, 0..) |c, i| if (c.key == (if (s.hi != 0) s.hi else used)) { + at = i; + }; + band.add(try levelStep(arena, pane, level, at, used)); + band.add(try docStep(p, arena, cur.root, cur.path, level[at])); + try band.place(p, arena, pane, id); + return band; +} + +/// Help's rows (`chord · word · group`, the query's bytes in the match +/// tint) around the cursor, and the cursor's leaf's doc beside them. +fn helpSteps(band: *Band, p: *Pardes, arena: std.mem.Allocator, s: *const TagState) !void { + if (s.nhits == 0) { + const none = try arena.alloc(Row, 1); + none[0] = .{ .text = if (s.field.len == 0) "no keys here" else "no key matches", .dim = true }; + band.add(.{ .rows = none }); + return; + } + const w = s.rows.window(s.nhits); + const rows = try arena.alloc(Row, w.hi - w.lo); + const q = s.field.text(); + for (rows, w.lo..) |*row, i| { + const buf = try arena.create([TagState.row_max]u8); + const leaf = TagState.helpLeaf(p, s.hits[i], buf); + var marks: [Names.max_query * 4]u16 = undefined; + var nmarks: usize = 0; + if (std.mem.trim(u8, q, " ").len > 0) { + const low = try std.ascii.allocLowerString(arena, leaf.row); + _ = Names.match(q, leaf.row, low, 0, &marks, &nmarks); + } + row.* = .{ .text = leaf.row, .on = i == s.rows.at, .marks = try arena.dupe(u16, marks[0..nmarks]), .index = @intCast(i), .dim = bindings.dimmed(p.panes[p.view().active].?, leaf.child) }; + } + band.add(.{ .rows = rows }); + var buf: [TagState.row_max]u8 = undefined; + const at = TagState.helpLeaf(p, s.hits[s.rows.at], &buf); + band.add(try docStep(p, arena, at.root, at.path[0 .. at.path.len - 1], at.child)); +} + +/// A list's cursor and the rows of it a band shows: eleven at most, around +/// the cursor (SPEC §3.6, the prototype's `H.window`). Each view's (a +/// tag state's field): Help's rows, a picker's, a prompt's history. +pub const Cursor = struct { + at: u16 = 0, + + pub const shown = 11; + + /// Rows [lo, hi) of `n` the band shows. + pub fn window(c: Cursor, n: u16) struct { lo: u16, hi: u16 } { + const lo = @min(c.at -| shown / 2, n -| shown); + return .{ .lo = lo, .hi = @min(n, lo + shown) }; + } + + /// A key that steps a list of `n`: Down, C-j, C-n a row on, Up, C-k, + /// C-p a row back, PageDown and PageUp ten; true when taken. + pub fn key(c: *Cursor, k: pardes.Key, n: u16) bool { + const Key = pardes.Key; + const plain = !k.ctrl and !k.alt; + const ctrl = k.ctrl and !k.alt; + const step: i32 = if (plain and k.cp == Key.down or ctrl and (k.cp == 'j' or k.cp == 'n')) + 1 + else if (plain and k.cp == Key.up or ctrl and (k.cp == 'k' or k.cp == 'p')) + -1 + else if (plain and k.cp == Key.page_down) + 10 + else if (plain and k.cp == Key.page_up) + -10 + else + return false; + if (n == 0) return true; + c.at = @intCast(std.math.clamp(@as(i32, c.at) + step, 0, @as(i32, n) - 1)); + return true; + } +}; + +fn add(band: *Band, step: Step) void { + if (band.nsteps == max_steps) return; + band.steps[band.nsteps] = step; + band.nsteps += 1; +} + +/// A level's children as rows (`k Label`, a group's `label…`), the cursor +/// on child `at`. +pub fn levelStep(arena: std.mem.Allocator, pane: *const Pane, level: []const bindings.Child, at: usize, used: u8) !Step { + const rows = try arena.alloc(Row, level.len); + for (level, rows, 0..) |c, *row, i| { + const key = bindings.keyName(c.key); + row.* = .{ + .text = try std.fmt.allocPrint(arena, "{s} {s}{s}", .{ key, c.label, if (c.group) "…" else "" }), + .on = i == at, + .key = @intCast(key.len), + .dim = bindings.dimmed(pane, c), + .under = c.key == used, + .index = @intCast(i), + }; + } + return .{ .rows = rows, .two = level.len > one_column }; +} + +/// What child `c` is: a leaf's word and its whole documentation, then its +/// keys; a group's children, a row each. +pub fn docStep(p: *Pardes, arena: std.mem.Allocator, root: bindings.Root, path: []const u8, c: bindings.Child) !Step { + var rows: std.ArrayList(Row) = .empty; + const key = bindings.keyName(c.key); + try rows.append(arena, .{ .text = try std.fmt.allocPrint(arena, "{s} {s}{s}", .{ key, c.label, if (c.group) "…" else "" }), .key = @intCast(key.len) }); + if (c.group) { + const here = try std.mem.concat(arena, u8, &.{ path, &.{c.key} }); + var below: [bindings.max_children]bindings.Child = undefined; + for (bindings.level(p, root, here, &below)) |g| { + const k = bindings.keyName(g.key); + try rows.append(arena, .{ .text = try std.fmt.allocPrint(arena, "{s} {s}{s}", .{ k, g.label, if (g.group) "…" else "" }), .key = @intCast(k.len) }); + } + return .{ .rows = rows.items, .doc = true }; + } + const doc = if (c.node) |n| switch (n.leaf.?) { + .builtin => |b| builtins.registry.doc(b).text, + .arg => |a| builtins.registry.doc(pardes.config.leader_args[a].cmd).text, + .role => bindings.docOf(root, c, try arena.alloc(u8, 160)), + } else bindings.docOf(root, c, &.{}); + try rows.append(arena, .{ .text = doc }); + var buf: [64]u8 = undefined; + const here = try std.mem.concat(arena, u8, &.{ path, &.{c.key} }); + try rows.append(arena, .{ .text = try std.fmt.allocPrint(arena, "keys {s}", .{bindings.chord(root, here, &buf)}) }); + return .{ .rows = rows.items, .doc = true }; +} + +/// Where each step goes: right of the spines, a rule's cell between steps; +/// a doc takes what is left, wrapped to it. Narrow, the doc goes first, +/// then the spines (the steps start at the band's left edge). +fn place(band: *Band, p: *Pardes, arena: std.mem.Allocator, pane: *Pane, id: usize) !void { + const tab = p.settings.tab; + try band.findSpines(p, arena, pane, id); + var x: u16 = if (band.nspines > 0) band.spines[band.nspines - 1] + 2 else 0; + var need: u16 = 0; + for (band.steps[0..band.nsteps]) |*step| { + if (step.doc) continue; + var widest: usize = 0; + for (step.rows) |row| widest = @max(widest, File.displayWidth(tab, row.text)); + const column: u16 = @intCast(@min(widest + 2, std.math.maxInt(u16) / 4, @max(min_width, band.columns -| x))); + step.width = if (step.two) 2 * column + 1 else column; + need += step.width + 2; + } + if (x + need > band.columns) { + band.nspines = 0; + x = 0; + } + var kept: u8 = 0; + for (band.steps[0..band.nsteps]) |step| { + var placed = step; + if (step.doc) { + const room = band.columns -| x; + if (room < min_width) continue; + placed.width = room; + placed.rows = try wrap(arena, tab, step.rows, room -| 1, band.height); + } + placed.x = x; + x +|= placed.width + 2; + band.steps[kept] = placed; + kept += 1; + } + band.nsteps = kept; +} + +/// The display columns of the head's key cells, when they are all on the +/// tag's last row (the spines hang from there). +fn findSpines(band: *Band, p: *Pardes, arena: std.mem.Allocator, pane: *Pane, id: usize) !void { + const h = (try TagState.head(p, arena, pane)) orelse return; + const whole = try tagline.tagText(p, arena, pane); + const shown = try tagline.wrapTag(p.settings.tab, arena, whole, tagline.tagWidth(p, id)); + const lead = whole.len - h.text.len; + const last = shown.rows() -| 1; + for (h.spans[0..h.cells]) |span| { + const at = modal.positionAt(shown.text, shown.fromReal(lead + span.lo)); + if (at.row != last or band.nspines == max_spines) { + band.nspines = 0; + return; + } + band.spines[band.nspines] = @intCast(File.rawDisplayCol(p.settings.tab, modal.lineSlice(shown.text, at.row), at.col)); + band.nspines += 1; + } +} + +/// `rows` wrapped at `width` display columns, word by word, `height` rows +/// at most: a doc's paragraphs, a line each in its text (builtins.Doc), +/// each starting a row (a newline drawn in a row was a `�`). +fn wrap(arena: std.mem.Allocator, tab: u16, rows: []const Row, width: u16, max: u16) ![]const Row { + var out: std.ArrayList(Row) = .empty; + for (rows) |whole| { + var paragraphs = std.mem.splitScalar(u8, whole.text, '\n'); + var row = whole; + while (paragraphs.next()) |text| : (row = .{ .text = "" }) { + if (out.items.len >= max) break; + row.text = text; + if (File.displayWidth(tab, row.text) <= width) { + try out.append(arena, row); + } else { + var rest = row.text; + while (rest.len > 0 and out.items.len < max) { + var cut = File.byteAtDisplay(tab, rest, width); + if (cut < rest.len) { + if (std.mem.lastIndexOfScalar(u8, rest[0..cut], ' ')) |space| { + if (space > 0) cut = space; + } + } + if (cut == 0) cut = modal.nextGrapheme(rest, 0); + try out.append(arena, .{ .text = std.mem.trimEnd(u8, rest[0..cut], " ") }); + rest = std.mem.trimStart(u8, rest[cut..], " "); + } + } + } + if (out.items.len >= max) break; + } + if (out.items.len > max) out.shrinkRetainingCapacity(max); + return out.items; +} + +/// One row of the band as text, and where each step's row starts in it. +pub const Line = struct { + text: []const u8, + parts: []const Part, + pub const Part = struct { col: u16, width: u16, row: Row }; +}; + +/// Row `y`: the spines, then each step's row, padded to its width, a rule +/// between steps. +pub fn line(band: *const Band, arena: std.mem.Allocator, tab: u16, y: u16) !Line { + var text: std.ArrayList(u8) = .empty; + var parts: std.ArrayList(Line.Part) = .empty; + var col: u16 = 0; + for (band.spines[0..band.nspines]) |spine| { + while (col < spine) : (col += 1) try text.append(arena, ' '); + try text.appendSlice(arena, "│"); + col += 1; + } + for (band.steps[0..band.nsteps], 0..) |step, i| { + if (i > 0) { + while (col + 2 < step.x) : (col += 1) try text.append(arena, ' '); + try text.appendSlice(arena, "│ "); + col += 2; + } + while (col < step.x) : (col += 1) try text.append(arena, ' '); + const per = if (step.two) (step.width - 1) / 2 else step.width; + const shown: u16 = if (step.two) levelRows(@intCast(step.rows.len)) else @intCast(step.rows.len); + var lane: u16 = 0; + while (lane < @as(u16, if (step.two) 2 else 1)) : (lane += 1) { + const k = y + lane * shown; + const start = step.x + lane * (per + 1); + while (col < start) : (col += 1) try text.append(arena, ' '); + if (y >= shown or k >= step.rows.len) continue; + const row = step.rows[k]; + const lead: []const u8 = if (step.doc) "" else if (row.on) "▶ " else if (row.mark) "• " else " "; + try text.appendSlice(arena, lead); + col += @intCast(File.displayWidth(tab, lead)); + try parts.append(arena, .{ .col = col, .width = per -| @as(u16, @intCast(File.displayWidth(tab, lead))), .row = row }); + const room = per -| @as(u16, @intCast(File.displayWidth(tab, lead))); + const cut = File.byteAtDisplay(tab, row.text, room); + try text.appendSlice(arena, row.text[0..cut]); + col += @intCast(File.displayWidth(tab, row.text[0..cut])); + } + } + return .{ .text = text.items, .parts = parts.items }; +} + +/// The word under column `col` of band row `y` of pane `id`, at the +/// tagline's pitch: what B2 executes and B3 looks at. +pub fn wordAt(p: *Pardes, arena: std.mem.Allocator, id: usize, y: u16, col: u16) !?[]const u8 { + const pane = p.panes[id] orelse return null; + const band = (try of(p, arena, pane, id)) orelse return null; + if (y >= band.height) return null; + const ln = try band.line(arena, p.settings.tab, y); + const at = File.rawAtDisplay(p.settings.tab, ln.text, col); + const b = tagline.wordBoundsAtCol(ln.text, at) orelse return null; + if (b.lo == b.hi) return null; + return ln.text[b.lo..b.hi]; +} + +fn bandLayer(p: *Pardes, id: usize) ?*pardes.Layer { + const layer = &p.surface.tag_layers[pardes.BAND_LAYER]; + return if (layer.rows > 0 and layer.kind == .band and layer.id == id) layer else null; +} + +fn layerRow(arena: std.mem.Allocator, layer: *const pardes.Layer, row: usize) ![]const u8 { + var out: std.ArrayList(u8) = .empty; + for (layer.cells[row * layer.cols ..][0..layer.cols]) |cell| try out.appendSlice(arena, cell.grapheme()); + return out.items; +} + +test "SPC Down unrolls the level into a band under the tag's text, the body pushed down and never drawn over; Up on its first row rolls it up" { + const Key = pardes.Key; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 }); + defer p.deinit(); + const pane = try p.setTestFile("one\ntwo\nthree\n"); + const id = p.view().active; + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + p.sync(); + const r = p.view().rects[id]; + const text_rows = pane.tag_rows; + const body_top = p.bodyTop(pane, r); + _ = try p.render(frame.allocator()); + try std.testing.expect(bandLayer(p, id) == null); + p.update(.{ .key = .{ .cp = ' ' } }); + p.update(.{ .key = .{ .cp = Key.down } }); + try std.testing.expect(p.view().tag_state.unrolled); + // SPC's top has more than nine children: two columns, and a doc. + try std.testing.expect(pane.band_rows >= doc_rows); + try std.testing.expectEqual(text_rows + pane.band_rows, pane.tag_rows); + try std.testing.expectEqual(body_top + pane.band_rows, p.bodyTop(pane, r)); + _ = frame.reset(.retain_capacity); + const s = try p.render(frame.allocator()); + const layer = bandLayer(p, id).?; + try std.testing.expectEqual(p.tagTop(pane, r) + text_rows, layer.viewport.y); + try std.testing.expectEqual(pane.band_rows, layer.viewport.h); + // The body region starts under the band: nothing is drawn over it. + const body = s.region(.body, id).?; + try std.testing.expectEqual(layer.viewport.y + layer.viewport.h, body.rect.y); + const first = try layerRow(frame.allocator(), layer, 0); + try std.testing.expect(std.mem.indexOf(u8, first, "│") != null); + try std.testing.expect(std.mem.indexOf(u8, first, "▶ b buffer…") != null); + // The grid has the same row, where the layer is. + var grid: std.ArrayList(u8) = .empty; + for (s.cells[@as(usize, layer.viewport.y) * s.cols ..][layer.viewport.x..][0..layer.viewport.w]) |cell| try grid.appendSlice(frame.allocator(), cell.grapheme()); + try std.testing.expect(std.mem.indexOf(u8, grid.items, "▶ b buffer…") != null); + // The head names the level and says how to roll it up. + try std.testing.expect(std.mem.endsWith(u8, try tagline.tagText(p, frame.allocator(), pane), " ␣ SPC ↑ roll up · ? field · esc")); + // Down moves the cursor; Up back to the first row, then rolls up. + p.update(.{ .key = .{ .cp = Key.down } }); + try std.testing.expectEqual(@as(u8, 'c'), p.view().tag_state.hi); + p.update(.{ .key = .{ .cp = Key.up } }); + try std.testing.expect(p.view().tag_state.unrolled); + p.update(.{ .key = .{ .cp = Key.up } }); + try std.testing.expect(!p.view().tag_state.unrolled); + try std.testing.expectEqual(@as(u16, 0), pane.band_rows); + try std.testing.expectEqual(body_top, p.bodyTop(pane, r)); + // Unrolled, Right enters the cursor's group and Left leaves it. + p.update(.{ .key = .{ .cp = Key.down } }); + p.update(.{ .key = .{ .cp = Key.right } }); + try std.testing.expectEqualStrings("b", p.view().leader_keys[0..p.view().leader_n]); + try std.testing.expect(p.view().tag_state.unrolled); + p.update(.{ .key = .{ .cp = Key.left } }); + try std.testing.expectEqual(@as(u8, 0), p.view().leader_n); + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expectEqual(@as(u16, 0), pane.band_rows); + try std.testing.expect(!p.view().tag_state.unrolled); +} + +test "a pane whose body would drop below four rows under its band borrows them from its column" { + const Key = pardes.Key; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 24 }); + defer p.deinit(); + _ = try p.setTestFile("one\n"); + const top = p.view().active; + p.newScratchBelow(top); + const low = p.view().active; + p.newScratchBelow(low); + p.view().active = low; + p.sync(); + const before = p.view().rects[low].h; + p.update(.{ .key = .{ .cp = ' ' } }); + p.update(.{ .key = .{ .cp = Key.down } }); + const pane = p.panes[low].?; + const r = p.view().rects[low]; + try std.testing.expect(r.h > before); + try std.testing.expect(r.h -| pane.tag_rows >= 4); + // The other panes dim; the one out of rest does not. + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + const s = try p.render(frame.allocator()); + const other = p.view().rects[top]; + try std.testing.expect(s.at(other.x + 3, other.y).style.dim); + try std.testing.expect(!s.at(r.x + 3, r.y).style.dim); + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expectEqual(before, p.view().rects[low].h); +} + +test "the band's words are read-only text: B2 runs one, the tag back at rest" { + const Key = pardes.Key; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 }); + defer p.deinit(); + _ = try p.setTestFile("one\n"); + const id = p.view().active; + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + for ([_]u21{ ' ', 't', Key.down }) |c| p.update(.{ .key = .{ .cp = c } }); + const s = try p.render(frame.allocator()); + const layer = bandLayer(p, id).?; + // Find `Wrap` in the grid's copy of the band. + const at = found: for (0..layer.rows) |row| { + const y = layer.viewport.y + row; + var x: u16 = layer.viewport.x; + while (x + 4 < layer.viewport.x + layer.viewport.w) : (x += 1) { + const cells = s.cells[@as(usize, y) * s.cols + x ..][0..4]; + if (std.mem.eql(u8, cells[0].grapheme(), "W") and std.mem.eql(u8, cells[1].grapheme(), "r") and std.mem.eql(u8, cells[2].grapheme(), "a") and std.mem.eql(u8, cells[3].grapheme(), "p")) + break :found .{ x + 1, @as(u16, @intCast(y)) }; + } + } else return error.NoWrapInTheBand; + const wrapped = p.settings.wrap; + p.update(.{ .mouse = .{ .button = .middle, .kind = .press, .col = at[0], .row = at[1] } }); + p.update(.{ .mouse = .{ .button = .middle, .kind = .release, .col = at[0], .row = at[1] } }); + try std.testing.expect(p.settings.wrap != wrapped); + try std.testing.expect(p.view().prefix == .none and !p.view().tag_state.unrolled); +} + +test "a doc's paragraphs are rows of their own: no newline in a band's row" { + const Key = pardes.Key; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 }); + defer p.deinit(); + _ = try p.setTestFile("one\n"); + const id = p.view().active; + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + const a = frame.allocator(); + // SPC b b is Panes, whose documentation has three paragraphs. + for ([_]u21{ ' ', 'b', Key.down }) |c| p.update(.{ .key = .{ .cp = c } }); + const band = (try of(p, a, p.panes[id].?, id)).?; + var docs: usize = 0; + for (band.steps[0..band.nsteps]) |step| for (step.rows) |row| { + try std.testing.expect(std.mem.indexOfScalar(u8, row.text, '\n') == null); + if (step.doc) docs += 1; + }; + try std.testing.expect(docs > 2); +} diff --git a/core/Core.zig b/core/Core.zig index 92c81ba6..296f4159 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -188,6 +188,9 @@ pub const View = struct { window_pick: ?usize = null, leader_keys: [4]u8 = undefined, leader_n: u8 = 0, + /// Its tag out of rest: the which-key level, the typing states + /// (TagState.zig). + tag_state: pardes.TagState = .{}, /// The keyboard is on a header: a column's tag, or the workspace's. header: ?Header = null, /// A mouse sweep is extending the focused header's selection. @@ -397,6 +400,9 @@ lsp_ask: Ask = .{}, pipe: Pipe = .{}, /// A query pane's Grep, and its Find's listing, on a worker (Stream.zig). stream: Stream = .{}, +/// The pickers: the one live in a view's tag, and the last ones rolled +/// up, which their list words and Resume reopen (Pick.zig). +picks: [pardes.Pick.max_lists]?*pardes.Pick = @splat(null), /// The panes' `Changes` (jj.zig): what was asked of jj, and what it /// answered for each pane, by its serial: the session's, not a field of /// every pane (a digest and a rollback copy walk every pane's fields at @@ -927,6 +933,7 @@ pub fn deinit(p: *Pardes) void { look.cancelLookHover(p); if (p.repl_ask) |ask| p.gpa.free(ask.text); for (0..MAX_PANES) |id| p.dropPendingWrite(id); + pardes.Pick.deinitAll(p); // The panes, then those retired these last two frames. inline for (.{ &p.panes, &p.retired_panes.previous, &p.retired_panes.current }) |slots| for (slots) |*slot| if (slot.*) |pane| { pardes.panes.teardownPane(p, pane); @@ -1809,6 +1816,7 @@ fn updateInner(p: *Pardes, ev: Event) void { for (p.panes) |slot| if (slot) |pane| pane.places.settle(p, pane, ev == .tick); // Each live query pane's rows, made from what changed this step. pardes.panes.Query.produceAll(p, ev == .tick, ev == .key); + pardes.Pick.produceAll(p, ev == .tick); _ = p.scratch.reset(.{ .retain_with_limit = memory.limits.scratch_kept }); p.sync(); p.fsReport(); @@ -1998,11 +2006,12 @@ pub fn sync(p: *Pardes) void { pane.tag_lead = lead; } // A row per shown row: the tag's lines wrapped at its width. - var lines = std.mem.count(u8, tagline.curTail(pane), "\n") + 1; + const tail = tagline.shownTail(p, wa, pane) catch tagline.curTail(pane); + var lines = std.mem.count(u8, tail, "\n") + 1; var wanted = lines; var caret_row: usize = @intCast(@max(0, pane.tag.cur_row)); if (prefix) |made| wrap: { - const whole = std.mem.concat(wa, u8, &.{ made, tagline.curTail(pane) }) catch break :wrap; + const whole = std.mem.concat(wa, u8, &.{ made, tail }) catch break :wrap; const shown = tagline.wrapTag(p.settings.tab, wa, whole, tagline.tagWidth(p, id)) catch break :wrap; lines = shown.rows(); // Collapsed, one row, as acme's Tagup sets taglines to 1 @@ -2012,6 +2021,15 @@ pub fn sync(p: *Pardes) void { caret_row = std.mem.count(u8, shown.text[0..@min(shown.fromReal(cur), shown.text.len)], "\n"); } if (!pane.tag_expanded) wanted = 1; + // Out of rest the head is the tag's text (TagState), and the tag + // keeps the rows its own text takes at least: a head shorter than + // it (a root's key cell, before its level shows) moved the body up + // and back down a moment later; a terminal's exactly those, its pty + // its body (a resize the program under it saw at every C-w and SPC). + if (pardes.TagState.hostOf(p) == id) { + const rest = layout.wantedTagRows(p, id); + wanted = if (pane.isTerminal()) rest else @max(wanted, rest); + } pane.tag_rows = @intCast(@min(wanted, MAX_TAG_ROWS, @max(BOX_H, r.h -| 1))); if (pane.collapsed) pane.tag_rows = BOX_H; if (pane.focus == .tag and pane.prompt != .name) { @@ -2019,8 +2037,12 @@ pub fn sync(p: *Pardes) void { var top: usize = pane.tag_top; if (cur < top) top = cur; if (cur >= top + pane.tag_rows) top = cur + 1 - pane.tag_rows; - pane.tag_top = @intCast(@min(top, lines - pane.tag_rows)); + pane.tag_top = @intCast(@min(top, lines -| pane.tag_rows)); } else pane.tag_top = 0; + // The band unrolled under the tag's text pushes the body down: + // the tag's rows, as everything under them counts them. + pane.band_rows = if (pane.collapsed) 0 else @min(pardes.Band.takes(p, id), r.h -| pane.tag_rows); + pane.tag_rows += pane.band_rows; const cols = @max(1, r.w -| config.GUTTER); // The tag steals the top rows. The pty is what the pane shows // (layout keeps a terminal two body rows where the window has @@ -2142,7 +2164,7 @@ pub fn nextWake(p: *const Pardes) ?u64 { for (p.panes) |slot| if (slot) |pane| if (pane.places.busy(pane)) return next; const kinds = pardes.Kind.wake(p); if (kinds) |due| if (due <= next) return next; - if (pardes.panes.Query.busy(p)) return next; + if (pardes.panes.Query.busy(p) or pardes.Pick.busy(p)) return next; // A typed Grep waiting out its pause. const streaming = p.stream.wake(next); if (streaming) |due| if (due <= next) return next; @@ -2163,6 +2185,11 @@ pub fn nextWake(p: *const Pardes) ?u64 { const wait = @max(1, (pane.question_due_ns - p.clock.stepped_ns + frame_ns - 1) / frame_ns); frames = if (frames) |soonest| @min(soonest, wait) else wait; }; + // A which-key level shows at the end of its root's delay (TagState). + if (pardes.TagState.wake(p)) |due| { + const wait = @max(1, (due - p.clock.stepped_ns + frame_ns - 1) / frame_ns); + frames = if (frames) |soonest| @min(soonest, wait) else wait; + } // A paste's Enter waiting on its REPL goes at the end of its wait, // a time on the clock: the frames from `stepped_ns` that reach it. for (p.panes) |slot| if (slot) |pane| if (pane.repl_enter > 0) { @@ -2204,6 +2231,8 @@ fn advanceInner(p: *Pardes, now_ns: u64) void { for (p.panes) |slot| if (slot) |pane| if (pane.question_due_ns == Pane.question_asked) { pane.question_due_ns = now_ns + config.del_question_delay_ns; }; + // A which-key root struck since: its level's delay from now. + pardes.TagState.dated(p, now_ns); const frame = frame_ns; var moving: u32 = 0; // The session's ticks are the recording session's: a picture still @@ -2621,12 +2650,16 @@ test "TreeContext rows in the tag style keep the message rows" { p.sync(); _ = try p.render(p.scratch.allocator()); try std.testing.expectEqual(full_height, p.surface.body_layers[0].viewport.h); - // ...and the leader's chip is an overlay that takes nothing either. + // ...and the leader's chip (a shown level's last leaf) is an overlay + // at the body's top (the level itself wraps the tag: TagState). const r = p.view().rects[0]; p.view().prefix = .leader; + p.view().leader_n = 0; + p.view().tag_state.used[0] = 'q'; + p.view().tag_state.due_ns = 1; + p.clock.now_ns = 1; p.sync(); _ = try p.render(p.scratch.allocator()); - try std.testing.expectEqual(full_height, p.surface.body_layers[0].viewport.h); const band = for (p.surface.tagLayers()) |*layer| { if (layer.rows != 0 and layer.kind == .notice) break layer; } else return error.NoNoticeBand; diff --git a/core/Field.zig b/core/Field.zig new file mode 100644 index 00000000..7b8ea399 --- /dev/null +++ b/core/Field.zig @@ -0,0 +1,142 @@ +//! A field typed in a tag's head (walk UI, pick-ui SPEC.md §3.2, the typing +//! row): one line of text and its caret, in a fixed buffer, each view's +//! own (TagState.field). Help's query, a picker's, a prompt's: the keys +//! that edit it are a line editor's (readline's, helix's prompt's), and +//! the state that owns it takes the rest (Enter, Esc, the arrows a list +//! steps with). +const Field = @This(); + +const std = @import("std"); +const pardes = @import("root.zig"); +const modal = @import("modal.zig"); +const Key = pardes.Key; + +/// The longest field, in bytes: a query, a command line, a pattern. +pub const max = 256; + +buf: [max]u8 = undefined, +len: u16 = 0, +/// A byte offset in the text, at a character's start. +caret: u16 = 0, + +pub const replica = .{ .len = .{.{ "buf", "len" }} }; + +pub fn text(f: *const Field) []const u8 { + return f.buf[0..f.len]; +} + +pub fn clear(f: *Field) void { + f.len = 0; + f.caret = 0; +} + +/// `s` in place of the text, the caret at its end (a history's line). +pub fn set(f: *Field, s: []const u8) void { + var n = @min(s.len, max); + while (n > 0 and n < s.len and s[n] & 0xC0 == 0x80) n -= 1; + @memcpy(f.buf[0..n], s[0..n]); + f.len = @intCast(n); + f.caret = f.len; +} + +/// An editing key taken: true, the text or the caret moved (or a key that +/// would have, at an edge). False for a key the field has no use for, +/// which its owner takes. +pub fn key(f: *Field, k: Key) bool { + const t = f.text(); + const ctrl = k.ctrl and !k.alt; + const alt = k.alt and !k.ctrl; + const plain = !k.ctrl and !k.alt; + if (plain and k.cp == Key.backspace or ctrl and k.cp == 'h') { + if (f.caret > 0) f.cut(prev(t, f.caret), f.caret); + } else if (plain and k.cp == Key.delete or ctrl and k.cp == 'd') { + if (f.caret < f.len) f.cut(f.caret, @intCast(modal.nextGrapheme(t, f.caret))); + } else if (plain and k.cp == Key.left or ctrl and k.cp == 'b') { + f.caret = prev(t, f.caret); + } else if (plain and k.cp == Key.right or ctrl and k.cp == 'f') { + if (f.caret < f.len) f.caret = @intCast(modal.nextGrapheme(t, f.caret)); + } else if (plain and k.cp == Key.home or ctrl and k.cp == 'a') { + f.caret = 0; + } else if (plain and k.cp == Key.end or ctrl and k.cp == 'e') { + f.caret = f.len; + } else if (ctrl and k.cp == 'u') { + f.cut(0, f.caret); + } else if (ctrl and k.cp == 'k') { + f.cut(f.caret, f.len); + } else if (ctrl and k.cp == 'w' or alt and k.cp == Key.backspace) { + f.cut(wordBack(t, f.caret), f.caret); + } else if (alt and k.cp == 'b') { + f.caret = wordBack(t, f.caret); + } else if (alt and k.cp == 'f') { + f.caret = wordOn(t, f.caret); + } else if (plain and k.cp >= 0x20 and k.cp != Key.backspace and k.cp < 0xF0000) { + var utf: [4]u8 = undefined; + const n = std.unicode.utf8Encode(k.cp, &utf) catch return true; + f.insert(if (k.text.len > 0) k.text else utf[0..n]); + } else return false; + return true; +} + +/// `s` typed at the caret; what does not fit is dropped whole. +pub fn insert(f: *Field, s: []const u8) void { + if (f.len + s.len > max) return; + std.mem.copyBackwards(u8, f.buf[f.caret + s.len .. f.len + s.len], f.buf[f.caret..f.len]); + @memcpy(f.buf[f.caret..][0..s.len], s); + f.len += @intCast(s.len); + f.caret += @intCast(s.len); +} + +fn cut(f: *Field, lo: u16, hi: u16) void { + std.mem.copyForwards(u8, f.buf[lo .. f.len - (hi - lo)], f.buf[hi..f.len]); + f.len -= hi - lo; + f.caret = lo; +} + +fn prev(t: []const u8, at: u16) u16 { + var i = at; + while (i > 0) { + i -= 1; + if (t[i] & 0xC0 != 0x80) break; + } + return i; +} + +fn wordBack(t: []const u8, at: u16) u16 { + var i = at; + while (i > 0 and t[i - 1] == ' ') i -= 1; + while (i > 0 and t[i - 1] != ' ') i -= 1; + return i; +} + +fn wordOn(t: []const u8, at: u16) u16 { + var i = at; + while (i < t.len and t[i] == ' ') i += 1; + while (i < t.len and t[i] != ' ') i += 1; + return i; +} + +test "a field types, moves and deletes as a line editor does" { + var f: Field = .{}; + for ("find me") |c| try std.testing.expect(f.key(.{ .cp = c })); + try std.testing.expectEqualStrings("find me", f.text()); + try std.testing.expect(f.key(.{ .cp = 'w', .ctrl = true })); + try std.testing.expectEqualStrings("find ", f.text()); + try std.testing.expect(f.key(.{ .cp = Key.home })); + try std.testing.expect(f.key(.{ .cp = '>' })); + try std.testing.expectEqualStrings(">find ", f.text()); + try std.testing.expectEqual(@as(u16, 1), f.caret); + try std.testing.expect(f.key(.{ .cp = Key.backspace })); + try std.testing.expectEqualStrings("find ", f.text()); + try std.testing.expect(f.key(.{ .cp = 0x65e5 })); // 日 + try std.testing.expect(f.key(.{ .cp = Key.left })); + try std.testing.expectEqual(@as(u16, 0), f.caret); + try std.testing.expect(f.key(.{ .cp = Key.delete })); + try std.testing.expectEqualStrings("find ", f.text()); + try std.testing.expect(f.key(.{ .cp = 'k', .ctrl = true })); + try std.testing.expectEqualStrings("", f.text()); + // Enter, Esc and the arrows a list steps with are its owner's. + try std.testing.expect(!f.key(.{ .cp = Key.enter })); + try std.testing.expect(!f.key(.{ .cp = Key.escape })); + try std.testing.expect(!f.key(.{ .cp = Key.down })); + try std.testing.expect(!f.key(.{ .cp = 'n', .ctrl = true })); +} diff --git a/core/File.zig b/core/File.zig index f611bbbd..18745930 100644 --- a/core/File.zig +++ b/core/File.zig @@ -1312,6 +1312,8 @@ fn edit(p: *Pardes, f: *State, off: usize, len: usize, bytes_in: []const u8, who } f.revision +%= 1; f.splice = .{ .revision = f.revision, .head = span.head, .tail = span.tail, .old_len = old_len }; + // Edited, a reading pane is held (pick-ui SPEC §6.5). + if (how == .edit) pardes.Trail.edited(p, f); if (!told) { // The file's text is as it was: as clean as it was, its // declarations still its own. diff --git a/core/Jump.zig b/core/Jump.zig index 4a7c1e40..b28698ee 100644 --- a/core/Jump.zig +++ b/core/Jump.zig @@ -274,6 +274,11 @@ pub fn trackJump(p: *Pardes) void { /// always have, at the newest entry. pub fn jumpBy(p: *Pardes, delta: i32) void { const v = p.view(); + // A reading pane's walk first (pick-ui SPEC §6.4). Past its newest + // step, Ctrl-i steps the Walk queue a picker left (Pick.stepQueue); + // then the jump list's. + if (pardes.Trail.walkBy(p, v.active, delta)) return; + if (delta > 0 and pardes.Pick.stepQueue(p, v.active)) return; const older = delta < 0; // At an end of the list: said, not a step that silently does nothing. if (v.jumps.n == 0 or (older and v.jumps.cur == 0) or (!older and v.jumps.cur + 1 >= v.jumps.n)) diff --git a/core/Layer.zig b/core/Layer.zig index 79552631..df86821a 100644 --- a/core/Layer.zig +++ b/core/Layer.zig @@ -20,8 +20,9 @@ const Layer = @This(); /// chord -- carried as a tagline-shaped band so it gets the tagline's height, /// small-font metrics, band offset and border instead of being a body-grid row /// wearing a tagline font. +/// `band` is the rows a pane's tag unrolls into below it (Band.zig). /// `notice_row` is the window's foot row, the live messages' index. -pub const Kind = enum(u8) { workspace, column, pane, notice, body, notice_row }; +pub const Kind = enum(u8) { workspace, column, pane, notice, body, band, notice_row }; pub const Metrics = struct { body_w: u16 = 1, diff --git a/core/Messages.zig b/core/Messages.zig index a26cbad9..3fef1842 100644 --- a/core/Messages.zig +++ b/core/Messages.zig @@ -190,18 +190,14 @@ pub const LoggedMessage = struct { } }; -/// `SPC` plus the chord keys typed so far, spaced out the way the help -/// index spells a leader path. -fn leaderText(p: *const Pardes, buf: *[16]u8) []const u8 { - buf.* = @splat(' '); - @memcpy(buf[0..3], "SPC"); - var end: usize = 3; - for (p.view().leader_keys[0..p.view().leader_n]) |ch| { - if (end + 2 > buf.len) break; - buf[end + 1] = ch; - end += 2; - } - return buf[0..end]; +/// The room the leader band's line takes (TagState.lastUsed): a leaf's +/// key, word and summary (builtins.summary_max), and "(last used here)". +pub const leader_room = 192; + +/// The leaf the current which-key level ran last, and what it does: the +/// line under a rolled level (walk UI SPEC §3.7). +fn leaderText(p: *const Pardes, buf: *[leader_room]u8) []const u8 { + return pardes.TagState.lastUsed(p, p.view(), buf) orelse ""; } pub const Message = struct { @@ -748,7 +744,7 @@ pub fn noticeRow(p: *const Pardes, width: usize, out: *[notice_row_cap]u8) Row { /// What notice band `i` says. The grid pass and the band layers both /// read it here, so a terminal and a pixel shell show the same line. -pub fn noticeText(p: *const Pardes, pane: *const Pane, i: usize, leader_buf: *[16]u8) []const u8 { +pub fn noticeText(p: *const Pardes, pane: *const Pane, i: usize, leader_buf: *[leader_room]u8) []const u8 { return switch (pane.notices.kinds[i]) { .leader => leaderText(p, leader_buf), .prompt => pane.promptText() orelse "", @@ -929,7 +925,7 @@ pub fn collectNotices(p: *Pardes, pane: *Pane, r: Rect, id: usize) void { // draws, and a chip narrower than its text there would clip it. const tx = r.x + config.GUTTER; const tw = r.w -| config.GUTTER; - var leader_buf: [16]u8 = undefined; + var leader_buf: [leader_room]u8 = undefined; for (0..pane.notices.len) |i| { const chip = panes.File.displayWidth(p.settings.tab, noticeText(p, pane, i, &leader_buf)) + 2; pane.notices.left[i] = if (tw == 0) std.math.maxInt(u16) else tx + tw - @as(u16, @intCast(@min(chip, tw))); @@ -942,7 +938,8 @@ pub fn collectNotices(p: *Pardes, pane: *Pane, r: Rect, id: usize) void { pub fn bands(p: *const Pardes, v: *const Pardes.View, pane: *const Pane, tag_rows: u16, r: Rect, id: usize) Pane.Notices { var n: Pane.Notices = .{}; if (r.w <= config.GUTTER or r.h <= tag_rows) return n; - if (id == v.active and v.prefix == .leader) n.push(.leader); + var used_buf: [leader_room]u8 = undefined; + if (id == v.active and pardes.TagState.lastUsed(p, v, &used_buf) != null) n.push(.leader); // Del's question shows once its delay is up: answered before that, it // was never there. const del_waiting = pane.prompt == .del_side and pane.question_due_ns > p.clock.now_ns; diff --git a/core/Names.zig b/core/Names.zig index 2fbbec37..47165f52 100644 --- a/core/Names.zig +++ b/core/Names.zig @@ -233,7 +233,7 @@ fn bonusAt(text: []const u8, j: usize) i32 { /// `text`. Terms split on spaces are ANDed; smart case per term. With /// `marks`, the bytes matched are written there, ascending (the table they /// are backtracked through is `dp_trace`). -fn match(query: []const u8, text_in: []const u8, lower_in: []const u8, base: usize, marks: ?[]u16, marks_len: ?*usize) ?i32 { +pub fn match(query: []const u8, text_in: []const u8, lower_in: []const u8, base: usize, marks: ?[]u16, marks_len: ?*usize) ?i32 { const text = text_in[0..@min(text_in.len, max_text)]; const lower = lower_in[0..text.len]; var total: i32 = 0; diff --git a/core/Output.zig b/core/Output.zig index a7398ccf..32a00863 100644 --- a/core/Output.zig +++ b/core/Output.zig @@ -491,16 +491,23 @@ pub fn fillRows(p: *Pardes, id: usize, dir: []const u8, from: Origin, name: ?[]c pub fn openJumps(p: *Pardes, id: usize) !void { var out: std.Io.Writer.Allocating = .init(p.gpa); errdefer out.deinit(); + try jumpsText(p, &out.writer); + try refillOrOpen(p, id, .{ .cmd = .Jumplist }, try out.toOwnedSlice()); +} + +/// The live view's jump list as a +Jumps lists it, a place a row, the +/// oldest first (its picker's rows too, Pick.zig). +pub fn jumpsText(p: *Pardes, w: *std.Io.Writer) !void { for (p.view().jumps.list[0..p.view().jumps.n]) |j| { // A closed file's entry: marked, and a look at it opens it again. if (j.serial == 0) { const e = p.recentByHash(j.path_hash) orelse continue; // A kind's place has no Look's column. if (j.place.len > 0) { - try out.writer.print("{s}:{d} (closed)\n", .{ e.path, @max(1, j.line) }); + try w.print("{s}:{d} (closed)\n", .{ e.path, @max(1, j.line) }); continue; } - try out.writer.print("{s}:{d}:{d} (closed)\n", .{ e.path, @max(1, j.line), @max(1, j.col) }); + try w.print("{s}:{d}:{d} (closed)\n", .{ e.path, @max(1, j.line), @max(1, j.col) }); continue; } const jp = p.panes[j.pane] orelse continue; @@ -520,13 +527,12 @@ pub fn openJumps(p: *Pardes, id: usize) !void { var cut = @min(what.len, 120); while (cut > 0 and cut < what.len and what[cut] & 0xc0 == 0x80) cut -= 1; if (j.line == 0) - try out.writer.print("{s} {s}\n", .{ loc, what[0..cut] }) + try w.print("{s} {s}\n", .{ loc, what[0..cut] }) else if (j.place.len > 0) - try out.writer.print("{s}:{d} {s}\n", .{ loc, j.line, what[0..cut] }) + try w.print("{s}:{d} {s}\n", .{ loc, j.line, what[0..cut] }) else - try out.writer.print("{s}:{d}:{d} {s}\n", .{ loc, j.line, j.col, what[0..cut] }); + try w.print("{s}:{d}:{d} {s}\n", .{ loc, j.line, j.col, what[0..cut] }); } - try refillOrOpen(p, id, .{ .cmd = .Jumplist }, try out.toOwnedSlice()); } /// The state file's dumps (Db.listDumps: label, date, size, pane count, diff --git a/core/Pick.zig b/core/Pick.zig new file mode 100644 index 00000000..7913a7e0 --- /dev/null +++ b/core/Pick.zig @@ -0,0 +1,1781 @@ +//! A picker (pick-ui SPEC.md §5, direction E): a list of places, panes or +//! names unrolled in the tag of the pane its Enter lands in (§3.5): the +//! asking pane when it reads, else its reader, made for the picker when it +//! has none and taken away again by Esc. Its query is typed in that tag's +//! field (TagState.field), its rows hang in the band under it (Band.zig) +//! eleven at a time around the cursor, and that pane's body is the preview: +//! the current row's file at its line, its own text set aside meanwhile and +//! put back when the picker rolls up. +//! +//! The rows are Query.zig's producers', re-presented: names scored by +//! Names.zig a frame's count at a time (Find's listing from the disk +//! engine's worker, Recent, Panes, the asking text's declarations, the +//! rows a language server answered, the jump list), Grep's lines from the +//! disk engine's worker (Stream.zig: its pause, its cap). A frame makes +//! only the rows it shows, in its arena. +//! +//! A picker is the session's, named by a serial drawn from the panes' +//! counter (`id`), so the disk engine's `target` names it as it names a +//! pane; one is live in a view's tag (TagState.pick), and the last +//! `max_lists` are kept after they roll up. +const Pick = @This(); + +const std = @import("std"); +const pardes = @import("root.zig"); +const config = @import("config.zig"); +const layout = @import("layout.zig"); +const look = @import("look.zig"); +const panes = @import("panes.zig"); +const filesystem = @import("fs.zig"); +const exec = @import("exec.zig"); +const bindings = @import("bindings.zig"); +const Kind = @import("Kind.zig"); +const Names = @import("Names.zig"); +const Stream = @import("Stream.zig"); +const Trail = @import("Trail.zig"); +const TagState = @import("TagState.zig"); +const Band = @import("Band.zig"); +const Query = panes.Query; +const File = panes.File; +const Output = panes.Output; +const Pardes = pardes.Pardes; +const Pane = panes.Pane; +const Key = pardes.Key; + +/// What a picker lists (SPEC §5.1, the sources pardes has): the files +/// under the asking pane's directory, the lines of them holding the +/// query, the files opened lately, the panes, the asking text's +/// declarations, the lines holding the query in every open pane (All, its +/// places in each), the jump list, and rows handed over (a language +/// server's answer), titled by their word. +pub const Source = enum { find, grep, recent, panes, symbols, all, jumplist, list }; + +/// Each source's word in the tag and the leader keys of the builtin that +/// opens it, its key cells (`␣ f Find`). +const words = std.EnumArray(Source, struct { word: []const u8, keys: []const u8 }).init(.{ + .find = .{ .word = "Find", .keys = "f" }, + .grep = .{ .word = "Grep", .keys = "f" }, + .recent = .{ .word = "Recent", .keys = "f" }, + .panes = .{ .word = "Panes", .keys = "b" }, + .symbols = .{ .word = "Symbols", .keys = "s" }, + .all = .{ .word = "All", .keys = "" }, + .jumplist = .{ .word = "Jumplist", .keys = "j" }, + .list = .{ .word = "List", .keys = "l" }, +}); + +/// The pickers kept after they roll up, for their list words and Resume. +pub const max_lists = 8; +/// Refinements a picker stacks (C-SPC). +pub const max_refine = 3; + +pub const replica = .{ .len = .{.{ "refined", "nrefined" }} }; + +/// Its serial: the disk engine's target, a list word's index. +id: u32, +source: Source, +/// Its word, `Find`, or a list's own (`Refs`). +word: Kind.Buf(24) = .{}, +/// The leader keys under which its builtin is, drawn as key cells. +keys: Kind.Buf(4) = .{}, +/// Where Find and Grep look; what the rows' paths are relative to. +dir: Kind.Buf(4096) = .{}, +/// The pane that asked, and the one its Enter lands in, by serial. +owner: u32 = 0, +landing: u32 = 0, +/// The landing pane was made for it: Esc takes it away. +made: bool = false, +/// Unrolled in a view's tag now. +unrolled: bool = false, +names: Names = .{}, +/// A Grep's lines, as the disk engine sends them (Query.take). +found: std.ArrayList(Query.Found) = .empty, +found_bytes: std.ArrayList(u8) = .empty, +/// A list's rows, as they were handed over (`path:line:col text`). +rows: []u8 = &.{}, +/// The query and the cursor as it rolled up (live, they are its view's +/// field and cursor). +query: Kind.Buf(256) = .{}, +at: u32 = 0, +/// The landing pane's own text while its body previews (a reading pane: +/// put back when the picker rolls up), and its caret and top then (put +/// back too when it previewed its own file, with nothing set aside). +aside: ?File.State = null, +aside_row: i32 = 0, +aside_col: i32 = 0, +aside_top: usize = 0, +/// The row the preview shows (`no_row`: none yet); asked again on the +/// frame after the cursor moves, never on the key that moved it. +shown: u32 = no_row, +/// The preview on (M-p). +previews: bool = true, +/// Marked rows (Tab), by what each is (`idOf`), in order. +marks: std.ArrayList(u32) = .empty, +/// The queries refined from (C-SPC), each with the names it listed then: +/// Backspace on an empty field goes back to them. +refined: [max_refine]Refined = undefined, +nrefined: u8 = 0, +/// The band's second step: the sources to switch to (M-h), the acts on +/// the picked rows (M-l, M-Enter); `edit`: the field is the act Edit's +/// command, the query kept in `query`. +spine: enum(u8) { rows, sources, acts, edit } = .rows, +/// The act step's cursor, among the acts offered. +act_at: u8 = 0, +/// The places Walk queued (C-i steps them in the landing pane): each a +/// path in `queue_bytes`, its line and column. +queue: std.ArrayList(Queued) = .empty, +queue_bytes: std.ArrayList(u8) = .empty, +queue_at: u32 = 0, + +pub const Queued = struct { path: u32, len: u16, line: u32, col: u32 }; + +const Refined = struct { query: Kind.Buf(64) = .{}, names: Names = .{} }; + +const no_row = std.math.maxInt(u32); + +pub fn deinit(pk: *Pick, gpa: std.mem.Allocator) void { + for (pk.refined[0..pk.nrefined]) |*r| r.names.deinit(gpa); + pk.marks.deinit(gpa); + pk.queue.deinit(gpa); + pk.queue_bytes.deinit(gpa); + pk.names.deinit(gpa); + pk.found.deinit(gpa); + pk.found_bytes.deinit(gpa); + gpa.free(pk.rows); +} + +/// Whether a search a builtin asks for from pane `id` is a picker in the +/// tag (SPEC §14.3 phase 4): in a session whose jumps walk, from the +/// keyboard or a click, never a script's (a 9P write's: the query pane, +/// whose rows it reads back, and whose `not found` it hears). +pub fn asked(p: *const Pardes) bool { + return p.settings.jumps == .walk and !p.fs.serving; +} + +/// Picker `id`, kept or live. +pub fn byId(p: *const Pardes, id: u32) ?*Pick { + if (id == 0) return null; + for (p.picks) |slot| if (slot) |pk| if (pk.id == id) return pk; + return null; +} + +/// The picker live in the live view's tag. +pub fn live(p: *const Pardes) ?*Pick { + const s = &p.view().tag_state; + if (s.kind != .pick) return null; + const pk = byId(p, s.pick) orelse return null; + return if (pk.unrolled) pk else null; +} + +/// A picker of `source` asked from pane `from`, unrolled in the tag of the +/// pane its Enter will land in (SPEC §3.5), its field `query`. `rows` are +/// a list's (`source` `list`, titled `word`). +pub fn open(p: *Pardes, from: usize, source: Source, word: []const u8, query: []const u8, rows: []const u8) void { + const asker = p.panes[from] orelse return; + TagState.toRest(p); + const pk = make(p, source) catch |err| return p.reportError(.at(from), "pick", err); + pk.word.set(if (word.len > 0) word else words.get(source).word); + pk.keys.set(words.get(source).keys); + pk.dir.set(Pardes.paneDir(asker)); + pk.rows = p.gpa.dupe(u8, rows) catch |err| return p.reportError(.at(from), "pick", err); + hostIn(p, pk, from) catch |err| return p.reportError(.at(from), "pick", err); + unroll(p, pk, query); + start(p, pk); + filter(p, pk); +} + +/// A new picker in the ring, the oldest kept one dropped for it. +fn make(p: *Pardes, source: Source) !*Pick { + var slot: ?usize = null; + for (p.picks, 0..) |s, i| if (s == null) { + slot = i; + break; + }; + if (slot == null) { + // The oldest not live. + var oldest: ?usize = null; + for (p.picks, 0..) |s, i| if (s) |pk| if (!pk.unrolled and (oldest == null or pk.id < p.picks[oldest.?].?.id)) { + oldest = i; + }; + const i = oldest orelse return error.NoPickerSlots; + p.picks[i].?.deinit(p.gpa); + p.gpa.destroy(p.picks[i].?); + p.picks[i] = null; + slot = i; + } + const pk = try p.gpa.create(Pick); + p.next_serial += 1; + pk.* = .{ .id = p.next_serial, .source = source }; + p.picks[slot.?] = pk; + return pk; +} + +/// Picker `pk` asked from pane `from`: the pane it lands in is `from` when +/// it reads; its reader when it is held and has one; else a pane made under +/// it as its reader would be, empty until the preview fills it. The +/// keyboard stays where it was: the landing pane is the tag's host. +fn hostIn(p: *Pardes, pk: *Pick, from: usize) !void { + const asker = p.panes[from].?; + pk.owner = asker.serial; + pk.made = false; + const reader = if (Trail.reading(p, asker)) from else Trail.readerOf(p, asker); + pk.landing = p.panes[reader orelse try landingFor(p, from)].?.serial; + pk.made = reader == null; + p.view().active = from; +} + +/// A pane made under pane `from` for a picker, where its reader goes. +fn landingFor(p: *Pardes, from: usize) !usize { + const asker = p.panes[from].?; + const free = p.freeSlot() orelse return error.NoPaneSlots; + const content = try p.gpa.dupe(u8, ""); + errdefer p.gpa.free(content); + _ = try Output.open(p, free, Pardes.paneDir(asker), .preview, "", content); + layout.placeNew(p, from, from, free, .reader); + layout.compute(p); + return free; +} + +/// Picker `pk` live in the live view's tag: its host its landing pane, its +/// field `query`, the cursor where it was. +fn unroll(p: *Pardes, pk: *Pick, query: []const u8) void { + const v = p.view(); + const s = &v.tag_state; + s.kind = .pick; + s.pick = pk.id; + s.host = pk.landing; + s.field.set(query); + s.rows = .{ .at = @intCast(@min(pk.at, std.math.maxInt(u16))) }; + pk.unrolled = true; + pk.shown = no_row; + if (p.paneBySerial(pk.landing)) |id| { + s.previewing.set(id); + const pane = p.panes[id].?; + pk.aside_row = pane.body.cur_row; + pk.aside_col = pane.body.cur_col; + pk.aside_top = if (pane.file) |f| f.scroll else 0; + } +} + +/// Its source begun: the names gathered, a listing started. +fn start(p: *Pardes, pk: *Pick) void { + pk.names.reset(); + pk.found.clearRetainingCapacity(); + pk.found_bytes.clearRetainingCapacity(); + const dir = pk.dir.slice(); + switch (pk.source) { + .find => { + Stream.query(p, pk.id, .files, "", dir, .now) catch |err| return p.reportError(.at(p.view().active), "pick", err); + if (p.fs.serving) Stream.step(p); + }, + .grep, .all => {}, + .recent => Query.gather(p, &pk.names, .recent, dir, null, null), + .panes => Query.gather(p, &pk.names, .panes, dir, null, null), + .symbols => Query.gather(p, &pk.names, .symbols, dir, null, p.paneBySerial(pk.owner)), + .jumplist => { + var out: std.Io.Writer.Allocating = .init(p.gpa); + defer out.deinit(); + Output.jumpsText(p, &out.writer) catch return; + addRows(p, pk, out.written()); + }, + .list => addRows(p, pk, pk.rows), + } +} + +/// Rows of text as names, a row each, matched whole. +fn addRows(p: *Pardes, pk: *Pick, text: []const u8) void { + var lines = std.mem.splitScalar(u8, text, '\n'); + var i: u32 = 0; + while (lines.next()) |ln| : (i += 1) { + if (ln.len == 0) continue; + pk.names.add(p.gpa, ln, 0, ln.len, 0, i) catch return; + } +} + +/// Its rows are names scored by the query: any source's but a live Grep's +/// or All's, and theirs once refined. +fn fuzzy(pk: *const Pick) bool { + return pk.nrefined > 0 or (pk.source != .grep and pk.source != .all); +} + +/// The field typed: the rows again for it. A Grep's lines are the disk +/// engine's, once the typing pauses; the names are scored a frame's count +/// at a time from here. +pub fn filter(p: *Pardes, pk: *Pick) void { + const q = std.mem.trim(u8, p.view().tag_state.field.text(), " "); + p.view().tag_state.rows.at = 0; + pk.shown = no_row; + if (fuzzy(pk)) return pk.names.typed(p.gpa, q); + if (pk.source == .grep) { + pk.found.clearRetainingCapacity(); + pk.found_bytes.clearRetainingCapacity(); + if (q.len > 0) { + Stream.query(p, pk.id, .grep, q, pk.dir.slice(), if (p.fs.serving) .now else .typed) catch |err| return p.reportError(.at(p.view().active), "pick", err); + if (p.fs.serving) Stream.step(p); + } else if (p.stream.target == pk.id) _ = p.stream.stop(); + return; + } + { + // All: each open text's places, found a frame's more at a time. + for (p.panes) |slot| { + const tp = slot orelse continue; + if (!searchable(tp)) continue; + if (q.len == 0) { + if (tp.places.from == pk.id) tp.places.clear(p.gpa); + } else tp.places.search(p, tp, .list, pk.id, q, false, null, false); + } + } +} + +/// A pane whose text All searches: a file's or a list's, not a query +/// pane's nor a preview's. +fn searchable(tp: *const Pane) bool { + const f = tp.file orelse return false; + if (tp.query != null) return false; + if (f.output) |o| if (o.from == .preview) return false; + return true; +} + +/// The panes All's places are in, in the order of their serials. +fn allPanes(p: *const Pardes, pk: *const Pick, out: *[pardes.MAX_PANES]usize) []usize { + var n: usize = 0; + for (p.panes, 0..) |slot, i| if (slot) |tp| if (tp.places.from == pk.id and tp.places.shows(tp) and tp.places.hits.items.len > 0) { + out[n] = i; + n += 1; + }; + std.mem.sort(usize, out[0..n], p, struct { + fn lt(pp: *const Pardes, a: usize, b: usize) bool { + return pp.panes[a].?.serial < pp.panes[b].?.serial; + } + }.lt); + return out[0..n]; +} + +/// The disk engine's rows for picker `target` (Stream.receive). +pub fn take(p: *Pardes, target: u32, kind: Stream.Kind, rows: []const u8) bool { + const pk = byId(p, target) orelse return false; + Query.take(p, pk, kind, rows); + // A listing's names, scored as they come. + if (kind == .files) pk.names.rescore(p.gpa); + return true; +} + +/// Pane `serial`'s declarations came (Stream.receiveParse): a Symbols +/// picker asked from it gathers them. +pub fn declsArrived(p: *Pardes, serial: u32) void { + for (p.picks) |slot| if (slot) |pk| if (pk.unrolled and pk.source == .symbols and pk.owner == serial and pk.names.cands.items.len == 0) { + Query.gather(p, &pk.names, .symbols, pk.dir.slice(), null, p.paneBySerial(serial)); + pk.names.typed(p.gpa, pk.names.queryText()); + pk.names.rescore(p.gpa); + }; +} + +/// After every step: each live picker's names scored on (a frame's count), +/// and on a frame of its own after the cursor stood, the preview of the +/// current row. +pub fn produceAll(p: *Pardes, tick: bool) void { + for (p.picks) |slot| if (slot) |pk| if (pk.unrolled) { + if (pk.names.busy()) pk.names.rescore(p.gpa); + if (tick) preview(p, pk); + }; +} + +/// The frames a live picker still owes: scoring, a preview (nextWake's). +pub fn busy(p: *const Pardes) bool { + for (p.picks) |slot| if (slot) |pk| if (pk.unrolled) { + if (pk.names.busy() or (pk.previews and pk.shown != p.view().tag_state.rows.at)) return true; + }; + return false; +} + +// ---- the rows ---- + +/// The rows the list has now. +pub fn count(p: *const Pardes, pk: *const Pick) usize { + if (fuzzy(pk)) return pk.names.hits.items.len; + switch (pk.source) { + .grep => return pk.found.items.len, + .all => { + var order: [pardes.MAX_PANES]usize = undefined; + var n: usize = 0; + for (allPanes(p, pk, &order)) |i| n += p.panes[i].?.places.hits.items.len; + return n; + }, + else => return pk.names.hits.items.len, + } +} + +/// What row `i` is, kept by a mark across a new query: a name's candidate, +/// a line's place in its source. +fn idOf(pk: *const Pick, i: usize) u32 { + return if (fuzzy(pk)) pk.names.hits.items[i].cand else @intCast(i); +} + +fn marked(pk: *const Pick, id: u32) ?usize { + const at = std.sort.lowerBound(u32, pk.marks.items, id, struct { + fn order(a: u32, b: u32) std.math.Order { + return std.math.order(a, b); + } + }.order); + return if (at < pk.marks.items.len and pk.marks.items[at] == id) at else null; +} + +/// Where a row points: a place in a file, or a pane by its serial. +const Target = union(enum) { none, place: struct { path: []const u8, at: look.Spot }, pane: u32 }; + +/// Row `i` as the band shows it and what it points at, its text in +/// `arena`. +const Row = struct { text: []const u8, pre: u16 = 0, faint: u16 = 0, dim: bool = false, marks: []const u16 = &.{}, target: Target = .none }; + +fn rowAt(p: *Pardes, pk: *const Pick, arena: std.mem.Allocator, i: usize) !Row { + const dir = pk.dir.slice(); + if (!fuzzy(pk) and pk.source == .all) { + var order: [pardes.MAX_PANES]usize = undefined; + var k = i; + for (allPanes(p, pk, &order)) |id| { + const tp = p.panes[id].?; + const hits = tp.places.hits.items; + if (k >= hits.len) { + k -= hits.len; + continue; + } + const f = &tp.file.?; + const h = hits[k]; + const line = @import("Places.zig").lineOf(try File.lineIndex(p.gpa, f), h.start); + const ls = File.lineStart(p.gpa, f, line); + const le = std.mem.indexOfScalarPos(u8, f.content, h.start, '\n') orelse f.content.len; + const whole = f.content[ls..le]; + const lead = whole.len - std.mem.trimStart(u8, whole, " \t").len; + const name = if (f.output == null) std.Io.Dir.path.basename(f.path) else ""; + const pre = try std.fmt.allocPrint(arena, config.pane_addr ++ "{d} {s}:{d}", .{ tp.serial, name, line + 1 }); + const text = try std.fmt.allocPrint(arena, "{s} {s}", .{ pre, whole[lead..@min(whole.len, lead + 240)] }); + var marks: std.ArrayList(u16) = .empty; + var c = h.start - ls; + while (c < h.end - ls and c >= lead and pre.len + 1 + c - lead < text.len) : (c += 1) try marks.append(arena, @intCast(pre.len + 1 + c - lead)); + const target: Target = if (f.output == null) .{ .place = .{ .path = f.path, .at = .{ .line = line + 1, .col = h.start - ls + 1 } } } else .{ .pane = tp.serial }; + return .{ .text = text, .pre = @intCast(pre.len), .marks = marks.items, .target = target }; + } + return .{ .text = "" }; + } + if (!fuzzy(pk)) { + const fd = pk.found.items[i]; + const name = pk.found_bytes.items[fd.path..][0..fd.path_len]; + const code = pk.found_bytes.items[fd.code..][0..fd.code_len]; + const lead = code.len - std.mem.trimStart(u8, code, " \t").len; + const pre = try std.fmt.allocPrint(arena, "{f}:{d}", .{ look.quoted(name), fd.line }); + const text = try std.fmt.allocPrint(arena, "{s} {s}", .{ pre, code[lead..] }); + var marks: std.ArrayList(u16) = .empty; + var c = fd.col; + while (c < fd.end and c >= lead and pre.len + 1 + c - lead < text.len) : (c += 1) try marks.append(arena, @intCast(pre.len + 1 + c - lead)); + const path = try std.Io.Dir.path.join(arena, &.{ dir, name }); + return .{ .text = text, .pre = @intCast(pre.len), .marks = marks.items, .target = .{ .place = .{ .path = path, .at = .{ .line = fd.line, .col = fd.col + 1 } } } }; + } + var marks: [Names.max_query * 4]u16 = undefined; + var nmarks: usize = 0; + const text = pk.names.row(i, &marks, &nmarks); + const cand = pk.names.cands.items[pk.names.hits.items[i].cand]; + var row: Row = .{ .text = text, .marks = try arena.dupe(u16, marks[0..nmarks]) }; + switch (pk.source) { + .find => { + var namebuf: [4096]u8 = undefined; + const name = if (text.len > 1 and text[0] == '"' and text[text.len - 1] == '"') look.unquoted(&namebuf, text[1 .. text.len - 1]) else text; + row.faint = @intCast(if (std.mem.lastIndexOfScalar(u8, text, '/')) |k| k + 1 else 0); + row.target = .{ .place = .{ .path = try std.Io.Dir.path.join(arena, &.{ dir, name }), .at = .{ .line = 1, .col = 1 } } }; + }, + .panes => { + row.pre = cand.key -| 1; + row.dim = p.paneBySerial(cand.ref) == null; + row.target = .{ .pane = cand.ref }; + }, + .symbols => { + row.pre = 6; + const owner = p.panes[p.paneBySerial(pk.owner) orelse return row] orelse return row; + const f = owner.file orelse return row; + row.target = .{ .place = .{ .path = f.path, .at = .{ .line = cand.ref } } }; + }, + .recent, .jumplist, .list, .grep, .all => { + const t = look.parsePathLine(text); + row.pre = @intCast(t.end); + if (t.path.len == 0) return row; + const path = if (t.path[0] == '/' or t.path[0] == '@') t.path else try std.Io.Dir.path.join(arena, &.{ dir, t.path }); + row.target = .{ .place = .{ .path = path, .at = t.at } }; + }, + } + return row; +} + +// ---- the tag ---- + +/// The head of the landing pane's tag (SPEC §5.3): the key cells, the +/// source's word, the query, the count `cursor/total` and `•marked`; on a +/// second row the other sources' words, under spines from the key cells. +pub fn head(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) !?TagState.Head { + const pk = live(p) orelse return null; + const s = &p.view().tag_state; + var text: std.ArrayList(u8) = .empty; + var spans: std.ArrayList(TagState.Span) = .empty; + try text.append(arena, ' '); + var cells: [4][2]u32 = undefined; + var ncells: usize = 0; + // SPC's cell, then its keys': `␣ f`. + if (pk.keys.len > 0) for (0..pk.keys.len + 1) |k| { + const name = if (k == 0) "␣" else bindings.keyName(pk.keys.slice()[k - 1]); + cells[ncells] = .{ @intCast(text.items.len), @intCast(text.items.len + name.len) }; + ncells += 1; + try text.appendSlice(arena, name); + try text.append(arena, ' '); + }; + try text.appendSlice(arena, pk.word.slice()); + try text.append(arena, ' '); + for (pk.refined[0..pk.nrefined]) |r| try text.print(arena, "{s} | ", .{r.query.slice()}); + if (pk.spine == .edit) try text.print(arena, "{s} | Edit ", .{pk.query.slice()}); + const caret: u32 = @intCast(text.items.len + s.field.caret); + try text.appendSlice(arena, s.field.text()); + const n = count(p, pk); + try text.print(arena, " {d}/{d}", .{ if (n == 0) 0 else s.rows.at + 1, n }); + if (pk.marks.items.len > 0) try text.print(arena, " •{d}", .{pk.marks.items.len}); + if (pk.names.busy() or p.stream.busyFor(pk.id)) try text.appendSlice(arena, " ⋯"); + // The second row: the spines go on through it from the key cells, + // then the other sources' words, each switching to it. + try text.append(arena, '\n'); + const prefix = try pardes.tagline.prefixIn(p, arena, pane); + const width = pardes.tagline.tagWidth(p, panes.paneIdOf(p, pane) orelse 0); + const lead = File.displayWidth(p.settings.tab, prefix) % @max(1, width); + var col: usize = 0; + for (cells[0..ncells]) |c| { + const at = lead + File.displayWidth(p.settings.tab, text.items[0..c[0]]); + while (col < at) : (col += 1) try text.append(arena, ' '); + try spans.append(arena, .{ .lo = @intCast(text.items.len), .hi = @intCast(text.items.len + "│".len), .style = .key }); + try text.appendSlice(arena, "│"); + col += 1; + } + const nspines: u8 = @intCast(spans.items.len); + try text.appendSlice(arena, if (ncells == 0) "" else " "); + for (acts) |act| if (offered(pk, act)) try text.print(arena, "{s} ", .{act.word}); + try text.appendSlice(arena, "|"); + var first = false; + inline for (comptime std.enums.values(Source)) |src| if (src != .list) { + if (src != pk.source) { + if (!first) try text.append(arena, ' '); + first = false; + try text.appendSlice(arena, words.get(src).word); + } + }; + for (cells[0..ncells]) |c| try spans.append(arena, .{ .lo = c[0], .hi = c[1], .style = .key }); + return .{ .text = text.items, .spans = spans.items, .cells = nspines, .caret = caret }; +} + +/// The band's rows: as many as the list will show, eleven at most, from +/// what the source has (not what the query keeps: typing never moves the +/// body). +pub fn bandRows(p: *const Pardes) u16 { + const pk = live(p) orelse return 0; + const have = if (!fuzzy(pk)) Band.Cursor.shown else pk.names.cands.items.len; + const rows: usize = @max(1, @min(Band.Cursor.shown, have)); + // Its second step's rows too: the sources, the acts and what they act on. + return @intCast(switch (pk.spine) { + .sources => @max(rows, spine_rows.len), + .acts => acts: { + var n: usize = 1; + for (acts) |act| n += @intFromBool(offered(pk, act)); + break :acts @max(rows, n); + }, + .rows, .edit => rows, + }); +} + +/// The band's steps: the rows around the cursor. +pub fn steps(p: *Pardes, arena: std.mem.Allocator) ![]Band.Step { + const pk = live(p) orelse return &.{}; + const s = &p.view().tag_state; + const n = count(p, pk); + const out = try arena.alloc(Band.Step, if (pk.spine == .sources or pk.spine == .acts) 2 else 1); + if (pk.spine == .acts) out[1] = try actStep(p, pk, arena); + if (pk.spine == .sources) { + const rows = try arena.alloc(Band.Row, spine_rows.len); + for (spine_rows, rows, 0..) |src, *row, i| row.* = .{ .text = try std.fmt.allocPrint(arena, "{c} {s}", .{ src.key, src.word }), .key = 1, .index = @intCast(i), .dim = src.source == pk.source }; + out[1] = .{ .rows = rows }; + } + if (n == 0) { + const none = try arena.alloc(Band.Row, 1); + none[0] = .{ .text = if (pk.names.busy() or p.stream.busyFor(pk.id)) "⋯" else if (s.field.len == 0 and pk.source == .grep) "type to search" else "nothing matches", .dim = true }; + out[0] = .{ .rows = none }; + return out; + } + const w = s.rows.window(@intCast(@min(n, std.math.maxInt(u16)))); + const rows = try arena.alloc(Band.Row, w.hi - w.lo); + for (rows, w.lo..) |*row, i| { + const r = try rowAt(p, pk, arena, i); + row.* = .{ .text = r.text, .on = i == s.rows.at, .mark = marked(pk, idOf(pk, i)) != null, .dim = r.dim, .pre = r.pre, .faint = r.faint, .marks = r.marks, .index = @intCast(i) }; + } + out[0] = .{ .rows = rows }; + return out; +} + +// ---- the preview ---- + +/// The landing pane's body showing the current row's place (SPEC §5.3): +/// a file at its line, the query's matches lit for a Grep. Its own text is +/// set aside the first time, put back when the picker rolls up. A file an +/// open pane shows is taken from it; any other is read. +fn preview(p: *Pardes, pk: *Pick) void { + const s = &p.view().tag_state; + if (pk.shown == s.rows.at or !pk.previews) return; + pk.shown = s.rows.at; + if (count(p, pk) == 0) return; + var frame = std.heap.ArenaAllocator.init(p.gpa); + defer frame.deinit(); + const row = rowAt(p, pk, frame.allocator(), s.rows.at) catch return; + const place = switch (row.target) { + .place => |t| t, + else => return, + }; + const id = p.paneBySerial(pk.landing) orelse return; + const pane = p.panes[id].?; + const f = if (pane.file) |*file| file else return; + if (f.twin != 0) return; + if (!std.mem.eql(u8, f.path, place.path)) { + if (exec.kindOf(p.tape, place.path)) |kind| if (kind != .file) return; + const bytes = openText(p, place.path) orelse (p.tape.site(.preview, p.gpa, filesystem.read, .{ p, place.path }) catch return); + if (std.mem.indexOfScalar(u8, bytes[0..@min(bytes.len, 8000)], 0) != null) { + p.gpa.free(bytes); + return; + } + const path = p.gpa.dupe(u8, place.path) catch { + p.gpa.free(bytes); + return; + }; + if (pk.aside == null and !pk.made) { + const history = File.History.create(p.gpa) catch { + p.gpa.free(bytes); + p.gpa.free(path); + return; + }; + pk.aside = pane.file; + pane.file = .{ .path = path, .content = bytes, .output = .{ .from = .preview }, .history = history }; + } else { + const pf = &pane.file.?; + p.gpa.free(pf.path); + pf.path = path; + File.setContent(p, pf, bytes); + pf.saved_revision = pf.revision; + pf.scroll = 0; + pf.scroll_row = 0; + pf.syntax_dirty = true; + pane.places.clear(p.gpa); + } + pane.hscroll = 0; + p.sync(); + } + const keyboard = p.view().active; + defer p.view().active = keyboard; + look.clearNavigationSelection(p, pane); + const pf = &pane.file.?; + const at = place.at; + if (at.line == 0 or at.line > File.nlines(p.gpa, pf)) { + pf.scroll = 0; + pf.scroll_row = 0; + pane.body.cur_row = 0; + pane.body.cur_col = 0; + return; + } + look.focusPaneLine(p, id, at, .center); + // A Grep's matches in the file lit, as its own pane would have them. + if (pk.source == .grep) pane.places.search(p, pane, .list, pk.id, std.mem.trim(u8, s.field.text(), " "), true, null, false); +} + +/// The text of `path` as an open pane has it, copied: no read for it. +fn openText(p: *Pardes, path: []const u8) ?[]u8 { + for (p.panes) |slot| { + const tp = slot orelse continue; + const tf = tp.file orelse continue; + if (tf.output != null or !std.mem.eql(u8, tf.path, path)) continue; + return p.gpa.dupe(u8, tf.content) catch null; + } + return null; +} + +/// The landing pane as the picker found it: its own text back, or the +/// pane made for the picker taken away; the places it lit put out. +fn restore(p: *Pardes, pk: *Pick) void { + const id = p.paneBySerial(pk.landing) orelse return; + for (p.panes) |slot| if (slot) |tp| if (tp.places.from == pk.id) tp.places.clear(p.gpa); + if (pk.made) { + pk.made = false; + p.removePane(id, p.paneBySerial(pk.owner)) catch |err| p.reportError(.at(id), "pick", err); + return; + } + putBack(p, pk); +} + +/// The landing pane's own text back in it, the preview's freed. +fn putBack(p: *Pardes, pk: *Pick) void { + const id = p.paneBySerial(pk.landing) orelse return; + const pane = p.panes[id].?; + if (pk.made) return; + const own = pk.aside orelse { + // Its own file previewed: its caret and top as they were. + look.clearNavigationSelection(p, pane); + pane.body.cur_row = pk.aside_row; + pane.body.cur_col = pk.aside_col; + if (pane.file != null) File.setTop(pane, .{ .line = pk.aside_top }); + return; + }; + pk.aside = null; + File.deinit(p, pane, &pane.file.?); + pane.file = own; + pane.body.cur_row = pk.aside_row; + pane.body.cur_col = pk.aside_col; + pane.body.vsel.active = false; + p.sync(); +} + +/// The live picker rolled up (Esc, or the tag put to rest by anything): +/// its query and cursor kept for its list word and Resume, every body as +/// it was (TagState.toRest). +pub fn rollUp(p: *Pardes) void { + const pk = live(p) orelse return; + const s = &p.view().tag_state; + if (pk.spine != .edit) pk.query.set(s.field.text()); + pk.spine = .rows; + pk.at = s.rows.at; + pk.unrolled = false; + if (p.stream.target == pk.id) _ = p.stream.stop(); + restore(p, pk); +} + +/// Every picker freed, a live one's landing pane put back first (the +/// session's end). +pub fn deinitAll(p: *Pardes) void { + for (&p.picks) |*slot| if (slot.*) |pk| { + if (pk.unrolled) { + pk.unrolled = false; + if (pk.aside) |own| if (p.paneBySerial(pk.landing)) |id| { + const pane = p.panes[id].?; + File.deinit(p, pane, &pane.file.?); + pane.file = own; + pk.aside = null; + }; + } + pk.deinit(p.gpa); + p.gpa.destroy(pk); + slot.* = null; + }; +} + +// ---- keys ---- + +/// A key in the live picker (keys.zig tagStateKey, SPEC §5.4). Esc is +/// the tag's: TagState.toRest rolls it up. +pub fn key(p: *Pardes, k: Key) void { + const pk = live(p) orelse return TagState.toRest(p); + const s = &p.view().tag_state; + const n: u16 = @intCast(@min(count(p, pk), std.math.maxInt(u16))); + const plain = !k.ctrl and !k.alt; + const ctrl = k.ctrl and !k.alt; + const alt = k.alt and !k.ctrl; + if (pk.spine == .sources) { + pk.spine = .rows; + for (spine_rows) |src| if (plain and k.cp == src.key) return switchTo(p, pk, src.source); + return; + } + if (pk.spine == .acts) return actKey(p, pk, k); + if (pk.spine == .edit) { + if (plain and k.cp == Key.enter) return editRows(p, pk); + if (plain and k.cp == Key.backspace and s.field.len == 0 or alt and k.cp == 'h') { + s.field.set(pk.query.slice()); + pk.spine = .rows; + return; + } + _ = s.field.key(k); + return; + } + if (alt and (k.cp == Key.enter or k.cp == 'l')) { + pk.spine = .acts; + pk.act_at = 0; + return; + } + if (plain and k.cp == Key.enter) return land(p, if (k.shift) .below else .walk); + if (ctrl and k.cp == 's') return land(p, .below); + if (ctrl and k.cp == 'v') return land(p, .column); + if (plain and k.cp == Key.tab) { + if (n == 0) return; + toggle(p, pk, idOf(pk, s.rows.at)); + _ = s.rows.key(.{ .cp = if (k.shift) Key.up else Key.down }, n); + return; + } + if (alt and k.cp == 'a') return markAll(p, pk); + if (alt and k.cp == 'h') { + pk.spine = .sources; + return; + } + if (ctrl and (k.cp == ' ' or k.cp == '@')) return refine(p, pk, false); + if (ctrl and k.cp == 'q') return keep(p, pk); + if (alt and k.cp == 'p') { + pk.previews = !pk.previews; + pk.shown = no_row; + if (!pk.previews) putBack(p, pk); + return; + } + if (plain and k.cp == Key.backspace and s.field.len == 0) return back(p, pk); + if (s.rows.key(k, n)) return; + if (s.field.key(k)) filter(p, pk); +} + +/// The source spine (M-h): a key a source, the query kept. +const spine_rows = [_]struct { key: u8, word: []const u8, source: ?Source }{ + .{ .key = 'f', .word = "Find", .source = .find }, + .{ .key = 'g', .word = "Grep", .source = .grep }, + .{ .key = 'r', .word = "Recent", .source = .recent }, + .{ .key = 'b', .word = "Panes", .source = .panes }, + .{ .key = 's', .word = "Symbols", .source = .symbols }, + .{ .key = '/', .word = "All", .source = .all }, + .{ .key = '?', .word = "Help", .source = null }, +}; + +/// The live picker's source another (`null`: Help over the binding tree), +/// its query kept, its landing pane the same. +fn switchTo(p: *Pardes, pk: *Pick, source: ?Source) void { + const s = &p.view().tag_state; + const to = source orelse { + var query: Kind.Buf(256) = .{}; + query.set(s.field.text()); + TagState.toRest(p); + TagState.openHelp(p, null, ""); + p.view().tag_state.field.set(query.slice()); + return TagState.filter(p); + }; + if (p.stream.target == pk.id) _ = p.stream.stop(); + for (p.panes) |slot| if (slot) |tp| if (tp.places.from == pk.id) tp.places.clear(p.gpa); + for (pk.refined[0..pk.nrefined]) |*r| r.names.deinit(p.gpa); + pk.nrefined = 0; + pk.marks.clearRetainingCapacity(); + pk.source = to; + pk.word.set(words.get(to).word); + pk.keys.set(words.get(to).keys); + start(p, pk); + filter(p, pk); +} + +fn toggle(p: *Pardes, pk: *Pick, id: u32) void { + if (marked(pk, id)) |at| { + _ = pk.marks.orderedRemove(at); + return; + } + const at = std.sort.lowerBound(u32, pk.marks.items, id, struct { + fn order(a: u32, b: u32) std.math.Order { + return std.math.order(a, b); + } + }.order); + pk.marks.insert(p.gpa, at, id) catch |err| p.reportError(.at(p.view().active), "pick", err); +} + +/// Every row marked, or none when every one is. +fn markAll(p: *Pardes, pk: *Pick) void { + const n = count(p, pk); + const all = pk.marks.items.len == n; + pk.marks.clearRetainingCapacity(); + if (all) return; + pk.marks.ensureTotalCapacity(p.gpa, n) catch |err| return p.reportError(.at(p.view().active), "pick", err); + for (0..n) |i| pk.marks.appendAssumeCapacity(idOf(pk, i)); + std.mem.sort(u32, pk.marks.items, {}, std.sort.asc(u32)); +} + +/// C-SPC: the rows the query keeps become the list, the query starts +/// empty; a Grep's lines and All's become names to score from here. +fn refine(p: *Pardes, pk: *Pick, drop: bool) void { + const s = &p.view().tag_state; + const q = std.mem.trim(u8, s.field.text(), " "); + if (q.len == 0 and !drop or pk.nrefined == max_refine) return; + // Dropped: the marked rows, or the current one. + const current = if (count(p, pk) > 0) idOf(pk, s.rows.at) else std.math.maxInt(u32); + var next: Names = .{}; + if (fuzzy(pk)) { + for (pk.names.hits.items) |h| { + if (drop and (if (pk.marks.items.len > 0) marked(pk, h.cand) != null else h.cand == current)) continue; + const c = pk.names.cands.items[h.cand]; + next.add(p.gpa, pk.names.bytes.items[c.start..][0..c.len], c.key, c.key_len, c.base, c.ref) catch break; + } + } else { + var arena = std.heap.ArenaAllocator.init(p.gpa); + defer arena.deinit(); + for (0..count(p, pk)) |i| { + if (drop and (if (pk.marks.items.len > 0) marked(pk, @intCast(i)) != null else i == current)) continue; + _ = arena.reset(.retain_capacity); + const row = rowAt(p, pk, arena.allocator(), i) catch break; + const at = switch (row.target) { + .place => |t| t, + else => continue, + }; + const ln = std.fmt.allocPrint(arena.allocator(), "{s}:{d}:{d} {s}", .{ relative(at.path, pk.dir.slice()), at.at.line, at.at.col, row.text[@min(row.text.len, row.pre + 1)..] }) catch break; + next.add(p.gpa, ln, 0, ln.len, 0, @intCast(i)) catch break; + } + if (p.stream.target == pk.id) _ = p.stream.stop(); + for (p.panes) |slot| if (slot) |tp| if (tp.places.from == pk.id) tp.places.clear(p.gpa); + } + pk.refined[pk.nrefined] = .{ .names = pk.names }; + pk.refined[pk.nrefined].query.set(q); + pk.nrefined += 1; + pk.names = next; + pk.marks.clearRetainingCapacity(); + s.field.clear(); + filter(p, pk); +} + +fn relative(path: []const u8, dir: []const u8) []const u8 { + const d = std.mem.trimEnd(u8, dir, "/"); + if (d.len > 0 and path.len > d.len + 1 and std.mem.startsWith(u8, path, d) and path[d.len] == '/') return path[d.len + 1 ..]; + return path; +} + +/// Backspace on an empty field: the last refinement undone, its query +/// back; else back a step, to the leader's level the picker was run from. +fn back(p: *Pardes, pk: *Pick) void { + const v = p.view(); + const s = &v.tag_state; + if (pk.nrefined > 0) { + pk.nrefined -= 1; + const r = &pk.refined[pk.nrefined]; + pk.names.deinit(p.gpa); + pk.names = r.names; + pk.marks.clearRetainingCapacity(); + s.field.set(r.query.slice()); + s.rows.at = 0; + pk.shown = no_row; + // A live source's own rows again: All's places are found anew. + if (!fuzzy(pk) and pk.source == .all) filter(p, pk); + return; + } + const keys = pk.keys; + TagState.toRest(p); + if (keys.len == 0) return; + v.prefix = .leader; + @memcpy(v.leader_keys[0..keys.len], keys.slice()); + v.leader_n = @intCast(keys.len); + s.root = .leader; + s.unrolled = true; +} + +/// C-q: the rows (the marked, else all, `Query.max_rows` at most) kept as +/// text in a +Search under the asking pane, the source's word and query +/// its first line, each row an address a Look opens. +fn keep(p: *Pardes, pk: *Pick) void { + const s = &p.view().tag_state; + const from = p.paneBySerial(pk.owner) orelse p.view().active; + var out: std.Io.Writer.Allocating = .init(p.gpa); + defer out.deinit(); + var arena = std.heap.ArenaAllocator.init(p.gpa); + defer arena.deinit(); + out.writer.print("{s} ", .{pk.word.slice()}) catch return; + for (pk.refined[0..pk.nrefined]) |r| out.writer.print("{s} | ", .{r.query.slice()}) catch return; + out.writer.print("{s}\n", .{s.field.text()}) catch return; + var kept: usize = 0; + for (0..count(p, pk)) |i| { + if (kept == Query.max_rows) break; + if (pk.marks.items.len > 0 and marked(pk, idOf(pk, i)) == null) continue; + _ = arena.reset(.retain_capacity); + const row = rowAt(p, pk, arena.allocator(), i) catch break; + switch (row.target) { + .place => |t| if (pk.source == .symbols) + out.writer.print("{s}:{d} {s}\n", .{ std.Io.Dir.path.basename(t.path), t.at.line, std.mem.trimStart(u8, row.text, " 0123456789") }) catch break + else + out.writer.print("{s}\n", .{row.text}) catch break, + else => out.writer.print("{s}\n", .{row.text}) catch break, + } + kept += 1; + } + TagState.toRest(p); + const free = p.freeSlot() orelse return p.reportError(.at(from), "pick", error.NoPaneSlots); + const content = out.toOwnedSlice() catch |err| return p.reportError(.at(from), "pick", err); + _ = Output.open(p, free, pk.dir.slice(), .search, "", content) catch |err| { + p.gpa.free(content); + return p.reportError(.at(from), "pick", err); + }; + layout.placeNew(p, from, from, free, .doc); +} + +/// How Enter lands: a walk step, a new pane below, a new column; `queue`: +/// a walk step to the first, the others queued for C-i (the act Walk). +const How = enum { walk, below, column, queue }; + +/// Enter: the current row, or the marked ones, looked at from the asking +/// pane (look.open, the walk's way: a reading pane steps, a held one's +/// reader does), the first as `how` says, the others each in a pane below. +/// The list rolls into the landing pane's trail as its word (item 4). +fn land(p: *Pardes, how: How) void { + const pk = live(p) orelse return; + var arena = std.heap.ArenaAllocator.init(p.gpa); + defer arena.deinit(); + const a = arena.allocator(); + const picked = pickedRows(p, pk, a) catch return; + if (picked.len == 0) return; + // Walk: the first now, the others queued for C-i. + pk.queue.clearRetainingCapacity(); + pk.queue_bytes.clearRetainingCapacity(); + pk.queue_at = 0; + if (how == .queue) for (picked[1..]) |t| switch (t) { + .place => |at| { + const q: Queued = .{ .path = @intCast(pk.queue_bytes.items.len), .len = @intCast(@min(at.path.len, std.math.maxInt(u16))), .line = std.math.lossyCast(u32, at.at.line), .col = std.math.lossyCast(u32, at.at.col) }; + pk.queue_bytes.appendSlice(p.gpa, at.path[0..q.len]) catch break; + pk.queue.append(p.gpa, q) catch break; + }, + else => {}, + }; + // A step from the pane it lands in when that reads (its owner's reader + // or itself), else from its owner, whose reader the place opens as. + const landing = if (pk.made) null else p.paneBySerial(pk.landing); + TagState.toRest(p); + const v = p.view(); + const owner = p.paneBySerial(pk.owner) orelse v.active; + const from = if (how == .walk or how == .queue) landing orelse owner else owner; + v.active = from; + v.jumps.force = true; + for (picked, 0..) |t, k| switch (t) { + .none => {}, + .pane => |serial| if (p.paneBySerial(serial)) |tid| { + v.active = tid; + if (layout.findPane(p, tid)) |at| p.setActiveColumn(at.col); + } else { + _ = p.store.reopen(p, serial, from); + }, + .place => |at| if (k == 0 and (how == .walk or how == .queue)) { + switch (look.open(p, from, at.path, at.at, .replace)) { + .none => {}, + else => listed(p, pk), + } + } else if (k == 0 and how == .column) { + layout.newColumn(p, from); + const c = layout.activeColumn(p) orelse continue; + p.exec_column = c; + defer p.exec_column = null; + pardes.tagline.exitHeader(p); + _ = look.open(p, from, at.path, at.at, .below); + } else if (how != .queue) { + _ = look.open(p, from, at.path, at.at, .below); + }, + }; + if (how == .queue and pk.queue.items.len > 0) { + var said: Kind.Buf(64) = .{}; + p.setMessage(.at(v.active), said.print("Walk: {d} more places here, C-i for the next", .{pk.queue.items.len})); + } +} + +// ---- after Enter: the list word ---- + +/// The list as its word in a trail says it (SPEC §5.6): its source, its +/// query, where its cursor is among its rows, and its marks: +/// `Find pick 3/6 •2`. +fn wordOf(p: *const Pardes, pk: *const Pick, buf: *Kind.Buf(Trail.max_text)) []const u8 { + var w: std.Io.Writer = .fixed(&buf.bytes); + w.writeAll(pk.word.slice()) catch {}; + for (pk.refined[0..pk.nrefined]) |r| w.print(" {s} |", .{r.query.slice()}) catch {}; + if (pk.query.len > 0) w.print(" {s}", .{pk.query.slice()}) catch {}; + const n = count(p, pk); + w.print(" {d}/{d}", .{ if (n == 0) 0 else pk.at + 1, n }) catch {}; + if (pk.marks.items.len > 0) w.print(" •{d}", .{pk.marks.items.len}) catch {}; + buf.len = @intCast(w.buffered().len); + return buf.slice(); +} + +/// The list rolled into the trail of the reading pane it landed in, its +/// word before the place: the list `n` and `N` walk there. +fn listed(p: *Pardes, pk: *const Pick) void { + const pane = p.panes[p.view().active] orelse return; + if (!Trail.reading(p, pane)) return; + var w: Trail.Word = .{ .index = pk.id }; + _ = wordOf(p, pk, &w.text); + Trail.through(&pane.trail, .{ .list = w }); +} + +/// `n` and `N` in a reading pane whose trail's newest list or search word +/// is a list's: its next or previous row in place of the current step +/// (Trail.replaceStep), its word saying where it is now. False when there +/// is no list for them to walk (normal.zig: the search's then). +pub fn walkList(p: *Pardes, id: usize, forward: bool) bool { + const pane = p.panes[id] orelse return false; + if (!Trail.reading(p, pane)) return false; + const t = &pane.trail; + var i: usize = @min(t.cur, t.n); + while (i > 0) { + i -= 1; + switch (t.steps[i]) { + .list => break, + .search => return false, + else => {}, + } + } else return false; + const pk = byId(p, t.steps[i].list.index) orelse return false; + const n = count(p, pk); + if (n == 0) return false; + if (if (forward) pk.at + 1 >= n else pk.at == 0) { + p.setMessage(.at(id), if (forward) "n: the list's last row" else "N: the list's first row"); + return true; + } + pk.at = if (forward) pk.at + 1 else pk.at - 1; + var arena = std.heap.ArenaAllocator.init(p.gpa); + defer arena.deinit(); + const row = rowAt(p, pk, arena.allocator(), pk.at) catch return true; + const at = switch (row.target) { + .place => |x| x, + else => return true, + }; + _ = wordOf(p, pk, &t.steps[i].list.text); + _ = Trail.replaceStep(p, id, at.path, at.at) catch |err| p.reportError(.at(id), "walk", err); + return true; +} + +/// Look on a list word in pane `id`'s trail (SPEC §6.3): the list unrolled +/// again in that pane's tag, its rows, marks, cursor and query as they were. +pub fn reopen(p: *Pardes, id: usize, index: u32) void { + const pk = byId(p, index) orelse return p.setMessage(.at(id), "walk: that list is gone: the last 8 are kept"); + const pane = p.panes[id] orelse return; + TagState.toRest(p); + pk.landing = pane.serial; + pk.made = false; + unroll(p, pk, pk.query.slice()); + unrollRows(p, pk); +} + +/// A list unrolled again: All's places found again, the cursor where it was. +fn unrollRows(p: *Pardes, pk: *Pick) void { + const at = pk.at; + if (!fuzzy(pk) and pk.source == .all) filter(p, pk); + p.view().tag_state.rows.at = @intCast(@min(at, std.math.maxInt(u16))); +} + +/// Exec on a list word (SPEC §6.3): its source run again with its query, +/// from pane `id`. +pub fn rerun(p: *Pardes, id: usize, index: u32) void { + const pk = byId(p, index) orelse return p.setMessage(.at(id), "walk: that list is gone: the last 8 are kept"); + var query: Kind.Buf(256) = .{}; + query.set(pk.query.slice()); + open(p, id, pk.source, pk.word.slice(), query.slice(), pk.rows); +} + +/// Resume (`SPC '`): the last picker reopened as it was, from pane `from`, +/// in the tag of the pane its Enter lands in. +pub fn resumeFrom(p: *Pardes, from: usize) void { + var newest: ?*Pick = null; + for (p.picks) |slot| if (slot) |pk| if (newest == null or pk.id > newest.?.id) { + newest = pk; + }; + const pk = newest orelse return p.setMessage(.at(from), "Resume: no picker yet"); + TagState.toRest(p); + if (p.panes[from] == null) return; + hostIn(p, pk, from) catch |err| return p.reportError(.at(from), "Resume", err); + unroll(p, pk, pk.query.slice()); + unrollRows(p, pk); +} + +/// B3 on a picker's row (mouse.zig bandPress): Enter on it. +pub fn landHere(p: *Pardes) void { + const pk = live(p) orelse return; + if (pk.spine == .rows) land(p, .walk); +} + +/// The rows an act or Enter takes: the marked, else the current. +fn pickedRows(p: *Pardes, pk: *const Pick, a: std.mem.Allocator) ![]Target { + const s = &p.view().tag_state; + const n = count(p, pk); + var picked: std.ArrayList(Target) = .empty; + if (n == 0) return picked.items; + if (pk.marks.items.len == 0) { + try picked.append(a, (try rowAt(p, pk, a, s.rows.at)).target); + } else for (0..n) |i| if (marked(pk, idOf(pk, i)) != null) { + try picked.append(a, (try rowAt(p, pk, a, i)).target); + }; + return picked.items; +} + +/// C-i past a reading pane's newest step (Jump.jumpBy, SPEC §6.4): the +/// next place a Walk queued in it, through the list its trail holds last. +pub fn stepQueue(p: *Pardes, id: usize) bool { + const pane = p.panes[id] orelse return false; + const t = &pane.trail; + var i: usize = @min(t.cur, t.n); + const pk = while (i > 0) { + i -= 1; + if (t.steps[i] == .list) break byId(p, t.steps[i].list.index) orelse return false; + } else return false; + if (pk.queue_at >= pk.queue.items.len) return false; + const q = pk.queue.items[pk.queue_at]; + pk.queue_at += 1; + p.view().jumps.force = true; + _ = look.open(p, id, pk.queue_bytes.items[q.path..][0..q.len], .{ .line = q.line, .col = q.col }, .replace); + return true; +} + +// ---- acts ---- + +/// What the act step offers (SPEC §5.5): the same everywhere, but a list +/// of panes, whose rows are no places, has Look, Copy, Keep, Drop and Del. +const Act = struct { key: u8, word: []const u8, says: []const u8 }; +const acts = [_]Act{ + .{ .key = 'w', .word = "Walk", .says = "here, one by one (C-i)" }, + .{ .key = 'o', .word = "Look", .says = "open them (Enter)" }, + .{ .key = 's', .word = "Split", .says = "each in a pane below" }, + .{ .key = 'v', .word = "Newcol", .says = "in a new column" }, + .{ .key = 'g', .word = "Grep", .says = "in their directory, the same pattern" }, + .{ .key = 'e', .word = "Edit", .says = "a sam command on each line" }, + .{ .key = 'y', .word = "Copy", .says = "the places, as text" }, + .{ .key = 'k', .word = "Keep", .says = "the rows as a +Search" }, + .{ .key = 'x', .word = "Drop", .says = "the picked from the list" }, + .{ .key = 'd', .word = "Del", .says = "close those panes" }, +}; + +fn offered(pk: *const Pick, act: Act) bool { + if (pk.source == .panes) return std.mem.indexOfScalar(u8, "oykxd", act.key) != null; + return act.key != 'd'; +} + +/// The act step: what it acts on (`on 2 marked`, `on core/pick.zig`), +/// then the acts. +fn actStep(p: *Pardes, pk: *const Pick, arena: std.mem.Allocator) !Band.Step { + var rows: std.ArrayList(Band.Row) = .empty; + const s = &p.view().tag_state; + const on = if (pk.marks.items.len > 0) + try std.fmt.allocPrint(arena, "on {d} marked", .{pk.marks.items.len}) + else if (count(p, pk) > 0) on: { + const row = try rowAt(p, pk, arena, s.rows.at); + break :on try std.fmt.allocPrint(arena, "on {s}", .{switch (row.target) { + .place => |t| relative(t.path, pk.dir.slice()), + else => row.text, + }}); + } else "on nothing"; + try rows.append(arena, .{ .text = on, .dim = true }); + var k: u8 = 0; + for (acts) |act| if (offered(pk, act)) { + try rows.append(arena, .{ .text = try std.fmt.allocPrint(arena, "{c} {s: <7} {s}", .{ act.key, act.word, act.says }), .key = 1, .on = k == pk.act_at, .index = k }); + k += 1; + }; + return .{ .rows = rows.items }; +} + +fn actKey(p: *Pardes, pk: *Pick, k: Key) void { + const plain = !k.ctrl and !k.alt; + var n: u8 = 0; + for (acts) |act| n += @intFromBool(offered(pk, act)); + if (plain and (k.cp == Key.down or k.cp == Key.up)) { + pk.act_at = if (k.cp == Key.down) (pk.act_at + 1) % n else (pk.act_at + n - 1) % n; + return; + } + var at: u8 = 0; + for (acts) |act| if (offered(pk, act)) { + if (plain and (k.cp == act.key or k.cp == Key.enter and at == pk.act_at)) return doAct(p, pk, act.key); + at += 1; + }; + // Anything else (M-h, Left): back to the rows. + pk.spine = .rows; +} + +/// Act `key` on the picked rows. +fn doAct(p: *Pardes, pk: *Pick, key_: u8) void { + const s = &p.view().tag_state; + pk.spine = .rows; + switch (key_) { + 'w' => land(p, .queue), + 'o' => land(p, .walk), + 's' => land(p, .below), + 'v' => land(p, .column), + 'k' => keep(p, pk), + 'x' => refine(p, pk, true), + 'e' => { + pk.query.set(s.field.text()); + s.field.clear(); + pk.spine = .edit; + }, + 'g' => { + var arena = std.heap.ArenaAllocator.init(p.gpa); + defer arena.deinit(); + const picked = pickedRows(p, pk, arena.allocator()) catch return; + const dir = for (picked) |t| switch (t) { + .place => |at| break std.Io.Dir.path.dirname(at.path) orelse pk.dir.slice(), + else => {}, + } else pk.dir.slice(); + const q = if (pk.source == .grep) arena.allocator().dupe(u8, s.field.text()) catch return else ""; + const where = arena.allocator().dupe(u8, dir) catch return; + const from = p.paneBySerial(pk.owner) orelse p.view().active; + TagState.toRest(p); + open(p, from, .grep, "", "", ""); + const grep = live(p) orelse return; + grep.dir.set(where); + p.view().tag_state.field.set(q); + filter(p, grep); + }, + 'y' => { + var out: std.Io.Writer.Allocating = .init(p.gpa); + defer out.deinit(); + var arena = std.heap.ArenaAllocator.init(p.gpa); + defer arena.deinit(); + const picked = pickedRows(p, pk, arena.allocator()) catch return; + for (picked) |t| switch (t) { + .place => |at| out.writer.print("{s}:{d}\n", .{ at.path, @max(1, at.at.line) }) catch return, + .pane => |serial| out.writer.print(config.pane_addr ++ "{d}\n", .{serial}) catch return, + .none => {}, + }; + p.registers.put(p.gpa, '"', out.written(), 0, 1, true) catch |err| return p.reportError(.at(p.view().active), "pick", err); + var said: Kind.Buf(64) = .{}; + p.setMessage(.at(p.view().active), said.print("Copy: {d} places into the \" register", .{picked.len})); + }, + 'd' => { + var arena = std.heap.ArenaAllocator.init(p.gpa); + defer arena.deinit(); + const picked = pickedRows(p, pk, arena.allocator()) catch return; + for (picked) |t| if (t == .pane) if (p.paneBySerial(t.pane)) |id| if (id != p.paneBySerial(pk.landing)) { + p.removePane(id, null) catch |err| p.reportError(.at(id), "pick", err); + }; + pk.marks.clearRetainingCapacity(); + start(p, pk); + filter(p, pk); + }, + else => {}, + } +} + +/// Edit's Enter: its command run on each picked row's line, in the open +/// text that shows its file (edit_cmd.zig, an undo step a line); a row +/// whose file no pane shows is passed over, and said. +fn editRows(p: *Pardes, pk: *Pick) void { + const s = &p.view().tag_state; + var arena = std.heap.ArenaAllocator.init(p.gpa); + defer arena.deinit(); + const a = arena.allocator(); + const command = a.dupe(u8, std.mem.trim(u8, s.field.text(), " ")) catch return; + const picked = pickedRows(p, pk, a) catch return; + TagState.toRest(p); + if (command.len == 0) return; + var ran: usize = 0; + // From the last line up, so an edit that adds lines moves none still to come. + var k = picked.len; + while (k > 0) { + k -= 1; + const at = switch (picked[k]) { + .place => |t| t, + else => continue, + }; + const id = for (p.panes, 0..) |slot, i| { + const tp = slot orelse continue; + const f = tp.file orelse continue; + if (f.output == null and std.mem.eql(u8, f.path, at.path)) break i; + } else continue; + @import("edit_cmd.zig").run(p, id, std.fmt.allocPrint(a, "{d} {s}", .{ @max(1, at.at.line), command }) catch return); + ran += 1; + } + var said: Kind.Buf(96) = .{}; + p.setMessage(.at(p.view().active), said.print("Edit {s}: {d} of {d} lines, in open texts", .{ command[0..@min(command.len, 40)], ran, picked.len })); +} + +/// A word of the picker's tag or band run (B2, exec.zig +/// executeBuiltinLine) while it is live: an act's word acts, a source's +/// switches to it (Grep, both, is the source); anything else is no +/// picker's. +pub fn execWord(p: *Pardes, txt: []const u8) bool { + const pk = live(p) orelse return false; + const word = std.mem.trim(u8, txt, " \t\n"); + for (spine_rows) |src| if (std.mem.eql(u8, word, src.word)) { + switchTo(p, pk, src.source); + return true; + }; + if (std.mem.eql(u8, word, "Jumplist")) { + switchTo(p, pk, .jumplist); + return true; + } + for (acts) |act| if (offered(pk, act) and std.mem.eql(u8, word, act.word)) { + doAct(p, pk, act.key); + return true; + }; + return false; +} + +fn testFile(p: *Pardes, tmp: *std.testing.TmpDir, name: []const u8, text: []const u8) ![]u8 { + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = name, .data = text }); + var base_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + const dir = base_buf[0..try tmp.dir.realPath(std.testing.io, &base_buf)]; + return std.Io.Dir.path.join(p.gpa, &.{ dir, name }); +} + +fn tagOf(p: *Pardes, arena: std.mem.Allocator, id: usize) ![]const u8 { + return pardes.tagline.tagText(p, arena, p.panes[id].?); +} + +fn paneCount(p: *const Pardes) usize { + var n: usize = 0; + for (p.panes) |slot| n += @intFromBool(slot != null); + return n; +} + +fn settle(p: *Pardes) void { + var n: usize = 0; + while (n < 50 and (busy(p) or p.stream.busyFor(live(p).?.id))) : (n += 1) { + Stream.step(p); + p.update(.tick); + } +} + +test "a picker from a held pane unrolls in a reader made for it: its rows in the band, the body the current row's file, Esc takes the reader away" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 50 }); + defer p.deinit(); + p.settings.jumps = .walk; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const a_path = try testFile(p, &tmp, "alpha.zig", "const alpha = 1;\n"); + defer p.gpa.free(a_path); + const b_path = try testFile(p, &tmp, "pick_state.zig", "//! The state a picker keeps\nconst x = 2;\n"); + defer p.gpa.free(b_path); + const held = try p.setTestFile("held\n"); + _ = held; + const asker = p.view().active; + // Held: Keep. + Trail.keep(p.panes[asker].?); + const dir = std.Io.Dir.path.dirname(a_path).?; + p.gpa.free(p.panes[asker].?.file.?.path); + p.panes[asker].?.file.?.path = try std.Io.Dir.path.join(p.gpa, &.{ dir, "held.txt" }); + p.stream.engine = .walk; + const npanes = paneCount(p); + open(p, asker, .find, "", "", ""); + const pk = live(p).?; + // A reader made for it, under the asker; its tag is the picker's. + try std.testing.expectEqual(npanes + 1, paneCount(p)); + try std.testing.expect(pk.made); + const reader = p.paneBySerial(pk.landing).?; + try std.testing.expectEqual(@as(?usize, reader), TagState.hostOf(p)); + try std.testing.expectEqual(asker, p.view().active); + settle(p); + try std.testing.expectEqual(@as(usize, 2), count(p, pk)); + for ("pick") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); + settle(p); + try std.testing.expectEqual(@as(usize, 1), count(p, pk)); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + const a = frame.allocator(); + const tag = try tagOf(p, a, reader); + try std.testing.expect(std.mem.indexOf(u8, tag, " ␣ f Find pick 1/1\n") != null); + try std.testing.expect(std.mem.indexOf(u8, tag, "│ Walk Look Split Newcol Grep Edit Copy Keep Drop | Grep Recent Panes Symbols All Jumplist") != null); + // The body previews the row's file, after a frame of its own. + p.update(.tick); + try std.testing.expectEqualStrings(b_path, p.panes[reader].?.file.?.path); + _ = try p.render(a); + const r = p.view().rects[reader]; + try std.testing.expectEqualStrings("^", p.surface.at(r.x, r.y).grapheme()); + try std.testing.expect(p.panes[reader].?.band_rows >= 1); + // Esc: the reader made for it goes, the asker as it was. + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expectEqual(npanes, paneCount(p)); + try std.testing.expect(live(p) == null); + try std.testing.expectEqual(TagState.Kind.rest, p.view().tag_state.kind); + try std.testing.expectEqualStrings("pick", pk.query.slice()); +} + +test "a picker's keys: Tab marks and moves, M-a all and none, C-SPC refines and Backspace undoes it, M-h switches source keeping the query" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 50 }); + defer p.deinit(); + p.settings.jumps = .walk; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const a_path = try testFile(p, &tmp, "alpha.zig", "const alpha = 1;\n"); + defer p.gpa.free(a_path); + look.lookAt(p, p.view().active, a_path); + const id = p.view().active; + open(p, id, .list, "Refs", "", "alpha.zig:1:1 one\nalpha.zig:1:2 two\nbeta.zig:1:1 tree\nalpha.zig:1:4 four\n"); + const pk = live(p).?; + settle(p); + const s = &p.view().tag_state; + try std.testing.expectEqual(@as(usize, 4), count(p, pk)); + p.update(.{ .key = .{ .cp = Key.tab } }); + try std.testing.expectEqual(@as(u16, 1), s.rows.at); + p.update(.{ .key = .{ .cp = Key.tab } }); + try std.testing.expectEqual(@as(usize, 2), pk.marks.items.len); + p.update(.{ .key = .{ .cp = Key.up } }); + p.update(.{ .key = .{ .cp = Key.tab } }); + try std.testing.expectEqual(@as(usize, 1), pk.marks.items.len); + try std.testing.expectEqual(@as(u16, 2), s.rows.at); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + try std.testing.expect(std.mem.indexOf(u8, try tagOf(p, frame.allocator(), id), " Refs 3/4 •1\n") != null); + p.update(.{ .key = .{ .cp = 'a', .alt = true } }); + try std.testing.expectEqual(@as(usize, 4), pk.marks.items.len); + p.update(.{ .key = .{ .cp = 'a', .alt = true } }); + try std.testing.expectEqual(@as(usize, 0), pk.marks.items.len); + // C-SPC: what `alpha` keeps becomes the list; `w` then narrows it. + for ("alpha") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); + settle(p); + try std.testing.expectEqual(@as(usize, 3), count(p, pk)); + p.update(.{ .key = .{ .cp = ' ', .ctrl = true } }); + try std.testing.expectEqual(@as(u8, 1), pk.nrefined); + try std.testing.expectEqual(@as(u16, 0), s.field.len); + settle(p); + try std.testing.expectEqual(@as(usize, 3), count(p, pk)); + for ("w") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); + settle(p); + try std.testing.expectEqual(@as(usize, 1), count(p, pk)); + _ = frame.reset(.retain_capacity); + try std.testing.expect(std.mem.indexOf(u8, try tagOf(p, frame.allocator(), id), " Refs alpha | w 1/1\n") != null); + // Backspace twice: the `w` goes, then the refinement, its query back. + p.update(.{ .key = .{ .cp = Key.backspace } }); + p.update(.{ .key = .{ .cp = Key.backspace } }); + try std.testing.expectEqual(@as(u8, 0), pk.nrefined); + try std.testing.expectEqualStrings("alpha", s.field.text()); + settle(p); + try std.testing.expectEqual(@as(usize, 3), count(p, pk)); + // M-p: the preview off, and no frame asked for it. + p.update(.{ .key = .{ .cp = 'p', .alt = true } }); + try std.testing.expect(!pk.previews and !busy(p)); + p.update(.{ .key = .{ .cp = 'p', .alt = true } }); + // M-h r: Recent, the query kept. + p.update(.{ .key = .{ .cp = 'h', .alt = true } }); + try std.testing.expect(pk.spine == .sources); + p.update(.{ .key = .{ .cp = 'r', .text = "r" } }); + try std.testing.expectEqual(Source.recent, pk.source); + try std.testing.expectEqualStrings("alpha", s.field.text()); + p.update(.{ .key = .{ .cp = Key.escape } }); +} + +test "Enter lands as a walk step in the reading pane; S-Enter opens below; from a held pane the reader made for the picker becomes its reader" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 50 }); + defer p.deinit(); + p.settings.jumps = .walk; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const a_path = try testFile(p, &tmp, "alpha.zig", "const alpha = 1;\n"); + defer p.gpa.free(a_path); + const b_path = try testFile(p, &tmp, "beta.zig", "one\ntwo\nthree\n"); + defer p.gpa.free(b_path); + look.lookAt(p, p.view().active, a_path); + const id = p.view().active; + const npanes = paneCount(p); + open(p, id, .list, "Refs", "", "beta.zig:3:1 three\n"); + settle(p); + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expect(live(p) == null); + const here = p.panes[p.view().active].?; + try std.testing.expectEqualStrings(b_path, here.file.?.path); + try std.testing.expectEqual(@as(i32, 2), here.body.cur_row); + try std.testing.expect(here.file.?.output == null); + try std.testing.expectEqual(npanes, paneCount(p)); + // Its trail: where it was, then the place. + try std.testing.expect(here.trail.n >= 2); + // S-Enter: a pane below, the reading pane as it was. + open(p, p.view().active, .list, "Refs", "", "alpha.zig:1:7 alpha\n"); + settle(p); + p.update(.{ .key = .{ .cp = Key.enter, .shift = true } }); + try std.testing.expectEqual(npanes + 1, paneCount(p)); + try std.testing.expectEqualStrings(a_path, p.panes[p.view().active].?.file.?.path); + + // From a held pane: the reader made for the picker is taken away and + // the place opens as the held pane's reader, its trail its owner's. + const held = p.view().active; + Trail.keep(p.panes[held].?); + open(p, held, .list, "Refs", "", "beta.zig:2:1 two\n"); + const pk = live(p).?; + try std.testing.expect(pk.made); + settle(p); + p.update(.{ .key = .{ .cp = Key.enter } }); + const reader = Trail.readerOf(p, p.panes[held].?).?; + try std.testing.expectEqualStrings(b_path, p.panes[reader].?.file.?.path); + try std.testing.expectEqual(npanes + 2, paneCount(p)); +} + +test "M-l unrolls the act step, which says what it acts on; Copy puts the places in the register, Drop takes the picked rows out, Walk queues the rest for C-i" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 50 }); + defer p.deinit(); + p.settings.jumps = .walk; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const a_path = try testFile(p, &tmp, "alpha.zig", "one\ntwo\nthree\nfour\n"); + defer p.gpa.free(a_path); + look.lookAt(p, p.view().active, a_path); + const id = p.view().active; + const rows = "alpha.zig:1:1 one\nalpha.zig:2:1 two\nalpha.zig:3:1 three\nalpha.zig:4:1 four\n"; + open(p, id, .list, "Refs", "", rows); + const pk = live(p).?; + settle(p); + p.update(.{ .key = .{ .cp = 'l', .alt = true } }); + try std.testing.expect(pk.spine == .acts); + // The band as tall as the acts and what they act on, the list's rows fewer. + try std.testing.expectEqual(@as(u16, 10), bandRows(p)); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + const band = (try Band.of(p, frame.allocator(), p.panes[id].?, id)).?; + try std.testing.expectEqual(@as(u8, 2), band.nsteps); + try std.testing.expectEqualStrings("on alpha.zig", band.steps[1].rows[0].text); + // y: the place copied, the act step rolled back to the rows. + p.update(.{ .key = .{ .cp = 'y', .text = "y" } }); + try std.testing.expect(pk.spine == .rows); + // x: the current row dropped, as a refinement. + p.update(.{ .key = .{ .cp = 'l', .alt = true } }); + p.update(.{ .key = .{ .cp = 'x', .text = "x" } }); + settle(p); + try std.testing.expectEqual(@as(usize, 3), count(p, pk)); + try std.testing.expectEqual(@as(u8, 1), pk.nrefined); + // Tab Tab: two marked; Walk lands on the first and queues the second. + p.update(.{ .key = .{ .cp = Key.tab } }); + p.update(.{ .key = .{ .cp = Key.tab } }); + p.update(.{ .key = .{ .cp = 'l', .alt = true } }); + _ = frame.reset(.retain_capacity); + const marked_band = (try Band.of(p, frame.allocator(), p.panes[id].?, id)).?; + try std.testing.expectEqualStrings("on 2 marked", marked_band.steps[1].rows[0].text); + p.update(.{ .key = .{ .cp = 'w', .text = "w" } }); + try std.testing.expect(live(p) == null); + try std.testing.expectEqual(@as(i32, 1), p.panes[p.view().active].?.body.cur_row); + try std.testing.expectEqual(@as(usize, 1), pk.queue.items.len); +} + +test "after Enter the list is a word in the reader's trail: n and N walk its rows in place, a Look on it reopens it with its cursor and marks, Exec runs it again, Resume reopens the last" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 50 }); + defer p.deinit(); + p.settings.jumps = .walk; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const a_path = try testFile(p, &tmp, "alpha.zig", "one\ntwo\nthree\nfour\n"); + defer p.gpa.free(a_path); + const b_path = try testFile(p, &tmp, "beta.zig", "b1\nb2\n"); + defer p.gpa.free(b_path); + _ = try p.setTestFile("held\n"); + const held = p.view().active; + Trail.keep(p.panes[held].?); + p.gpa.free(p.panes[held].?.file.?.path); + p.panes[held].?.file.?.path = try std.Io.Dir.path.join(p.gpa, &.{ std.Io.Dir.path.dirname(a_path).?, "held.txt" }); + open(p, held, .list, "Refs", "", "alpha.zig:2:1 two\nbeta.zig:2:1 b2\nalpha.zig:4:1 four\n"); + const pk = live(p).?; + settle(p); + p.update(.{ .key = .{ .cp = Key.tab } }); + p.update(.{ .key = .{ .cp = Key.up } }); + p.update(.{ .key = .{ .cp = Key.enter } }); + // The reader: its owner, the list's word, the place. + const reader = Trail.readerOf(p, p.panes[held].?).?; + var t = &p.panes[reader].?.trail; + try std.testing.expectEqual(@as(u8, 3), t.n); + try std.testing.expect(t.steps[1] == .list); + try std.testing.expectEqualStrings("Refs 1/3 •1", t.steps[1].list.text.slice()); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + try std.testing.expect(std.mem.indexOf(u8, try tagOf(p, frame.allocator(), reader), "‹@p") != null); + try std.testing.expect(std.mem.indexOf(u8, try tagOf(p, frame.allocator(), reader), " › Refs 1/3 •1 › ") != null); + // n: the next row, in place of the step (another file: a pane in its place). + p.view().active = reader; + p.update(.{ .key = .{ .cp = 'n', .text = "n" } }); + const r2 = Trail.readerOf(p, p.panes[held].?).?; + try std.testing.expectEqualStrings(b_path, p.panes[r2].?.file.?.path); + t = &p.panes[r2].?.trail; + try std.testing.expectEqual(@as(u8, 3), t.n); + try std.testing.expectEqualStrings("Refs 2/3 •1", t.steps[1].list.text.slice()); + p.update(.{ .key = .{ .cp = 'N', .text = "N", .shift = true } }); + const r3 = Trail.readerOf(p, p.panes[held].?).?; + try std.testing.expectEqualStrings(a_path, p.panes[r3].?.file.?.path); + try std.testing.expectEqual(@as(i32, 1), p.panes[r3].?.body.cur_row); + // Look on the word: the list again, in the reader's tag, as it was. + Trail.lookStep(p, r3, 1); + try std.testing.expect(live(p) == pk); + try std.testing.expectEqual(@as(?usize, r3), TagState.hostOf(p)); + try std.testing.expectEqual(@as(u16, 0), p.view().tag_state.rows.at); + try std.testing.expectEqual(@as(usize, 1), pk.marks.items.len); + p.update(.{ .key = .{ .cp = Key.escape } }); + // Exec on it: a new picker of the same source. + Trail.execStep(p, r3, 1); + try std.testing.expect(live(p) != null and live(p) != pk); + p.update(.{ .key = .{ .cp = Key.escape } }); + // Resume: the last one. + exec.runBuiltin(p, .Resume, held, "", null); + try std.testing.expect(live(p) != null); + p.update(.{ .key = .{ .cp = Key.escape } }); +} + +test "pick-ui §14.3 phase 4: SPC f f from a held pane opens in its reader and Esc removes it; from a reading pane it unrolls there; Enter lands as a step leaving the list word; n walks; a Look on the word reopens it with its cursor and marks" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 50 }); + defer p.deinit(); + p.settings.jumps = .walk; + p.stream.engine = .walk; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const a_path = try testFile(p, &tmp, "pick.zig", "const pick = 1;\n"); + defer p.gpa.free(a_path); + const b_path = try testFile(p, &tmp, "pick_test.zig", "test {}\n"); + defer p.gpa.free(b_path); + const c_path = try testFile(p, &tmp, "other.zig", "x\n"); + defer p.gpa.free(c_path); + _ = try p.setTestFile("held\n"); + const held = p.view().active; + Trail.keep(p.panes[held].?); + p.gpa.free(p.panes[held].?.file.?.path); + p.panes[held].?.file.?.path = try std.Io.Dir.path.join(p.gpa, &.{ std.Io.Dir.path.dirname(a_path).?, "held.txt" }); + const npanes = paneCount(p); + const typeIn = struct { + fn f(pp: *Pardes, keys: []const u8) void { + for (keys) |c| pp.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); + } + }.f; + // SPC f f from the held pane: a reader made for it, which Esc takes. + typeIn(p, " ff"); + try std.testing.expect(live(p) != null and live(p).?.made); + try std.testing.expectEqual(npanes + 1, paneCount(p)); + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expectEqual(npanes, paneCount(p)); + try std.testing.expectEqual(held, p.view().active); + // Again, typed into: Enter lands in a reader of the held pane. + typeIn(p, " ffpick"); + const pk = live(p).?; + settle(p); + try std.testing.expectEqual(@as(usize, 2), count(p, pk)); + p.update(.{ .key = .{ .cp = Key.tab } }); + p.update(.{ .key = .{ .cp = Key.up } }); + p.update(.{ .key = .{ .cp = Key.enter } }); + const reader = Trail.readerOf(p, p.panes[held].?).?; + const t = &p.panes[reader].?.trail; + try std.testing.expect(t.n == 3 and t.steps[1] == .list); + try std.testing.expect(std.mem.startsWith(u8, t.steps[1].list.text.slice(), "Find pick 1/2 •1")); + const first = p.panes[reader].?.file.?.path; + try std.testing.expect(std.mem.eql(u8, first, a_path) or std.mem.eql(u8, first, b_path)); + // n: the other row, in place of the step. + p.view().active = reader; + p.update(.{ .key = .{ .cp = 'n', .text = "n" } }); + const now = Trail.readerOf(p, p.panes[held].?).?; + try std.testing.expect(!std.mem.eql(u8, p.panes[now].?.file.?.path, first)); + try std.testing.expectEqual(@as(u8, 3), p.panes[now].?.trail.n); + // SPC f f from the reader, which reads: it unrolls in the reader itself. + typeIn(p, " ff"); + try std.testing.expectEqual(@as(?usize, now), TagState.hostOf(p)); + try std.testing.expect(!live(p).?.made); + p.update(.{ .key = .{ .cp = Key.escape } }); + // A Look on the list word: the list again, its cursor and its mark. + Trail.lookStep(p, now, 1); + try std.testing.expect(live(p) == pk); + try std.testing.expectEqual(@as(u16, 1), p.view().tag_state.rows.at); + try std.testing.expectEqual(@as(usize, 1), pk.marks.items.len); + try std.testing.expectEqualStrings("pick", p.view().tag_state.field.text()); + p.update(.{ .key = .{ .cp = Key.escape } }); +} + +test "a picker from a reading pane unrolls in that pane, its own text set aside while it previews and back on Esc" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 50 }); + defer p.deinit(); + p.settings.jumps = .walk; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const a_path = try testFile(p, &tmp, "alpha.zig", "const alpha = 1;\n"); + defer p.gpa.free(a_path); + const b_path = try testFile(p, &tmp, "beta.zig", "one\ntwo\nthree\n"); + defer p.gpa.free(b_path); + look.lookAt(p, p.view().active, a_path); + const id = p.view().active; + try std.testing.expect(Trail.reading(p, p.panes[id].?)); + const npanes = paneCount(p); + open(p, id, .list, "Refs", "", "beta.zig:2:1 two\nalpha.zig:1:7 alpha\n"); + const pk = live(p).?; + try std.testing.expect(!pk.made); + try std.testing.expectEqual(npanes, paneCount(p)); + try std.testing.expectEqual(@as(?usize, id), TagState.hostOf(p)); + settle(p); + try std.testing.expectEqual(@as(usize, 2), count(p, pk)); + try std.testing.expectEqualStrings(b_path, p.panes[id].?.file.?.path); + try std.testing.expectEqual(@as(i32, 1), p.panes[id].?.body.cur_row); + try std.testing.expect(pk.aside != null); + // Down: the next row's file, on the frame after. + p.update(.{ .key = .{ .cp = Key.down } }); + try std.testing.expectEqualStrings(b_path, p.panes[id].?.file.?.path); + p.update(.tick); + try std.testing.expectEqualStrings(a_path, p.panes[id].?.file.?.path); + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expect(pk.aside == null); + try std.testing.expectEqualStrings(a_path, p.panes[id].?.file.?.path); + try std.testing.expect(p.panes[id].?.file.?.output == null); + try std.testing.expectEqual(npanes, paneCount(p)); +} diff --git a/core/Query.zig b/core/Query.zig index b272da4b..d97a7fd1 100644 --- a/core/Query.zig +++ b/core/Query.zig @@ -713,7 +713,6 @@ fn startSource(p: *Pardes, id: usize, q: *Query, source: Source, owner_id: ?usiz q.found.clearRetainingCapacity(); q.found_bytes.clearRetainingCapacity(); const dir = std.Io.Dir.path.dirname(rp.file.?.path) orelse "/"; - const gpa = p.gpa; switch (source) { // The files under the directory, listed once on the disk engine's // worker (rg --files, else the walk); each keystroke scores them. @@ -721,6 +720,19 @@ fn startSource(p: *Pardes, id: usize, q: *Query, source: Source, owner_id: ?usiz Stream.query(p, rp.serial, .files, "", dir, .now) catch |err| return p.reportError(.at(id), "search", err); if (p.fs.serving) Stream.step(p); }, + .recent, .panes, .symbols => gather(p, &q.names, source, dir, rp, owner_id), + else => {}, + } +} + +/// The names a Recent, Panes or Symbols query scores, into `names`: the +/// files opened lately, the panes but `self` (then the ones this session +/// closed), the declarations of pane `owner_id`'s text (asked of the +/// worker when it has none yet: declsArrived gathers them). Rows relative +/// to `dir`. A query pane's, and a picker's (Pick.zig). +pub fn gather(p: *Pardes, names: *Names, source: Source, dir: []const u8, self: ?*const Pane, owner_id: ?usize) void { + const gpa = p.gpa; + switch (source) { .recent => { var out: std.Io.Writer.Allocating = .init(gpa); defer out.deinit(); @@ -729,19 +741,19 @@ fn startSource(p: *Pardes, id: usize, q: *Query, source: Source, owner_id: ?usiz if (ln.len == 0) continue; const rel = relative(ln, dir); const path_end = std.mem.indexOfAny(u8, rel, ": ") orelse rel.len; - q.names.add(gpa, rel, 0, path_end, Names.baseOf(rel[0..path_end]), 0) catch break; + names.add(gpa, rel, 0, path_end, Names.baseOf(rel[0..path_end]), 0) catch break; } }, .panes => { for (p.panes) |slot| { const other = slot orelse continue; - if (other == rp or other.query != null) continue; + if (other == self or other.query != null) continue; var buf: [4096 + 32]u8 = undefined; const what: []const u8 = if (other.file) |f| f.path else if (other.command) |c| c else other.cwdSlice(); const row = std.fmt.bufPrint(&buf, config.pane_addr ++ "{d} {s}", .{ other.serial, relative(what, dir) }) catch continue; const key_at = std.mem.indexOfScalar(u8, row, ' ').? + 1; const ln = row[0 .. std.mem.indexOfAny(u8, row, "\r\n") orelse row.len]; - q.names.add(gpa, ln, key_at, ln.len -| key_at, Names.baseOf(ln[@min(key_at, ln.len)..]), other.serial) catch break; + names.add(gpa, ln, key_at, ln.len -| key_at, Names.baseOf(ln[@min(key_at, ln.len)..]), other.serial) catch break; } // Then the panes this session closed, the latest first, each // `(closed)` and dimmer (makeNameRows): Enter brings one back @@ -752,7 +764,7 @@ fn startSource(p: *Pardes, id: usize, q: *Query, source: Source, owner_id: ?usiz const row = std.fmt.bufPrint(&buf, config.pane_addr ++ "{d} {s}" ++ closed_word, .{ c.serial, relative(c.name, dir) }) catch continue; const key_at = std.mem.indexOfScalar(u8, row, ' ').? + 1; const key_len = row.len - closed_word.len - key_at; - q.names.add(gpa, row, key_at, key_len, Names.baseOf(row[key_at..][0..key_len]), c.serial) catch break; + names.add(gpa, row, key_at, key_len, Names.baseOf(row[key_at..][0..key_len]), c.serial) catch break; } }, .symbols => { @@ -769,7 +781,7 @@ fn startSource(p: *Pardes, id: usize, q: *Query, source: Source, owner_id: ?usiz const first = std.mem.trim(u8, header[0 .. std.mem.indexOfScalar(u8, header, '\n') orelse header.len], " \t\r"); var buf: [256 + 16]u8 = undefined; const row = std.fmt.bufPrint(&buf, "{d: >6} {s}", .{ d.start_line + 1, first[0..@min(first.len, 240)] }) catch continue; - q.names.add(gpa, row, 8, row.len - 8, 0, @intCast(d.start_line + 1)) catch break; + names.add(gpa, row, 8, row.len - 8, 0, @intCast(d.start_line + 1)) catch break; } }, else => {}, @@ -1253,10 +1265,11 @@ fn countGrepCurrent(q: *Query) void { if (c < q.items.items.len and q.items.items[c].kind == .hit) q.k = q.items.items[c].hit + 1; } -/// The disk engine's rows for query pane `q` (Stream.receive): a Grep's -/// lines (`path:line:col-end code`, relative to the pane's directory) kept -/// as found, a listing's names added to what Find scores. -pub fn take(p: *Pardes, q: *Query, kind: Stream.Kind, rows: []const u8) void { +/// The disk engine's rows for query pane `q` (Stream.receive), or for a +/// picker (Pick.zig: the same fields): a Grep's lines (`path:line:col-end +/// code`, relative to the pane's directory) kept as found, a listing's +/// names added to what Find scores. +pub fn take(p: *Pardes, q: anytype, kind: Stream.Kind, rows: []const u8) void { var lines = std.mem.splitScalar(u8, rows, '\n'); while (lines.next()) |ln| { if (ln.len == 0) continue; diff --git a/core/Stream.zig b/core/Stream.zig index 2f700cb4..49329361 100644 --- a/core/Stream.zig +++ b/core/Stream.zig @@ -713,6 +713,7 @@ pub fn receive(p: *Pardes, b: *const Batch) void { } } p.needs_frame = true; + if (panes.Pick.take(p, s.target, s.kind, b.rows)) return; const id = p.paneBySerial(s.target) orelse return; const q = p.panes[id].?.query orelse return; q.capped = s.state == .capped; @@ -735,6 +736,7 @@ fn receiveParse(p: *Pardes, b: *const Batch, serial: u32, revision: u32) void { if (p.tree_sitter_gpa.dupe(syntax.ContextDeclaration, b.decls)) |copy| { f.context.replace(p.tree_sitter_gpa, copy, revision); panes.Query.declsArrived(p, serial); + panes.Pick.declsArrived(p, serial); } else |_| {} }; p.needs_frame = true; diff --git a/core/TagState.zig b/core/TagState.zig new file mode 100644 index 00000000..f69404b2 --- /dev/null +++ b/core/TagState.zig @@ -0,0 +1,903 @@ +//! A tag out of rest (walk UI, pick-ui SPEC.md §3): which-key over a +//! root's level, rolled into the head or unrolled into the band, and the +//! typing states. Each view's own (the keyboard's transient state is the +//! view's, as `View.prefix` is: the coordinator's R4), in its digest and +//! dumps. A root and its keys are what keys.zig's leader, a text's normal +//! prefix or window mode already hold; this keeps what they do not: when +//! the level shows, whether it is unrolled, its cursor, the key it missed, +//! and the leaf each group ran last. +//! +//! The head (keys, level words, hints) is computed tag text drawn after +//! the prefix in place of the tag's own text (R1), never written into it: +//! `head`, which tagline.zig's `shownTail` reads. +const TagState = @This(); + +const std = @import("std"); +const pardes = @import("root.zig"); +const bindings = @import("bindings.zig"); +const tagline = @import("tagline.zig"); +const panes = @import("panes.zig"); +const Pardes = pardes.Pardes; +const View = Pardes.View; +const Pane = pardes.Pane; +const Root = bindings.Root; +const Field = @import("Field.zig"); +const Band = @import("Band.zig"); +const Names = @import("Names.zig"); + +/// The tag's states besides a root's level (which `kind` rest with a root +/// current is): `help`, a field over every leaf (SPEC §4.5); `describe`, +/// a sequence replayed in the tree (item 5); `pick`, a picker (Pick.zig, +/// SPEC §5). +pub const Kind = enum(u8) { rest, help, describe, pick }; + +pub const replica = .{ .len = .{ .{ "scope", "scope_n" }, .{ "hits", "nhits" } } }; + +kind: Kind = .rest, +/// The pane whose tag a typing state shows in, by serial: the one the +/// keyboard was on when it began (a picker's is the pane its Enter lands +/// in, SPEC §3.5). +host: u32 = 0, +/// Help's scope: the root and keys its `?` was struck under (`SPC l ?`), +/// or every root's leaves (`SPC ?`: null). +scope_root: ?Root = null, +scope: [8]u8 = undefined, +scope_n: u8 = 0, +/// describe-key's sequence (its root in scope_root, its keys in scope): +/// it reached a leaf, or nothing is bound to it. +found: bool = false, +missed: bool = false, +/// The field typed in the head (Field.zig): Help's query; a picker's, a +/// prompt's. +field: Field = .{}, +/// Help's rows, best first: an index of bindings.flat, or past it an +/// addon's word (`flat.len` + its slot in the registry); `ntotal` in scope. +hits: [max_hits]u16 = undefined, +nhits: u16 = 0, +ntotal: u16 = 0, +/// The rows' cursor (Band.Cursor). +rows: Band.Cursor = .{}, +/// The picker unrolled in the host's tag, by its serial (Pick.zig). +pick: u32 = 0, +/// The root the last key left current, whose delay `due_ns` counts. +root: ?Root = null, +/// When its level shows, on the session's clock: `asked` from its key +/// until the next advance (Pardes.advance), which has the time; 0 for none. +due_ns: u64 = 0, +unrolled: bool = false, +/// The unrolled level's cursor, a child's key: 0 is the leaf the group ran +/// last, else its first child. +hi: u8 = 0, +/// A key the level has no child for, shown struck until the next. +miss: u8 = 0, +/// The leaf each group ran last, by its key (bindings.groups): the cursor +/// starts there and the rolled level underlines it (SPEC §4.3). +used: [bindings.ngroups]u8 = @splat(0), +/// The panes showing a preview of what the state would do (a picker's +/// landing pane, a pane an action draws ghosts in), by slot: not dimmed +/// while the others are (SPEC §3.6). Set by the state that previews. +previewing: std.StaticBitSet(pardes.MAX_PANES) = .empty, + +/// describe-key (SPEC §4.5), in the tag of pane `id`: the next keys are +/// replayed in the tree. +pub fn openDescribe(p: *Pardes, id: usize) void { + const pane = p.panes[id] orelse return; + toRest(p); + const s = &p.view().tag_state; + s.kind = .describe; + s.host = pane.serial; + s.scope_root = null; + s.scope_n = 0; + s.found = false; + s.missed = false; +} + +/// A key of describe-key's sequence: the first a root's, then down its +/// tree to a group (more keys) or a leaf (found), or to nothing (missed). A +/// key after a sequence ended starts the next. +pub fn describeKey(p: *Pardes, key: pardes.Key) void { + const s = &p.view().tag_state; + if (s.found or s.missed) { + s.scope_root = null; + s.scope_n = 0; + s.found = false; + s.missed = false; + } + const root = s.scope_root orelse { + s.scope_root = bindings.rootOf(key); + if (s.scope_root == null or s.scope_root == .register) { + // Not a root: the key alone, struck. + s.scope_root = null; + s.scope[0] = if (key.cp >= 0x20 and key.cp < 0x7f and !key.ctrl and !key.alt) @intCast(key.cp) else '?'; + s.scope_n = 1; + s.missed = true; + } + return; + }; + const printable = key.cp >= 0x20 and key.cp < 0x7f and !key.ctrl and !key.alt; + if (!printable or s.scope_n == s.scope.len) { + s.missed = true; + return; + } + const k: u8 = @intCast(key.cp); + var children: [bindings.max_children]bindings.Child = undefined; + const child = for (bindings.level(p, root, s.scope[0..s.scope_n], &children)) |c| { + if (c.key == k) break c; + } else null; + s.scope[s.scope_n] = k; + s.scope_n += 1; + const c = child orelse { + s.missed = true; + return; + }; + if (!c.group) s.found = true; +} + +/// Help's rows at most: every leaf of every root, and the registry's words. +pub const max_hits = bindings.flat.len + 64; + +/// A root struck, its time not had yet (as Pane.question_asked: the step +/// that strikes it reads no clock). +pub const asked: u64 = std.math.maxInt(u64); + +/// The root current in view `v` and the keys typed under it: SPC's +/// leader keys, window mode, or the helix prefix the text with the +/// keyboard waits on. A view not live has its leader and window mode +/// alone (its texts' prefixes are in their panes' shares). +pub const Current = struct { root: Root, path: []const u8 }; + +pub fn current(p: *const Pardes, v: *const View) ?Current { + if (v.prefix == .leader) return .{ .root = .leader, .path = v.leader_keys[0..v.leader_n] }; + if (v.window_pick != null) return .{ .root = .window, .path = "" }; + if (v != p.view() or v.header != null) return null; + const pane = p.panes[v.active] orelse return null; + const t = if (pane.focus == .tag) &pane.tag else &pane.body; + const prefix = t.normal.prefix orelse return null; + const root: Root = switch (prefix) { + .goto_prefix => .goto, + .view_prefix => if (t.normal.sticky) .view_sticky else .view, + .match_prefix => if (t.normal.match_sub == null) .match else return null, + .next_prefix => .next, + .prev_prefix => .prev, + .register_prefix => .register, + else => return null, + }; + return .{ .root = root, .path = "" }; +} + +/// Whether view `v`'s current root has shown its level: its delay is up. +pub fn shown(p: *const Pardes, v: *const View) bool { + const s = &v.tag_state; + if (s.unrolled) return true; // Down shows it at once + return s.due_ns != asked and s.due_ns != 0 and p.clock.now_ns >= s.due_ns; +} + +/// The pane whose tag is out of rest in the live view, if one is: the one +/// with the keyboard while a root's key cell or level shows. Cheap at rest, +/// as every tag's text asks it. +pub fn hostOf(p: *const Pardes) ?usize { + const v = p.view(); + if (v.tag_state.kind == .rest and v.prefix == .none and v.window_pick == null and !textPrefix(p, v)) return null; + if (v.tag_state.kind != .rest) return for (p.panes, 0..) |slot, i| { + if (slot) |pane| if (pane.serial == v.tag_state.host) break i; + } else null; + const cur = current(p, v) orelse return null; + if (!bindings.info.get(cur.root).at_once and !shown(p, v)) return null; + return if (p.panes[v.active] != null) v.active else null; +} + +fn textPrefix(p: *const Pardes, v: *const View) bool { + const pane = p.panes[v.active] orelse return false; + return pane.body.normal.prefix != null or pane.tag.normal.prefix != null; +} + +/// After a key (keys.handleKey): a root newly current starts its delay; one +/// gone leaves the level as it was never there. A root a state put back +/// (Help's Backspace) is current already, its level as that state left it. +pub fn follow(p: *Pardes) void { + const v = p.view(); + const s = &v.tag_state; + const now = if (current(p, v)) |cur| cur.root else null; + if (now == s.root) return; + s.root = now; + s.unrolled = false; + s.hi = 0; + s.miss = 0; + s.due_ns = if (now == null) 0 else asked; +} + +/// Back to rest in the live view: no root waits, no typing state, nothing +/// unrolled (a word run from the band, Esc in a typing state). +pub fn toRest(p: *Pardes) void { + // A picker rolls up first: every body it previewed in as it was. + @import("Pick.zig").rollUp(p); + const v = p.view(); + v.prefix = .none; + v.window_pick = null; + if (p.panes[v.active]) |pane| { + pane.body.normal.clear(); + pane.tag.normal.clear(); + } + const s = &v.tag_state; + s.kind = .rest; + s.previewing = .empty; + s.root = null; + s.due_ns = 0; + s.unrolled = false; + s.hi = 0; + s.miss = 0; +} + +/// The root a key strikes when its time is had (Pardes.advance). +pub fn dated(p: *Pardes, now_ns: u64) void { + for (&p.views) |*slot| if (slot.*) |*v| { + const s = &v.tag_state; + if (s.due_ns != asked) continue; + s.due_ns = if (s.root) |r| now_ns + bindings.info.get(r).delay_ns else 0; + }; +} + +/// When a level next shows, for the loop's wake (Pardes.nextWake): a root +/// struck and not dated yet wants the next frame, whose advance dates it +/// (a pump settles its keys after its advance: a wake that waited for +/// the date would sleep until the next key, the level never shown). +pub fn wake(p: *const Pardes) ?u64 { + var soonest: ?u64 = null; + for (p.views) |slot| if (slot) |v| { + var due = v.tag_state.due_ns; + if (due == asked) due = p.clock.stepped_ns + pardes.frame_ns; + if (due == 0 or due <= p.clock.stepped_ns) continue; + soonest = if (soonest) |n| @min(n, due) else due; + }; + return soonest; +} + +/// The last leaf run in the current level, as the line under it says it +/// (Messages' leader band): `k Hover: its summary (last used here)`, while +/// the level is shown rolled. +pub fn lastUsed(p: *const Pardes, v: *const View, buf: []u8) ?[]const u8 { + const s = &v.tag_state; + if (s.kind != .rest or s.unrolled or !shown(p, v)) return null; + const cur = current(p, v) orelse return null; + const node = bindings.nodeAt(cur.root, cur.path) orelse return null; + const key = s.used[node.group]; + if (key == 0) return null; + var children: [bindings.max_children]bindings.Child = undefined; + for (bindings.level(p, cur.root, cur.path, &children)) |c| if (c.key == key) { + var doc_buf: [160]u8 = undefined; + return std.fmt.bufPrint(buf, "{s} {s}: {s} (last used here)", .{ bindings.keyName(c.key), c.label, bindings.docOf(cur.root, c, &doc_buf) }) catch null; + }; + return null; +} + +/// The cursor put on row `index` of the band's first step (a click on it). +pub fn point(p: *Pardes, index: u16) void { + const v = p.view(); + const s = &v.tag_state; + if (s.kind == .pick) { + s.rows.at = index; + return; + } + const cur = current(p, v) orelse return; + var children: [bindings.max_children]bindings.Child = undefined; + const level = bindings.level(p, cur.root, cur.path, &children); + if (index < level.len) s.hi = level[index].key; +} + +/// Remember `key` as the leaf run last at `path` under `root`. +pub fn ran(v: *View, root: Root, path: []const u8, key: u8) void { + const node = bindings.nodeAt(root, path) orelse return; + v.tag_state.used[node.group] = key; +} + +/// Help over the tree (SPEC §4.5), in the tag of the pane with the +/// keyboard: its field empty, its rows every leaf `root` and `path` lead +/// to, or with no root every leaf of every root. The level it was struck +/// from goes. +pub fn openHelp(p: *Pardes, root: ?Root, path: []const u8) void { + const v = p.view(); + const pane = p.panes[v.active] orelse return; + toRest(p); + const s = &v.tag_state; + s.kind = .help; + s.host = pane.serial; + s.scope_root = root; + s.scope_n = @intCast(@min(path.len, s.scope.len)); + @memcpy(s.scope[0..s.scope_n], path[0..s.scope_n]); + s.field.clear(); + s.rows = .{}; + filter(p); +} + +/// Help's rows again for its field: the leaves in its scope this view +/// takes, scored by the query pane's scorer (Names.match) and best first, +/// or in the tree's order while the field is empty. Each key's, over the +/// tree's leaves and the registry's words: a fixed count (max_hits). +pub fn filter(p: *Pardes) void { + const s = &p.view().tag_state; + const q = s.field.text(); + const empty = std.mem.trim(u8, q, " ").len == 0; + var found: [max_hits]struct { at: u16, score: i32 } = undefined; + var n: usize = 0; + var total: u16 = 0; + for (bindings.flat, 0..) |f, i| { + if (!inScope(s, f.root, f.path)) continue; + if (f.node.leaf.? == .builtin and !pardes.builtins.registry.here(p, f.node.leaf.?.builtin)) continue; + total += 1; + const score = if (empty) 0 else Names.match(q, f.row, f.lower, 0, null, null) orelse continue; + found[n] = .{ .at = @intCast(i), .score = score }; + n += 1; + } + for (p.kinds.words[0..p.kinds.nwords], 0..) |*w, k| { + if (w.leader.len == 0 or !inScope(s, .leader, w.leader.slice())) continue; + total += 1; + var buf: [row_max]u8 = undefined; + var low: [row_max]u8 = undefined; + const row = wordRow(w, &buf); + for (row, 0..) |c, i| low[i] = std.ascii.toLower(c); + const score = if (empty) 0 else Names.match(q, row, low[0..row.len], 0, null, null) orelse continue; + found[n] = .{ .at = @intCast(bindings.flat.len + k), .score = score }; + n += 1; + } + const Found = @TypeOf(found[0]); + if (!empty) std.sort.pdq(Found, found[0..n], {}, struct { + fn lt(_: void, a: Found, b: Found) bool { + return a.score > b.score or (a.score == b.score and a.at < b.at); + } + }.lt); + for (found[0..n], 0..) |f, i| s.hits[i] = f.at; + s.nhits = @intCast(n); + s.ntotal = total; + s.rows.at = 0; +} + +fn inScope(s: *const TagState, root: Root, path: []const u8) bool { + const r = s.scope_root orelse return true; + return r == root and std.mem.startsWith(u8, path, s.scope[0..s.scope_n]); +} + +/// The longest row Help makes of an addon's word: SPC, eight keys, a +/// 32-byte name. +pub const row_max = 80; + +/// An addon's word as Help's row: `SPC x y · Name · addon`. +fn wordRow(w: *const pardes.Kind.Word, buf: *[row_max]u8) []const u8 { + var out = std.Io.Writer.fixed(buf); + out.writeAll("SPC") catch {}; + for (w.leader.slice()) |k| out.print(" {s}", .{bindings.keyName(k)}) catch {}; + out.print(" · {s} · addon", .{w.name.slice()}) catch {}; + return out.buffered(); +} + +/// Help's hit `at` as a leaf: its row, its root and keys, and the child +/// its level shows it as (its doc's). +pub const Leaf = struct { row: []const u8, root: Root, path: []const u8, child: bindings.Child }; + +pub fn helpLeaf(p: *const Pardes, at: u16, buf: *[row_max]u8) Leaf { + if (at < bindings.flat.len) { + const f = bindings.flat[at]; + return .{ .row = f.row, .root = f.root, .path = f.path, .child = .{ .key = f.node.key, .label = f.node.label, .node = f.node, .lsp = f.node.lsp } }; + } + const w = &p.kinds.words[at - bindings.flat.len]; + const keys = w.leader.slice(); + return .{ .row = wordRow(w, buf), .root = .leader, .path = keys, .child = .{ .key = keys[keys.len - 1], .label = w.name.slice(), .word = w } }; +} + +/// How a span of the head is drawn (draw.zig paintPaneTag). +pub const Style = enum { key, dim, under, strike }; +pub const Span = struct { lo: u32, hi: u32, style: Style }; +/// The head: its text, the spans drawn apart, and the caret in it when the +/// head is typed in. +pub const Head = struct { + text: []const u8, + spans: []const Span = &.{}, + /// Its first `cells` spans are its key cells, which the band's spines + /// hang from (Band.zig). + cells: u8 = 0, + caret: ?u32 = null, +}; + +const Builder = struct { + arena: std.mem.Allocator, + text: std.ArrayList(u8) = .empty, + spans: std.ArrayList(Span) = .empty, + cells: u8 = 0, + + fn put(b: *Builder, s: []const u8) !void { + try b.text.appendSlice(b.arena, s); + } + fn styled(b: *Builder, s: []const u8, style: Style) !void { + const lo: u32 = @intCast(b.text.items.len); + try b.text.appendSlice(b.arena, s); + try b.spans.append(b.arena, .{ .lo = lo, .hi = @intCast(b.text.items.len), .style = style }); + } + /// The keys typed as 2-cell key cells: the root's, then each key. + fn keyCells(b: *Builder, root: Root, path: []const u8) !void { + try b.styled(bindings.info.get(root).cell, .key); + try b.put(" "); + for (path) |k| { + try b.styled(if (k == ' ') "␣" else bindings.keyName(k), .key); + try b.put(" "); + } + b.cells = @intCast(b.spans.items.len); + } + fn done(b: *const Builder) Head { + return .{ .text = b.text.items, .spans = b.spans.items, .cells = b.cells }; + } +}; + +/// The head of pane `pane`'s tag while it is out of rest in the live view, +/// null at rest. +pub fn head(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) !?Head { + const id = hostOf(p) orelse return null; + if (p.panes[id] != pane) return null; + const v = p.view(); + const s = &v.tag_state; + var b: Builder = .{ .arena = arena }; + switch (s.kind) { + .rest => {}, + // `Help`, its scope's keys, the field, its count: + // ` Help ␣ l hov 2/17`. + .help => { + try b.put(" Help "); + if (s.scope_root) |r| try b.keyCells(r, s.scope[0..s.scope_n]); + var h = b.done(); + h.caret = @intCast(b.text.items.len + s.field.caret); + try b.put(s.field.text()); + try b.text.print(arena, " {d}/{d}", .{ s.nhits, s.ntotal }); + h.text = b.text.items; + h.spans = b.spans.items; + return h; + }, + // `Keys`, then the keys replayed: `Keys g ▸ d Def`; struck, + // `runs nothing`. + .describe => { + try b.put(" Keys "); + if (s.missed) { + var buf: [64]u8 = undefined; + const keys = if (s.scope_root) |r| bindings.chord(r, s.scope[0..s.scope_n], &buf) else bindings.keyName(s.scope[0]); + try b.styled(keys, .strike); + // A key no root is: normal mode's own, no sequence. + try b.put(if (s.scope_root == null) " starts no sequence" else " runs nothing"); + } else if (s.scope_root) |r| { + const n = s.scope_n - @intFromBool(s.found); + try b.keyCells(r, s.scope[0..n]); + if (s.found) { + var children: [bindings.max_children]bindings.Child = undefined; + const k = s.scope[n]; + try b.styled("▸", .key); + try b.put(" "); + try b.styled(bindings.keyName(k), .key); + for (bindings.level(p, r, s.scope[0..n], &children)) |c| if (c.key == k) { + try b.put(" "); + try b.put(c.label); + }; + try b.put(" ⏎ run · esc"); + } else try b.put("…"); + } else try b.put("… press a key or a sequence · esc"); + return b.done(); + }, + .pick => return @import("Pick.zig").head(p, arena, pane), + } + const cur = current(p, v) orelse return null; + try b.put(" "); + try b.keyCells(cur.root, cur.path); + if (!shown(p, v)) { + try b.put("…"); + return b.done(); + } + const node = bindings.nodeAt(cur.root, cur.path) orelse return b.done(); + if (s.unrolled) { + try b.put(if (cur.path.len == 0) bindings.info.get(cur.root).label else node.label); + try b.put(" ↑ roll up · ? field · esc"); + return b.done(); + } + try b.styled("▸", .key); + // The rolled level wraps to three rows at most (SPEC §3.6): what does + // not fit is `…`, and `↓` unrolls it whole. A terminal's to the rows its + // own text takes: its pty is its body, and a which-key that took a row + // would resize the program under it at every SPC. Every cell is + // counted: the prefix, each child with its separator and a group's + // `…`, the ` …` after a child that is not the last, a struck key, the + // hint (left out, a terminal's tag took a row more at some widths). + const hint = " ↓ unroll · ? help"; + const more = " …"; + const prefix = try tagline.prefixIn(p, arena, pane); + const tab = p.settings.tab; + const most: usize = if (pane.isTerminal()) @import("layout.zig").wantedTagRows(p, id) else 3; + const struck: usize = if (s.miss != 0) 1 + panes.File.displayWidth(tab, bindings.keyName(s.miss)) else 0; + const room = most * tagline.tagWidth(p, id) -| panes.File.displayWidth(tab, prefix) -| panes.File.displayWidth(tab, hint) -| struck; + var children: [bindings.max_children]bindings.Child = undefined; + const level = bindings.level(p, cur.root, cur.path, &children); + const used = s.used[node.group]; + var width = panes.File.displayWidth(tab, b.text.items); + for (level, 0..) |c, i| { + width += @as(usize, if (i == 0) 1 else 2) + panes.File.displayWidth(tab, bindings.keyName(c.key)) + 1 + panes.File.displayWidth(tab, c.label) + @intFromBool(c.group); + if (width + @as(usize, if (i + 1 < level.len) panes.File.displayWidth(tab, more) else 0) > room) { + try b.put(more); + break; + } + try b.put(if (i == 0) " " else " "); + const lo: u32 = @intCast(b.text.items.len); + try b.styled(bindings.keyName(c.key), .key); + try b.put(" "); + try b.put(c.label); + if (c.group) try b.put("…"); + const hi: u32 = @intCast(b.text.items.len); + if (bindings.dimmed(pane, c)) try b.spans.append(arena, .{ .lo = lo, .hi = hi, .style = .dim }); + if (c.key == used) try b.spans.append(arena, .{ .lo = lo, .hi = hi, .style = .under }); + } + if (s.miss != 0) { + try b.put(" "); + try b.styled(bindings.keyName(s.miss), .strike); + } + try b.put(hint); + return b.done(); +} + +fn testTag(p: *Pardes, arena: std.mem.Allocator) ![]const u8 { + return tagline.tagText(p, arena, p.panes[p.view().active].?); +} + +test "SPC writes its key cell at once and its level 250 ms on; g changes nothing until 500 ms, and gg never" { + const Key = pardes.Key; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 30 }); + defer p.deinit(); + _ = try p.setTestFile("one\ntwo\nthree\n"); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + const a = frame.allocator(); + p.clock.now_ns = 5 * std.time.ns_per_s; + p.clock.stepped_ns = p.clock.now_ns; + p.sync(); + const rest = try a.dupe(u8, try testTag(p, a)); + // SPC: its cell at once, the own words gone under the head. + p.update(.{ .key = .{ .cp = ' ' } }); + try std.testing.expect(std.mem.endsWith(u8, try testTag(p, a), " ␣ …")); + // Its time is the next advance's; the level waits 250 ms from it, and + // the loop wakes for it then. + try std.testing.expectEqual(asked, p.view().tag_state.due_ns); + p.advance(p.clock.now_ns); + const due = p.view().tag_state.due_ns; + try std.testing.expectEqual(p.clock.now_ns + 250 * std.time.ns_per_ms, due); + const woken = p.nextWake().?; + try std.testing.expect(woken >= due and woken < due + pardes.frame_ns); + p.clock.now_ns = due - 1; + try std.testing.expect(std.mem.endsWith(u8, try testTag(p, a), " ␣ …")); + p.clock.now_ns = due; + const level = try testTag(p, a); + try std.testing.expect(std.mem.indexOf(u8, level, " ␣ ▸ b buffer…") != null); + try std.testing.expect(std.mem.indexOf(u8, level, "l lsp…") != null); + try std.testing.expect(std.mem.endsWith(u8, level, "↓ unroll · ? help")); + // Down a level: its keys, its children. + p.update(.{ .key = .{ .cp = 'l' } }); + try std.testing.expect(std.mem.indexOf(u8, try testTag(p, a), " ␣ l ▸ a CodeAction b Callstack") != null); + // Esc: rest, the tag as it was. + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expectEqualStrings(rest, try testTag(p, a)); + try std.testing.expectEqual(@as(u64, 0), p.view().tag_state.due_ns); + + // g: nothing until 500 ms pass with no next key, then its cell and + // its level together. + p.update(.{ .key = .{ .cp = 'g' } }); + try std.testing.expectEqualStrings(rest, try testTag(p, a)); + p.advance(p.clock.now_ns); + const g_due = p.view().tag_state.due_ns; + try std.testing.expectEqual(p.clock.now_ns + 500 * std.time.ns_per_ms, g_due); + p.clock.now_ns = g_due - 1; + try std.testing.expectEqualStrings(rest, try testTag(p, a)); + p.clock.now_ns = g_due; + try std.testing.expect(std.mem.indexOf(u8, try testTag(p, a), " g ▸ ") != null); + try std.testing.expect(std.mem.indexOf(u8, try testTag(p, a), "d Def") != null); + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expectEqualStrings(rest, try testTag(p, a)); + + // gg at speed: the tag never changes, the cursor goes to the top. + const pane = p.panes[p.view().active].?; + pane.body.cur_row = 2; + p.update(.{ .key = .{ .cp = 'g' } }); + try std.testing.expectEqualStrings(rest, try testTag(p, a)); + p.update(.{ .key = .{ .cp = 'g' } }); + try std.testing.expectEqualStrings(rest, try testTag(p, a)); + try std.testing.expectEqual(@as(i32, 0), pane.body.cur_row); + p.advance(p.clock.now_ns + std.time.ns_per_s); + try std.testing.expectEqualStrings(rest, try testTag(p, a)); + try std.testing.expect(p.view().tag_state.root == null); +} + +test "a leaf run from a level is remembered: underlined there, and said on the line under it" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 30 }); + defer p.deinit(); + _ = try p.setTestFile("one\n"); + p.clock.now_ns = 5 * std.time.ns_per_s; + p.clock.stepped_ns = p.clock.now_ns; + // SPC t w: Wrap, run from SPC t. + for (" tw") |c| p.update(.{ .key = .{ .cp = c } }); + try std.testing.expectEqual(@as(u8, 'w'), p.view().tag_state.used[bindings.nodeAt(.leader, "t").?.group]); + var buf: [192]u8 = undefined; + // Back in SPC t, rolled: the line under it says Wrap ran last here. + for (" t") |c| p.update(.{ .key = .{ .cp = c } }); + p.advance(p.clock.now_ns); + try std.testing.expect(lastUsed(p, p.view(), &buf) == null); // not shown yet + p.clock.now_ns = p.view().tag_state.due_ns; + const said = lastUsed(p, p.view(), &buf).?; + try std.testing.expect(std.mem.startsWith(u8, said, "w Wrap: ")); + try std.testing.expect(std.mem.endsWith(u8, said, " (last used here)")); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + const h = (try head(p, frame.allocator(), p.panes[p.view().active].?)).?; + const under = for (h.spans) |span| { + if (span.style == .under) break h.text[span.lo..span.hi]; + } else ""; + try std.testing.expectEqualStrings("w Wrap", under); + // Enter, rolled, runs it again. + const wrapped = p.settings.wrap; + p.update(.{ .key = .{ .cp = pardes.Key.enter } }); + try std.testing.expect(p.settings.wrap != wrapped); + try std.testing.expect(p.view().prefix == .none); +} + +test "a key the level has no child for is struck and the level stays; Backspace goes up a level" { + const Key = pardes.Key; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 30 }); + defer p.deinit(); + _ = try p.setTestFile("one\n"); + for (" l") |c| p.update(.{ .key = .{ .cp = c } }); + p.update(.{ .key = .{ .cp = 'z' } }); + try std.testing.expect(p.view().prefix == .leader); + try std.testing.expectEqual(@as(u8, 'z'), p.view().tag_state.miss); + try std.testing.expectEqualStrings("l", p.view().leader_keys[0..p.view().leader_n]); + p.update(.{ .key = .{ .cp = Key.backspace } }); + try std.testing.expectEqual(@as(u8, 0), p.view().leader_n); + try std.testing.expect(p.view().prefix == .leader); + p.update(.{ .key = .{ .cp = Key.backspace } }); + try std.testing.expect(p.view().prefix == .none); +} + +test "SPC ? is Help over every root's leaves: typed in its head, filtered by the scorer, its rows and the cursor's doc in the band; Enter runs the row" { + const Key = pardes.Key; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 40 }); + defer p.deinit(); + const pane = try p.setTestFile("one\n"); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + const a = frame.allocator(); + p.update(.{ .key = .{ .cp = ' ' } }); + p.update(.{ .key = .{ .cp = '?' } }); + const s = &p.view().tag_state; + try std.testing.expectEqual(Kind.help, s.kind); + try std.testing.expect(p.view().prefix == .none); + // Every leaf of every root: SPC's, the helix prefixes', window mode's. + try std.testing.expect(s.nhits == s.ntotal and s.ntotal > 100); + for ("wrap") |c| p.update(.{ .key = .{ .cp = c } }); + try std.testing.expectEqualStrings("wrap", s.field.text()); + try std.testing.expect(s.nhits > 0 and s.nhits < s.ntotal); + var buf: [row_max]u8 = undefined; + try std.testing.expectEqualStrings("SPC t w · Wrap · view", helpLeaf(p, s.hits[0], &buf).row); + const tag = try testTag(p, a); + try std.testing.expect(std.mem.indexOf(u8, tag, " Help wrap ") != null); + // Its box says it is typed in; the band holds its rows and a doc. + _ = try p.render(a); + const r = p.view().rects[p.view().active]; + try std.testing.expectEqualStrings("^", p.surface.at(r.x, r.y).grapheme()); + try std.testing.expect(pane.band_rows >= 4); + try std.testing.expect(p.surface.cursor != null and p.surface.cursor.?.bar); + // Enter runs it, typed as its keys, and the tag is back at rest. + const wrapped = p.settings.wrap; + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expect(p.settings.wrap != wrapped); + try std.testing.expectEqual(Kind.rest, s.kind); + try std.testing.expectEqual(@as(u16, 0), pane.band_rows); +} + +test "? down a level is Help for that level; Backspace on its empty field goes back to the level, Esc to rest" { + const Key = pardes.Key; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 40 }); + defer p.deinit(); + _ = try p.setTestFile("one\n"); + for (" l?") |c| p.update(.{ .key = .{ .cp = c } }); + const s = &p.view().tag_state; + try std.testing.expectEqual(Kind.help, s.kind); + var buf: [row_max]u8 = undefined; + for (s.hits[0..s.nhits]) |at| try std.testing.expect(std.mem.startsWith(u8, helpLeaf(p, at, &buf).row, "SPC l ")); + try std.testing.expect(s.nhits >= 15); + // g ?: the goto level's. + p.update(.{ .key = .{ .cp = Key.backspace } }); + try std.testing.expectEqual(Kind.rest, s.kind); + try std.testing.expect(p.view().prefix == .leader and s.unrolled); + try std.testing.expectEqualStrings("l", p.view().leader_keys[0..p.view().leader_n]); + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expect(p.view().prefix == .none); + for ("g?") |c| p.update(.{ .key = .{ .cp = c } }); + try std.testing.expectEqual(Kind.help, s.kind); + for (s.hits[0..s.nhits]) |at| try std.testing.expect(std.mem.startsWith(u8, helpLeaf(p, at, &buf).row, "g ")); + // Down moves the cursor; Enter runs `g g`. + const pane = p.panes[p.view().active].?; + pane.body.cur_row = 0; + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expectEqual(Kind.rest, s.kind); +} + +test "SPC h k is describe-key: g d replays `g ▸ d Def` with its level and doc under the tag; every root answers; Enter runs it; an unbound one runs nothing" { + const Key = pardes.Key; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 40 }); + defer p.deinit(); + const pane = try p.setTestFile("one\ntwo\nthree\n"); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + const a = frame.allocator(); + for (" hk") |c| p.update(.{ .key = .{ .cp = c } }); + const s = &p.view().tag_state; + try std.testing.expectEqual(Kind.describe, s.kind); + try std.testing.expect(std.mem.indexOf(u8, try testTag(p, a), " Keys …") != null); + for ("gd") |c| p.update(.{ .key = .{ .cp = c } }); + try std.testing.expect(s.found); + try std.testing.expect(std.mem.indexOf(u8, try testTag(p, a), " Keys g ▸ d Def") != null); + // The level unrolled under the tag, the leaf on the cursor, its doc. + try std.testing.expect(pane.band_rows >= 4); + _ = try p.render(a); + const layer = &p.surface.tag_layers[pardes.BAND_LAYER]; + var text: std.ArrayList(u8) = .empty; + for (0..layer.rows) |row| for (layer.cells[row * layer.cols ..][0..layer.cols]) |cell| try text.appendSlice(a, cell.grapheme()); + try std.testing.expect(std.mem.indexOf(u8, text.items, "▶ d Def") != null); + try std.testing.expect(std.mem.indexOf(u8, text.items, "keys g d") != null); + // Another sequence from the next key: ] f, then SPC l r. + for ("]f") |c| p.update(.{ .key = .{ .cp = c } }); + try std.testing.expect(std.mem.indexOf(u8, try testTag(p, a), " Keys ] ▸ f function") != null); + for (" lr") |c| p.update(.{ .key = .{ .cp = c } }); + try std.testing.expect(std.mem.indexOf(u8, try testTag(p, a), " Keys ␣ l ▸ r Rename") != null); + // Unbound: struck, runs nothing. + for ("gq") |c| p.update(.{ .key = .{ .cp = c } }); + try std.testing.expect(s.missed); + const struck = (try head(p, a, pane)).?; + try std.testing.expect(std.mem.endsWith(u8, struck.text, "g q runs nothing")); + try std.testing.expectEqual(Style.strike, struck.spans[0].style); + // Enter runs a found one, typed as its keys: g e, the last line. + for ("ge") |c| p.update(.{ .key = .{ .cp = c } }); + try std.testing.expect(s.found); + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expectEqual(Kind.rest, s.kind); + try std.testing.expectEqual(@as(i32, 2), pane.body.cur_row); + try std.testing.expectEqual(@as(u16, 0), pane.band_rows); +} + +test "C-w's level is window mode's, shown at once and kept while its keys move the outline, until Enter" { + const Key = pardes.Key; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 40 }); + defer p.deinit(); + _ = try p.setTestFile("one\n"); + const top = p.view().active; + p.newScratchBelow(top); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + const a = frame.allocator(); + p.update(.{ .key = .{ .cp = 'w', .ctrl = true } }); + try std.testing.expect(p.view().window_pick != null); + try std.testing.expect(std.mem.endsWith(u8, try testTag(p, a), " C-w …")); + p.advance(p.clock.now_ns); + p.clock.now_ns = p.view().tag_state.due_ns; + try std.testing.expect(std.mem.indexOf(u8, try testTag(p, a), " C-w ▸ c Collapse d Del h Left j Down k Up l Right") != null); + // Sticky: a move keeps the level. + p.update(.{ .key = .{ .cp = 'k' } }); + try std.testing.expect(p.view().window_pick != null); + try std.testing.expect(std.mem.indexOf(u8, try testTag(p, a), " C-w ▸ ") != null); + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expect(p.view().window_pick == null); + try std.testing.expect(p.view().tag_state.root == null); +} + +test "a root struck in a pump, after its advance, wakes the loop for the next frame, which dates it, then for its level" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 30 }); + defer p.deinit(); + _ = try p.setTestFile("one\n"); + while (p.nextEffect()) |_| {} + p.advance(5 * std.time.ns_per_s); + try std.testing.expect(p.nextWake() == null); + // The pump's order: its advance, then its keys (Pardes.pump, settle). + p.update(.{ .key = .{ .cp = ' ' } }); + const first = p.nextWake().?; + try std.testing.expectEqual(p.clock.stepped_ns + pardes.frame_ns, first); + p.advance(first); + const due = p.view().tag_state.due_ns; + try std.testing.expectEqual(first + 250 * std.time.ns_per_ms, due); + const second = p.nextWake().?; + try std.testing.expect(second >= due and second < due + pardes.frame_ns); + p.advance(second); + try std.testing.expect(shown(p, p.view())); + try std.testing.expect(p.nextWake() == null); +} + +test "a terminal's rolled level takes no more tag rows than its own text: its pty keeps its size" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const p = try Pardes.init(std.testing.allocator, .{ .file = "mise.toml", .cols = 40, .rows = 30 }); + defer p.deinit(); + _ = pardes.exec.spawnTty(p, 0); + const shell = p.view().active; + const pane = p.panes[shell].?; + pane.body.mode = .normal; + p.sync(); + const rows, const tag_rows = .{ pane.rows, pane.tag_rows }; + p.update(.{ .key = .{ .cp = ' ' } }); + p.advance(p.clock.now_ns); + p.clock.now_ns = p.view().tag_state.due_ns; + p.sync(); + try std.testing.expect(hostOf(p) == shell); + try std.testing.expectEqual(tag_rows, pane.tag_rows); + try std.testing.expectEqual(rows, pane.rows); +} + +test "a rolled level fits its rows at every width: its `…`, its groups' `…` and a struck key are counted" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 }); + defer p.deinit(); + _ = try p.setTestFile("one\n"); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + const a = frame.allocator(); + const pane = p.panes[p.view().active].?; + for ([_]pardes.Key{ .{ .cp = ' ' }, .{ .cp = 'w', .ctrl = true } }) |root| for ([_]bool{ false, true }) |struck| { + p.update(.{ .key = root }); + p.advance(p.clock.now_ns); + p.clock.now_ns = p.view().tag_state.due_ns; + // `x` is a child of neither level: struck, the level stays. + if (struck) p.update(.{ .key = .{ .cp = 'x' } }); + for (30..161) |cols| { + p.update(.{ .resize = .{ .cols = @intCast(cols), .rows = 40 } }); + try std.testing.expect(hostOf(p) != null); + try std.testing.expect((try tagline.shownTag(p, a, pane)).rows() <= 3); + } + toRest(p); + p.update(.{ .resize = .{ .cols = 120, .rows = 40 } }); + }; +} + +test "a terminal's rolled level keeps its tag rows at every width, C-w's as SPC's: its pty is never resized" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const p = try Pardes.init(std.testing.allocator, .{ .file = "mise.toml", .cols = 100, .rows = 30 }); + defer p.deinit(); + _ = pardes.exec.spawnTty(p, 0); + const shell = p.view().active; + const pane = p.panes[shell].?; + pane.body.mode = .normal; + for ([_]pardes.Key{ .{ .cp = ' ' }, .{ .cp = 'w', .ctrl = true } }) |root| for (30..131) |cols| { + p.update(.{ .resize = .{ .cols = @intCast(cols), .rows = 30 } }); + p.sync(); + const rows, const tag_rows = .{ pane.rows, pane.tag_rows }; + p.update(.{ .key = root }); + // Its key cell alone, before the level shows: shorter than the + // tag's own text, the rows it had. + p.sync(); + try std.testing.expect(hostOf(p) == shell); + try std.testing.expectEqual(tag_rows, pane.tag_rows); + try std.testing.expectEqual(rows, pane.rows); + p.advance(p.clock.now_ns); + p.clock.now_ns = p.view().tag_state.due_ns; + p.sync(); + try std.testing.expectEqual(tag_rows, pane.tag_rows); + try std.testing.expectEqual(rows, pane.rows); + toRest(p); + }; +} + +test "a tag out of rest keeps its rows at rest at least: a root's key cell alone moves no body up" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 30 }); + defer p.deinit(); + _ = try p.setTestFile("one\n"); + const pane = p.panes[p.view().active].?; + p.sync(); + const rows, const tag_rows = .{ pane.rows, pane.tag_rows }; + try std.testing.expect(tag_rows > 1); + p.update(.{ .key = .{ .cp = ' ' } }); + p.sync(); + try std.testing.expect(hostOf(p) != null); + try std.testing.expectEqual(tag_rows, pane.tag_rows); + try std.testing.expectEqual(rows, pane.rows); + // With the keyboard in the tag (whose top row follows its caret) too: + // C-w's key cell, a line, in a tag of more rows. + toRest(p); + pane.focus = .tag; + p.update(.{ .key = .{ .cp = 'w', .ctrl = true } }); + p.sync(); + try std.testing.expect(hostOf(p) != null); + try std.testing.expectEqual(tag_rows, pane.tag_rows); + try std.testing.expectEqual(@as(u16, 0), pane.tag_top); +} diff --git a/core/Trail.zig b/core/Trail.zig new file mode 100644 index 00000000..b5dff554 --- /dev/null +++ b/core/Trail.zig @@ -0,0 +1,724 @@ +//! A pane's walk (pick-ui SPEC §6): the places a reading pane stepped +//! through, written as words in its tag before its path, and whether it +//! is held. A held pane (edited, kept, or not a file) never walks: a jump +//! from it steps its one reader, a reading pane below it whose trail +//! starts with it (`‹@p3`). A reading pane steps in place. +//! +//! The steps are one array, oldest first: `cur` is where the pane is (its +//! place as it was at its last step: the caret is the truth between +//! steps), the steps before it the back steps, the ones after it the +//! forward steps a step back left, drawn dimmed after the path. +const std = @import("std"); +const pardes = @import("root.zig"); +const Kind = @import("Kind.zig"); +const config = @import("config.zig"); +const layout = @import("layout.zig"); +const panes = @import("panes.zig"); +const look = @import("look.zig"); +const Pardes = pardes.Pardes; +const Pane = panes.Pane; +const Spot = look.Spot; + +const Trail = @This(); + +/// The steps a trail keeps; past it the oldest go, the owner kept first. +pub const max_steps = 16; +/// The bytes of a step's path or word. A jump to a longer path is no step: +/// it opens a pane as `Jumps new-pane` does (look.zig open). +pub const max_text = 256; +/// The newest back steps written whole; older ones fold to `·` (§6.3). +pub const shown_steps = 3; + +/// `cur` held to the steps there are (walk.zig `.place`). +pub const replica = .{ .len = .{.{ "steps", "n" }}, .place = .{.{ "cur", "lastCur" }} }; + +steps: [max_steps]Step = undefined, +n: u8 = 0, +cur: u8 = 0, +/// Kept, or edited since it was shown: it no longer walks (§6.5). +held: bool = false, + +pub fn lastCur(t: *const Trail) usize { + return t.n -| 1; +} + +/// One step of a walk, as its word says it (§2 "trail word"). +pub const Step = union(enum) { + /// A place the pane was at: `rank.zig:14`. + place: Place, + /// The held pane this is the reader of, by its serial: `‹@p3`, always + /// the first step. + owner: u32, + /// A list the pane came through (`Find pick 3/6 •2`, §5.6): its word + /// and the pickers' index for it. Made by the pickers (not yet). + list: Word, + /// A search made in the pane (`/dirty/ 3/7`, §7.3). Made by the + /// prompts (not yet). + search: Word, + /// A chain of selection prompts as an Edit line (§7.5). Made by the + /// prompts (not yet). + recipe: Word, +}; +pub const Place = struct { path: Kind.Buf(max_text) = .{}, line: u32 = 0, col: u32 = 0 }; +pub const Word = struct { text: Kind.Buf(max_text) = .{}, index: u32 = 0 }; + +/// A file the walk can show: a text on its path, not an output, a +/// listing, a pager, a query or a kind (§2: what is not a file is held). +pub fn isFile(pane: *const Pane) bool { + const f = pane.file orelse return false; + return f.output == null and f.listing == null and !f.pager and f.mini == null and pane.query == null and pane.addon == null; +} + +/// A pane that walks: a file not held, in a session whose jumps walk. +pub fn reading(p: *const Pardes, pane: *const Pane) bool { + return p.settings.jumps == .walk and isFile(pane) and !pane.trail.held; +} + +/// The reading pane that is held pane `owner`'s reader, if it has one. +pub fn readerOf(p: *const Pardes, owner: *const Pane) ?usize { + for (p.panes, 0..) |slot, id| { + const r = slot orelse continue; + if (r == owner or !isFile(r) or r.trail.held or r.trail.n == 0) continue; + if (r.trail.steps[0] == .owner and r.trail.steps[0].owner == owner.serial) return id; + } + return null; +} + +/// A new reader's trail: its owner, then where it opened. +pub fn reader(owner: u32, path: []const u8, at: Spot) Trail { + var t: Trail = .{}; + push(&t, .{ .owner = owner }); + if (placeOf(path, at.line, at.col)) |s| push(&t, s); + t.cur = t.n - 1; + return t; +} + +/// A place as a step, null when its path does not fit one. +fn placeOf(path: []const u8, line: usize, col: usize) ?Step { + if (path.len > max_text) return null; + var at: Place = .{ .line = std.math.lossyCast(u32, line), .col = std.math.lossyCast(u32, col) }; + at.path.set(path); + return .{ .place = at }; +} + +/// Where `pane` is now, as a step. +fn here(pane: *const Pane) ?Step { + const f = pane.file orelse return null; + return placeOf(f.path, @as(usize, @intCast(@max(0, pane.body.cur_row))) + 1, @as(usize, @intCast(@max(0, pane.body.cur_col))) + 1); +} + +fn samePlace(s: Step, path: []const u8, line: usize) bool { + return s == .place and s.place.line == line and std.mem.eql(u8, s.place.path.slice(), path); +} + +/// `s` as the newest step, the oldest that is not the owner dropped when +/// the trail is full. +fn push(t: *Trail, s: Step) void { + if (t.n == max_steps) { + const first: usize = @intFromBool(t.steps[0] == .owner); + std.mem.copyForwards(Step, t.steps[first .. max_steps - 1], t.steps[first + 1 ..]); + t.n -= 1; + t.cur -|= 1; + } + t.steps[t.n] = s; + t.n += 1; +} + +/// Step reading pane `id` to `path` at `at` (§6.2): a place already on its +/// trail is gone back or forward to, never held twice; anything else is a +/// new step, which drops the forward steps. The pane's slot after it: a +/// step to another file is a new pane in its place (`replace`). +pub fn step(p: *Pardes, id: usize, path: []const u8, at: Spot) !usize { + const pane = p.panes[id].?; + const t = &pane.trail; + // Where it is already: no step. + if (here(pane)) |was| if (samePlace(was, path, at.line)) return show(p, id, path, at); + for (t.steps[0..t.cur], 0..) |s, i| if (samePlace(s, path, at.line)) return go(p, id, @intCast(i)); + if (t.n > t.cur + 1) for (t.steps[t.cur + 1 .. t.n], t.cur + 1..) |s, j| if (samePlace(s, path, at.line)) return go(p, id, @intCast(j)); + const to = placeOf(path, at.line, at.col) orelse return error.NameTooLong; + // Where it was: the current step's place, or a first one. + if (here(pane)) |was| { + if (t.n > t.cur) { + t.n = t.cur + 1; + t.steps[t.cur] = was; + } else push(t, was); + } else t.n = t.cur; + push(t, to); + t.cur = t.n - 1; + return show(p, id, path, at); +} + +/// Go to step `i` of reading pane `id`'s trail, back or forward (§6.4): +/// where it is now becomes the step it leaves, the ones between stay. +pub fn go(p: *Pardes, id: usize, i: u8) !usize { + const pane = p.panes[id].?; + const t = &pane.trail; + if (i >= t.n or t.steps[i] != .place) return id; + const s = t.steps[i]; + if (t.n > t.cur) if (here(pane)) |was| { + t.steps[t.cur] = was; + }; + t.cur = i; + return show(p, id, s.place.path.slice(), .{ .line = s.place.line, .col = s.place.col }); +} + +/// A list the pane's newest step came through (§6.2: a picker's Enter, +/// Pick.zig): its word before the step's place. +pub fn through(t: *Trail, s: Step) void { + if (t.cur >= t.n or t.steps[t.cur] != .place) return; + if (t.n == max_steps) { + const first: usize = @intFromBool(t.steps[0] == .owner); + if (t.cur <= first) return; + std.mem.copyForwards(Step, t.steps[first .. max_steps - 1], t.steps[first + 1 ..]); + t.n -= 1; + t.cur -= 1; + } + std.mem.copyBackwards(Step, t.steps[t.cur + 1 .. t.n + 1], t.steps[t.cur..t.n]); + t.steps[t.cur] = s; + t.n += 1; + t.cur += 1; +} + +/// Reading pane `id`'s current step replaced by `path` at `at`, no step +/// pushed (a list's `n`, §5.6); its slot after it, as `step`'s. +pub fn replaceStep(p: *Pardes, id: usize, path: []const u8, at: Spot) !usize { + const to = placeOf(path, at.line, at.col) orelse return error.NameTooLong; + const t = &p.panes[id].?.trail; + if (t.cur < t.n) t.steps[t.cur] = to; + return show(p, id, path, at); +} + +/// Pane `id` showing `path` at `at`, the keyboard on it: its caret moved +/// in the file it shows, or a new pane on `path` in its place, its walk +/// with it. A line past the new file's end is a miss that changes nothing. +fn show(p: *Pardes, id: usize, path: []const u8, at: Spot) !usize { + const pane = p.panes[id].?; + if (pane.file) |f| if (std.mem.eql(u8, f.path, path)) { + look.clearNavigationSelection(p, pane); + look.focusPaneLine(p, id, at, .center); + return id; + }; + const free = p.freeSlot() orelse return error.NoPaneSlots; + const nt = try panes.File.open(p, free, path, at.line); + // Refused: closed at the step's end, never placed (Pardes.unplaced). + errdefer { + p.unplaced.set(free); + nt.vweight = 0; + } + if (at.line > panes.File.nlines(p.gpa, &nt.file.?)) return error.LineMissing; + nt.trail = pane.trail; + // Before the layout gives its place away: its file is told closed + // while it is still in its slot. + try panes.deinitPane(p, pane); + layout.replacePane(p, id, free); + p.panes[id] = null; + layout.compute(p); + look.focusPaneLine(p, free, at, .keep); + // Its line half the body's rows down, as a look's new pane has it. + const rows = @max(1, p.view().rects[free].h -| pardes.BOX_H); + panes.File.setTop(nt, panes.File.walkRows(p.settings.tab, nt, .{ .line = nt.file.?.scroll }, -@as(i64, rows / 2)).to); + return free; +} + +/// Pane `id` held (§6.5): Keep, or an edit. It no longer walks, so the +/// walk leaves its trail (places, lists, its owner, forward steps); words +/// about its own text (a search, a recipe) stay. The next jump from its +/// old owner makes a new reader. +pub fn keep(pane: *Pane) void { + const t = &pane.trail; + if (t.held) return; + t.held = true; + var w: u8 = 0; + for (t.steps[0..t.cur]) |s| if (s == .search or s == .recipe) { + t.steps[w] = s; + w += 1; + }; + t.n = w; + t.cur = w; +} + +/// An edit of file `f`: the panes showing it are held from now on (§6.5). +/// Only where a pane could read: a session whose jumps walk, a file +/// (isFile), so that an edit anywhere else (an output's, a 9P append's +/// under `Jumps new-pane`) costs nothing past these checks. +pub fn edited(p: *Pardes, f: *const panes.File.State) void { + if (p.settings.jumps != .walk or f.output != null or f.listing != null or f.pager or f.mini != null) return; + for (p.panes) |slot| { + const pane = slot orelse continue; + if (pane.trail.held) continue; + const shown = if (pane.file) |*pf| pf else continue; + if (shown == f or (f.twin != 0 and shown.twin == f.twin)) keep(pane); + } +} + + +/// Back (`delta` < 0) or forward one place in reading pane `id`'s walk, +/// as Ctrl-o and Ctrl-i go first (pick-ui SPEC §6.4): true when it had +/// one that way, false to leave the step to the jump list (Jump.jumpBy). +pub fn walkBy(p: *Pardes, id: usize, delta: i32) bool { + const pane = p.panes[id] orelse return false; + if (!reading(p, pane)) return false; + const t = &pane.trail; + var i: usize = t.cur; + while (if (delta < 0) i > 0 else i + 1 < t.n) { + i = if (delta < 0) i - 1 else i + 1; + if (t.steps[i] != .place) continue; + _ = go(p, id, @intCast(i)) catch |err| p.reportError(.at(id), "walk", err); + return true; + } + return false; +} + +// ---- the words ---- + +pub const Part = enum { back, forward }; + +/// Step `i`'s word: `‹@p3`, `rank.zig:14`, a list's, search's or recipe's +/// own text; `·` when it is folded. +fn wordOf(t: *const Trail, i: usize, buf: *[max_text + 16]u8) []const u8 { + const s = t.steps[i]; + if (s != .owner and i < t.cur and t.cur - i > shown_steps) return "·"; + // The step's own bytes, not a copy's (a copy is gone at the return). + return switch (t.steps[i]) { + .owner => |serial| std.fmt.bufPrint(buf, "‹" ++ config.pane_addr ++ "{d}", .{serial}) catch unreachable, // a u32 fits + .place => |at| std.fmt.bufPrint(buf, "{s}:{d}", .{ std.Io.Dir.path.basename(at.path.slice()), at.line }) catch unreachable, // a basename and a u32 fit + .list, .search, .recipe => |*w| w.text.slice(), + }; +} + +const sep = " › "; + +/// The steps a part writes. +fn range(t: *const Trail, part: Part) [2]usize { + return switch (part) { + .back => .{ 0, t.cur }, + .forward => .{ @min(t.n, t.cur + 1), t.n }, + }; +} + +/// The back steps' words, each with the separator after it (before the +/// path), or the forward steps', each with one before it (after the path). +pub fn write(t: *const Trail, part: Part, w: *std.Io.Writer) std.Io.Writer.Error!void { + var buf: [max_text + 16]u8 = undefined; + const r = range(t, part); + for (r[0]..r[1]) |i| switch (part) { + .back => try w.print("{s}" ++ sep, .{wordOf(t, i, &buf)}), + .forward => try w.print(sep ++ "{s}", .{wordOf(t, i, &buf)}), + }; +} + +/// The bytes `write` writes for `part`. +pub fn bytes(t: *const Trail, part: Part) usize { + var buf: [max_text + 16]u8 = undefined; + var n: usize = 0; + const r = range(t, part); + for (r[0]..r[1]) |i| n += wordOf(t, i, &buf).len + sep.len; + return n; +} + +/// The step whose word in `part` is at byte `off` of what `write` wrote +/// for it, null on a separator or past them. +pub fn stepAt(t: *const Trail, part: Part, off: usize) ?u8 { + var buf: [max_text + 16]u8 = undefined; + var x: usize = 0; + const r = range(t, part); + for (r[0]..r[1]) |i| { + if (part == .forward) x += sep.len; + const n = wordOf(t, i, &buf).len; + if (off >= x and off < x + n) return @intCast(i); + x += n; + if (part == .back) x += sep.len; + } + return null; +} + +/// Look on step `i` of pane `id`'s trail (§6.3): a place is gone back or +/// forward to, the owner focused, a list unrolled again as it was +/// (Pick.reopen); a search or a recipe is the prompts' to take (not yet: +/// said). +pub fn lookStep(p: *Pardes, id: usize, i: u8) void { + const pane = p.panes[id] orelse return; + switch (pane.trail.steps[i]) { + .place => _ = go(p, id, i) catch |err| p.reportError(.at(id), "walk", err), + .owner => |serial| if (p.paneBySerial(serial)) |owner| { + p.view().active = owner; + } else p.reportFailure(id, "walk: its owner is closed"), + .list => |w| pardes.Pick.reopen(p, id, w.index), + .search, .recipe => p.setMessage(.at(id), "walk: a search or a recipe is not walked yet"), + } +} + +/// Exec on step `i` (§6.3): a place and the owner as Look; a list runs its +/// source again, a search searches again, a recipe replays (not yet). +pub fn execStep(p: *Pardes, id: usize, i: u8) void { + const pane = p.panes[id] orelse return; + switch (pane.trail.steps[i]) { + .place, .owner => lookStep(p, id, i), + .list => |w| pardes.Pick.rerun(p, id, w.index), + .search, .recipe => p.setMessage(.at(id), "walk: a search or a recipe is not run again yet"), + } +} + +fn typeKeys(p: *Pardes, keys: []const u8) void { + for (keys) |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); +} + +fn tagOf(p: *Pardes, pane: *Pane) ![]const u8 { + return pardes.tagline.tagText(p, p.scratch.allocator(), pane); +} + +/// The ground of the cell under the first cell of pane `id`'s tag text. +fn tagGroundOf(p: *Pardes, arena: *std.heap.ArenaAllocator, id: usize) !pardes.Color { + p.sync(); + _ = arena.reset(.retain_capacity); + const s = try p.render(arena.allocator()); + const r = p.view().rects[id]; + return s.at(r.x + pardes.TAG_TEXT_INSET, p.tagTop(p.panes[id].?, r)).style.bg; +} + +test "a file's pane is reading, its tag in the reading tint with Keep after its path; typed into, it is held, and Jumps new-pane reads none" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + p.settings.jumps = .walk; + const pane = try p.setTestFile("alpha\nbeta\n"); + try std.testing.expect(reading(p, pane)); + try std.testing.expect(std.mem.startsWith(u8, try tagOf(p, pane), "/test.txt Keep ")); + try std.testing.expectEqual(pardes.Color{ .rgb = p.chromeTheme().tag_reading_bg }, try tagGroundOf(p, &arena, 0)); + // Under Jumps new-pane nothing reads: the tag as it always was. + p.settings.jumps = .@"new-pane"; + try std.testing.expect(!reading(p, pane)); + try std.testing.expectEqualStrings("/test.txt Save Term Collapse Follow Del", try tagOf(p, pane)); + try std.testing.expectEqual(pardes.Color{ .rgb = p.chromeTheme().tag_active_bg }, try tagGroundOf(p, &arena, 0)); + p.settings.jumps = .walk; + // Typed into: held from now on, though Undo takes the text back. + typeKeys(p, "ix"); + p.update(.{ .key = .{ .cp = pardes.Key.escape } }); + typeKeys(p, "u"); + try std.testing.expectEqualStrings("alpha\nbeta\n", pane.file.?.content); + try std.testing.expect(!reading(p, pane)); + try std.testing.expect(std.mem.indexOf(u8, try tagOf(p, pane), "Keep") == null); + try std.testing.expectEqual(pardes.Color{ .rgb = p.chromeTheme().tag_active_bg }, try tagGroundOf(p, &arena, 0)); +} + +test "Keep holds a reading pane; a scratch and a listing are never reading" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + p.settings.jumps = .walk; + const pane = try p.setTestFile("alpha\n"); + pardes.exec.runBuiltin(p, .Keep, 0, "Keep", null); + try std.testing.expect(!reading(p, pane)); + try std.testing.expect(pane.trail.held); + pardes.exec.runBuiltin(p, .New, 0, "New", null); + const scratch = p.panes[p.view().active].?; + try std.testing.expect(scratch != pane and scratch.file != null and !reading(p, scratch)); + var dir = std.testing.tmpDir(.{}); + defer dir.cleanup(); + var buf: [4096]u8 = undefined; + const len = try dir.dir.realPath(std.testing.io, &buf); + pardes.look.lookAt(p, 0, buf[0..len]); + const listing = p.panes[p.view().active].?; + try std.testing.expect(listing.file.?.listing != null and !reading(p, listing)); +} + +/// A session over three files of 100 lines in a directory of its own, +/// search.zig, rank.zig and place.zig; search.zig open and edited (held) +/// in pane `held`, under the session's first pane. +const Fixture = struct { + p: *Pardes, + tmp: std.testing.TmpDir, + dir_buf: [4096]u8 = undefined, + dir: []const u8 = "", + held: usize = 0, + + fn init(f: *Fixture, rows: u16) !void { + f.tmp = std.testing.tmpDir(.{}); + errdefer f.tmp.cleanup(); + var text: [100 * 9]u8 = undefined; + var w: std.Io.Writer = .fixed(&text); + for (1..101) |n| try w.print("line {d}\n", .{n}); + for ([_][]const u8{ "search.zig", "rank.zig", "place.zig" }) |name| + try f.tmp.dir.writeFile(std.testing.io, .{ .sub_path = name, .data = w.buffered() }); + f.dir = f.dir_buf[0..try f.tmp.dir.realPath(std.testing.io, &f.dir_buf)]; + f.p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = rows }); + errdefer f.p.deinit(); + _ = try f.p.setTestFile("scratch\n"); + f.p.settings.jumps = .@"new-pane"; + f.look(0, "search.zig", 88); + f.p.settings.jumps = .walk; + f.held = f.p.view().active; + typeKeys(f.p, "ix"); + f.p.update(.{ .key = .{ .cp = pardes.Key.escape } }); + f.p.sync(); + } + + fn deinit(f: *Fixture) void { + f.p.deinit(); + f.tmp.cleanup(); + } + + /// A Look from pane `id` at `name:line` in the fixture's directory. + fn look(f: *Fixture, id: usize, name: []const u8, line: usize) void { + var buf: [4096 + 64]u8 = undefined; + pardes.look.lookAt(f.p, id, std.fmt.bufPrint(&buf, "{s}/{s}:{d}", .{ f.dir, name, line }) catch unreachable); + f.p.sync(); + } + + fn active(f: *Fixture) *Pane { + return f.p.panes[f.p.view().active].?; + } + + /// The active pane's file's name and line, as `rank.zig:12`. + fn at(f: *Fixture, buf: []u8) []const u8 { + const pane = f.active(); + return std.fmt.bufPrint(buf, "{s}:{d}", .{ std.Io.Dir.path.basename(pane.file.?.path), pane.body.cur_row + 1 }) catch unreachable; + } +}; + +test "a jump from a held pane steps its reader, made under it with half its rows; the reader walks in place, and a place on its trail is gone back to, never held twice" { + var f: Fixture = .{ .p = undefined, .tmp = undefined }; + try f.init(60); + defer f.deinit(); + const held = f.p.panes[f.held].?; + try std.testing.expect(!reading(f.p, held)); + const before = f.p.view().rects[f.held]; + var buf: [64]u8 = undefined; + // g d on rank: its reader, under it, half its rows. + f.look(f.held, "rank.zig", 12); + const r1 = f.p.view().active; + try std.testing.expect(r1 != f.held); + try std.testing.expectEqualStrings("rank.zig:12", f.at(&buf)); + try std.testing.expectEqual(held.serial, f.active().trail.steps[0].owner); + const col = layout.findPane(f.p, f.held).?; + try std.testing.expectEqual(col.col, layout.findPane(f.p, r1).?.col); + try std.testing.expectEqual(col.idx + 1, layout.findPane(f.p, r1).?.idx); + try std.testing.expect(f.p.view().rects[f.held].h <= before.h / 2 + 1); + // Look at place.zig:8 in the reader, from line 14: the reader walks. + typeKeys(f.p, "2j"); + f.look(r1, "place.zig", 8); + const r2 = f.p.view().active; + try std.testing.expect(f.p.panes[r1] == null or r2 == r1); + try std.testing.expectEqualStrings("place.zig:8", f.at(&buf)); + try std.testing.expectEqual(layout.findPane(f.p, f.held).?.idx + 1, layout.findPane(f.p, r2).?.idx); + // g d on Span, from line 9: one more step in the same file. + typeKeys(f.p, "j"); + f.look(r2, "place.zig", 40); + try std.testing.expectEqual(r2, f.p.view().active); + try std.testing.expectEqualStrings("place.zig:40", f.at(&buf)); + const t = &f.active().trail; + try std.testing.expectEqual(@as(u8, 4), t.n); + try std.testing.expectEqual(@as(u8, 3), t.cur); + try std.testing.expectEqual(@as(u32, 14), t.steps[1].place.line); + try std.testing.expectEqual(@as(u32, 9), t.steps[2].place.line); + // The next jump from the held pane lands in the same reader. + f.look(f.held, "rank.zig", 30); + const r3 = f.p.view().active; + try std.testing.expectEqualStrings("rank.zig:30", f.at(&buf)); + try std.testing.expectEqual(held.serial, f.active().trail.steps[0].owner); + var readers: usize = 0; + for (f.p.panes) |slot| if (slot) |pane| { + readers += @intFromBool(pane.trail.n > 0 and pane.trail.steps[0] == .owner); + }; + try std.testing.expectEqual(@as(usize, 1), readers); + // A Look at a place on its trail goes back to it: nothing pushed. + f.look(r3, "rank.zig", 14); + try std.testing.expectEqualStrings("rank.zig:14", f.at(&buf)); + try std.testing.expectEqual(@as(u8, 1), f.active().trail.cur); + try std.testing.expectEqual(@as(u8, 5), f.active().trail.n); +} + +test "a Look from inside the reader at a file its held pane shows focuses the held pane and replaces nothing" { + var f: Fixture = .{ .p = undefined, .tmp = undefined }; + try f.init(60); + defer f.deinit(); + f.look(f.held, "rank.zig", 12); + const reader_id = f.p.view().active; + const reader_pane = f.active(); + f.look(reader_id, "search.zig", 89); + try std.testing.expectEqual(f.held, f.p.view().active); + try std.testing.expectEqual(@as(i32, 88), f.active().body.cur_row); + try std.testing.expectEqual(reader_pane, f.p.panes[reader_id].?); + try std.testing.expectEqualStrings("rank.zig", std.Io.Dir.path.basename(reader_pane.file.?.path)); +} + +test "the reader of a held pane too short to halve goes to the bottom of the next column, of the previous one from the last" { + var f: Fixture = .{ .p = undefined, .tmp = undefined }; + try f.init(24); + defer f.deinit(); + const col = layout.findPane(f.p, f.held).?.col; + try std.testing.expect(f.p.view().rects[f.held].h / 2 < f.p.panes[f.held].?.tag_rows + layout.reader_keeps); + try std.testing.expect(layout.insertColumn(f.p, col, false) != null); + f.look(f.held, "rank.zig", 12); + const reader_id = f.p.view().active; + try std.testing.expectEqual(col + 1, layout.findPane(f.p, reader_id).?.col); +} + +/// Where `word` starts in pane `id`'s tag, on the screen. +fn tagCell(p: *Pardes, id: usize, word: []const u8) ![2]u16 { + const pane = p.panes[id].?; + const tag = try tagOf(p, pane); + const i = std.mem.indexOf(u8, tag, word) orelse return error.NotInTag; + const r = p.view().rects[id]; + return .{ r.x + pardes.TAG_TEXT_INSET + @as(u16, @intCast(panes.File.displayWidth(p.settings.tab, tag[0..i]))), p.tagTop(pane, r) }; +} + +/// A click with `button` on `word` in pane `id`'s tag: a press and a +/// release on its first cell. +fn clickTag(p: *Pardes, id: usize, word: []const u8, button: pardes.Mouse.Button) !void { + const at = try tagCell(p, id, word); + for ([_]pardes.Mouse.Kind{ .press, .release }) |kind| p.update(.{ .mouse = .{ .button = button, .kind = kind, .col = at[0], .row = at[1] } }); + p.sync(); +} + +test "the session of pick-ui §6.7: four jumps across three files, back by a click on a trail word, the later steps kept dimmed after the path, forward again, Keep, and a new reader on the next jump" { + var f: Fixture = .{ .p = undefined, .tmp = undefined }; + try f.init(60); + defer f.deinit(); + const p = f.p; + const owner = p.panes[f.held].?.serial; + var buf: [4096 + 128]u8 = undefined; + var at: [64]u8 = undefined; + // 1 · g d on rank from the held pane: its reader, made below it. + f.look(f.held, "rank.zig", 12); + // 2 · Look at Place.of from line 14 of rank.zig: the reader walks. + typeKeys(p, "2j"); + f.look(p.view().active, "place.zig", 8); + // 3 · g d on Span from line 9: one more step in the same file. + typeKeys(p, "j"); + f.look(p.view().active, "place.zig", 40); + var r = p.view().active; + try std.testing.expect(std.mem.startsWith(u8, try tagOf(p, p.panes[r].?), try std.fmt.bufPrint(&buf, "‹@p{d} › rank.zig:14 › place.zig:9 › {s}/place.zig Keep ", .{ owner, f.dir }))); + // 4 · a click on rank.zig:14: back, the later steps after the path, + // dimmed. + try clickTag(p, r, "rank.zig:14", .left); + r = p.view().active; + try std.testing.expectEqualStrings("rank.zig:14", f.at(&at)); + try std.testing.expect(std.mem.startsWith(u8, try tagOf(p, p.panes[r].?), try std.fmt.bufPrint(&buf, "‹@p{d} › {s}/rank.zig › place.zig:9 › place.zig:40 Keep ", .{ owner, f.dir }))); + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const s = try p.render(arena.allocator()); + const dim = try tagCell(p, r, "place.zig:40"); + try std.testing.expectEqual(pardes.Color{ .rgb = p.chromeTheme().lineno }, s.at(dim[0], dim[1]).style.fg); + // A click on a forward step goes forward to it. + try clickTag(p, r, "place.zig:9", .left); + r = p.view().active; + try std.testing.expectEqualStrings("place.zig:9", f.at(&at)); + try std.testing.expect(std.mem.startsWith(u8, try tagOf(p, p.panes[r].?), try std.fmt.bufPrint(&buf, "‹@p{d} › rank.zig:14 › {s}/place.zig › place.zig:40 Keep ", .{ owner, f.dir }))); + // Exec (B2) on the owner's word: the owner has the keyboard. + try clickTag(p, r, "‹@p", .middle); + try std.testing.expectEqual(f.held, p.view().active); + // A new step from the reader drops the forward steps. + f.look(r, "rank.zig", 50); + r = p.view().active; + try std.testing.expectEqual(p.panes[r].?.trail.cur + 1, p.panes[r].?.trail.n); + // 5 · Keep: the walk leaves its tag; the next jump from the owner + // makes a new reader. + pardes.exec.runBuiltin(p, .Keep, r, "Keep", null); + p.sync(); + try std.testing.expect(std.mem.startsWith(u8, try tagOf(p, p.panes[r].?), try std.fmt.bufPrint(&buf, "{s}/rank.zig Save", .{f.dir}))); + f.look(f.held, "place.zig", 20); + const fresh = p.view().active; + try std.testing.expect(fresh != r and fresh != f.held and p.panes[r] != null); + try std.testing.expectEqual(owner, p.panes[fresh].?.trail.steps[0].owner); +} + +test "a trail keeps its newest three back steps whole, older ones fold to ·, and a click on a · goes back to its step" { + var f: Fixture = .{ .p = undefined, .tmp = undefined }; + try f.init(60); + defer f.deinit(); + const p = f.p; + const owner = p.panes[f.held].?.serial; + for ([_]usize{ 10, 20, 30, 40, 50 }) |line| f.look(f.held, "rank.zig", line); + const r = p.view().active; + var buf: [4096 + 128]u8 = undefined; + var at: [64]u8 = undefined; + try std.testing.expect(std.mem.startsWith(u8, try tagOf(p, p.panes[r].?), try std.fmt.bufPrint(&buf, "‹@p{d} › · › rank.zig:20 › rank.zig:30 › rank.zig:40 › {s}/rank.zig Keep ", .{ owner, f.dir }))); + try clickTag(p, r, "·", .right); + try std.testing.expectEqualStrings("rank.zig:10", f.at(&at)); +} + +test "Ctrl-o goes back one place in a reader's walk and Ctrl-i forward again; past its first place, or from a held pane, the jump list's" { + var f: Fixture = .{ .p = undefined, .tmp = undefined }; + try f.init(60); + defer f.deinit(); + const p = f.p; + var at: [64]u8 = undefined; + f.look(f.held, "rank.zig", 12); + f.look(p.view().active, "place.zig", 8); + f.look(p.view().active, "place.zig", 40); + const back: pardes.Key = .{ .cp = 'o', .ctrl = true }; + const ahead: pardes.Key = .{ .cp = 'i', .ctrl = true }; + p.update(.{ .key = back }); + p.sync(); + try std.testing.expectEqualStrings("place.zig:8", f.at(&at)); + p.update(.{ .key = back }); + p.sync(); + try std.testing.expectEqualStrings("rank.zig:12", f.at(&at)); + p.update(.{ .key = ahead }); + p.sync(); + try std.testing.expectEqualStrings("place.zig:8", f.at(&at)); + p.update(.{ .key = back }); + p.sync(); + try std.testing.expectEqualStrings("rank.zig:12", f.at(&at)); + // The owner's word is no place: past the first, the jump list's. + try std.testing.expect(!walkBy(p, p.view().active, -1)); + try std.testing.expect(!walkBy(p, f.held, -1)); +} + +test "closing a held pane closes its reader; a kept reader stays; typed into, a reader is held and its walk leaves its tag" { + var f: Fixture = .{ .p = undefined, .tmp = undefined }; + try f.init(60); + defer f.deinit(); + const p = f.p; + const owner = p.panes[f.held].?.serial; + var buf: [4096 + 128]u8 = undefined; + f.look(f.held, "rank.zig", 12); + f.look(p.view().active, "place.zig", 8); + const r = p.view().active; + // Typed into: held, its walk gone from its tag, kept when its owner goes. + typeKeys(p, "ix"); + p.update(.{ .key = .{ .cp = pardes.Key.escape } }); + p.sync(); + try std.testing.expect(std.mem.startsWith(u8, try tagOf(p, p.panes[r].?), try std.fmt.bufPrint(&buf, "{s}/place.zig Save", .{f.dir}))); + try std.testing.expectEqual(@as(u8, 0), p.panes[r].?.trail.n); + // The next jump from its old owner makes a new reader. + f.look(f.held, "rank.zig", 30); + const fresh = p.view().active; + try std.testing.expect(fresh != r); + try std.testing.expectEqual(owner, p.panes[fresh].?.trail.steps[0].owner); + // Del of the owner: its reader goes with it; the edited one stays. + const fresh_serial = p.panes[fresh].?.serial; + try p.removePane(f.held, null); + p.sync(); + try std.testing.expect(p.paneBySerial(fresh_serial) == null); + try std.testing.expect(p.panes[r] != null); +} + +test "Jumps new-pane jumps as before the walk: a new pane for a file no pane shows, under the asking one, the one showing it focused, nothing stepped" { + var f: Fixture = .{ .p = undefined, .tmp = undefined }; + try f.init(60); + defer f.deinit(); + const p = f.p; + p.settings.jumps = .@"new-pane"; + var at: [64]u8 = undefined; + var open: usize = 0; + for (p.panes) |slot| open += @intFromBool(slot != null); + // From the held pane and from the reading one: a new pane each time. + f.look(f.held, "rank.zig", 12); + const rank = p.view().active; + try std.testing.expectEqualStrings("rank.zig:12", f.at(&at)); + f.look(rank, "place.zig", 8); + try std.testing.expect(p.view().active != rank and p.panes[rank] != null); + try std.testing.expectEqualStrings("place.zig:8", f.at(&at)); + // A file a pane shows: that pane, focused; nothing new, no walk. + f.look(p.view().active, "rank.zig", 30); + try std.testing.expectEqual(rank, p.view().active); + try std.testing.expectEqualStrings("rank.zig:30", f.at(&at)); + var now: usize = 0; + for (p.panes) |slot| if (slot) |pane| { + now += 1; + try std.testing.expectEqual(@as(u8, 0), pane.trail.n); + }; + try std.testing.expectEqual(open + 2, now); +} diff --git a/core/bindings.zig b/core/bindings.zig new file mode 100644 index 00000000..b2d84a7c --- /dev/null +++ b/core/bindings.zig @@ -0,0 +1,452 @@ +//! One binding table (walk UI, pick-ui SPEC.md §4): every key sequence a +//! root starts, as a tree per root, made at compile time from the tables +//! that bind them: SPC's from `config.leader_path` and `config.leader_args`, +//! the helix prefixes' (`g m z Z [ ]`) from their roles in modal.zig and +//! their chords in config.zig, window mode's (`C-w`) from +//! `config.window_keys`. An addon's leader words join SPC's levels where +//! they are read (`level`). Which-key, Help and describe-key all read it. +const std = @import("std"); +const pardes = @import("root.zig"); +const config = @import("config.zig"); +const builtins = @import("builtins.zig"); +const modal = @import("modal.zig"); +const Builtin = pardes.Builtin; +const Pardes = pardes.Pardes; +const Pane = pardes.Pane; +const Key = pardes.Key; +const Role = modal.Normal.Role; + +/// The keys a sequence starts with. `register` (`"`) is drawn the same way +/// but its rows are the registers' contents, not a tree. +pub const Root = enum(u8) { leader, window, goto, match, view, view_sticky, prev, next, register }; + +/// What a leaf runs: a builtin, a builtin with its argument +/// (`config.leader_args`, by index), or a normal-mode role typed as its keys. +pub const Leaf = union(enum) { builtin: Builtin, arg: u8, role: Role }; + +/// A group (`children`) or a leaf. `label` is a group's name, a builtin +/// leaf's word (`Def`), a motion's description (`line start`). +pub const Node = struct { + key: u8, + label: []const u8, + leaf: ?Leaf = null, + children: []const Node = &.{}, + /// A group's slot in a view's memory of the leaf it ran last + /// (TagState.used). + group: u8 = 0, + /// It asks the language server: dimmed in a pane none speaks for. + lsp: bool = false, +}; + +pub const Info = struct { + key: Key, + /// Its key cell in the head (`␣` for SPC). + cell: []const u8, + label: []const u8, + /// How long after it the level shows (SPEC §3.3). + delay_ns: u64, + /// Its key cell is written at once (SPC, `"`, `C-w`); the others change + /// nothing until the delay is up, so `gg` never touches the tag. + at_once: bool, + node: *const Node, +}; + +const ms = std.time.ns_per_ms; + +pub const info = std.EnumArray(Root, Info).init(.{ + .leader = .{ .key = .{ .cp = config.leader[0].cp }, .cell = "␣", .label = "SPC", .delay_ns = 250 * ms, .at_once = true, .node = &leader_tree }, + .window = .{ .key = .{ .cp = config.window_prefix[0].cp, .ctrl = true }, .cell = "C-w", .label = "window", .delay_ns = 250 * ms, .at_once = true, .node = &window_tree }, + .goto = .{ .key = .{ .cp = config.goto_prefix }, .cell = "g", .label = "goto", .delay_ns = 500 * ms, .at_once = false, .node = &goto_tree }, + .match = .{ .key = .{ .cp = config.match_prefix }, .cell = "m", .label = "match", .delay_ns = 500 * ms, .at_once = false, .node = &match_tree }, + .view = .{ .key = .{ .cp = config.view_prefix }, .cell = "z", .label = "view", .delay_ns = 500 * ms, .at_once = false, .node = &view_tree }, + .view_sticky = .{ .key = .{ .cp = config.view_prefix_sticky }, .cell = "Z", .label = "view", .delay_ns = 500 * ms, .at_once = false, .node = &view_sticky_tree }, + .prev = .{ .key = .{ .cp = config.prev_prefix }, .cell = "[", .label = "previous", .delay_ns = 500 * ms, .at_once = false, .node = &prev_tree }, + .next = .{ .key = .{ .cp = config.next_prefix }, .cell = "]", .label = "next", .delay_ns = 500 * ms, .at_once = false, .node = &next_tree }, + .register = .{ .key = .{ .cp = config.register_prefix }, .cell = "\"", .label = "registers", .delay_ns = 300 * ms, .at_once = true, .node = ®ister_tree }, +}); + +/// SPC's groups by their key, as the spec names them (Appendix A). +const leader_groups = [_]struct { key: u8, label: []const u8 }{ + .{ .key = 'b', .label = "buffer" }, .{ .key = 'c', .label = "column" }, + .{ .key = 'f', .label = "file" }, .{ .key = 'h', .label = "help" }, + .{ .key = 'j', .label = "jump" }, .{ .key = 'l', .label = "lsp" }, + .{ .key = 'n', .label = "new" }, .{ .key = 's', .label = "session" }, + .{ .key = 't', .label = "view" }, +}; + +/// Every group of every tree, a slot each in a view's memory: SPC's by +/// path, then each root's own level. +pub const groups = groups: { + @setEvalBranchQuota(100_000); + var paths: []const []const u8 = &.{""}; + for (leaderPaths()) |path| for (1..path.len) |n| { + const head = path[0..n]; + for (paths) |had| { + if (std.mem.eql(u8, had, head)) break; + } else paths = paths ++ .{head}; + }; + break :groups paths; +}; +/// SPC's groups, then one for each other root. +pub const ngroups = groups.len + std.enums.values(Root).len - 1; + +fn rootGroup(comptime r: Root) u8 { + return @intCast(groups.len + @intFromEnum(r) - 1); +} + +/// Every path SPC has: a builtin's (each one, whether this view takes it +/// or not: `here` is asked where a level is read) and `leader_args`'. +fn leaderPaths() []const []const u8 { + comptime { + var paths: []const []const u8 = &.{}; + for (std.enums.values(Builtin)) |b| if (config.leader_path.get(b)) |path| { + paths = paths ++ .{path}; + }; + for (config.leader_args) |la| paths = paths ++ .{la.path}; + return paths; + } +} + +/// Which-key order (SPEC §4.2): groups first, then keys: punctuation, then +/// a-z with a lowercase key before its capital. +fn rank(key: u8, group: bool) u16 { + const letter: u16 = if (std.ascii.isAlphabetic(key)) 256 + @as(u16, std.ascii.toLower(key) - 'a') * 2 + @intFromBool(std.ascii.isUpper(key)) else key; + return letter + if (group) 0 else @as(u16, 1024); +} + +fn sorted(comptime nodes: []const Node) []const Node { + comptime { + var out: [nodes.len]Node = nodes[0..nodes.len].*; + for (1..out.len) |i| { + var j = i; + while (j > 0 and rank(out[j].key, out[j].children.len > 0) < rank(out[j - 1].key, out[j - 1].children.len > 0)) : (j -= 1) { + const t = out[j]; + out[j] = out[j - 1]; + out[j - 1] = t; + } + } + const final = out; + return &final; + } +} + +/// SPC's level under `prefix`. +fn leaderLevel(comptime prefix: []const u8) []const Node { + comptime { + @setEvalBranchQuota(200_000); + var keys: []const u8 = ""; + for (leaderPaths()) |path| { + if (path.len <= prefix.len or !std.mem.startsWith(u8, path, prefix)) continue; + if (std.mem.indexOfScalar(u8, keys, path[prefix.len]) == null) keys = keys ++ .{path[prefix.len]}; + } + var nodes: [keys.len]Node = undefined; + for (keys, 0..) |k, i| { + const here = prefix ++ .{k}; + const lsp = here[0] == 'l'; + nodes[i] = for (std.enums.values(Builtin)) |b| { + const path = config.leader_path.get(b) orelse continue; + if (std.mem.eql(u8, path, here)) break .{ .key = k, .label = @tagName(b), .leaf = .{ .builtin = b }, .lsp = lsp }; + } else for (config.leader_args, 0..) |la, a| { + if (std.mem.eql(u8, la.path, here)) break .{ .key = k, .label = la.arg, .leaf = .{ .arg = a }, .lsp = lsp }; + } else .{ .key = k, .label = groupLabel(here), .children = leaderLevel(here), .group = groupIndex(here) }; + } + return sorted(&nodes); + } +} + +fn groupLabel(comptime path: []const u8) []const u8 { + if (path.len == 1) for (leader_groups) |g| if (g.key == path[0]) return g.label; + return path; +} + +fn groupIndex(comptime path: []const u8) u8 { + for (groups, 0..) |g, i| if (std.mem.eql(u8, g, path)) return i; + unreachable; +} + +/// A role's key under its root: the first chord config.zig binds it to +/// that a plain key types; none when only a held one does (`z C-d`). +fn roleKey(comptime role: Role) ?u8 { + const binding = @field(config, @tagName(role)); + if (@TypeOf(binding) == comptime_int) return if (binding >= 0x20 and binding < 0x7f) binding else null; + for (binding) |c| if (!c.ctrl and !c.alt and c.cp >= 0x20 and c.cp < 0x7f) return @intCast(c.cp); + return null; +} + +/// The builtin a role runs (normal.zig executeNormalAction), shown by its +/// word; null for a motion, shown by its description. +fn roleWord(comptime role: Role) ?Builtin { + return switch (role) { + .goto_definition => .Def, + .goto_references => .Refs, + .goto_callstack => .Callstack, + else => null, + }; +} + +/// A motion's description: its role's name without its context's word, +/// spaced (`goto_line_start` is `line start`). +fn roleLabel(comptime role: Role) []const u8 { + if (role == .match_prefix) return "matching bracket"; + if (roleWord(role)) |b| return @tagName(b); + var name: []const u8 = @tagName(role); + for ([_][]const u8{ "goto_", "view_", "match_" }) |head| if (std.mem.startsWith(u8, name, head)) { + name = name[head.len..]; + }; + var out: [name.len]u8 = undefined; + for (name, 0..) |c, i| out[i] = if (c == '_') ' ' else c; + const final = out; + return &final; +} + +fn roleLsp(comptime role: Role) bool { + return switch (role) { + .goto_definition, .goto_declaration, .goto_type_definition, .goto_implementation, .goto_references, .goto_callstack, .goto_diagnostic, .goto_diagnostic_end => true, + else => false, + }; +} + +/// A root's level of roles, `from` to `to` in Role's order (the order its +/// context tries them, modal.zig): the first role a key has is the one it +/// runs, so a later role on the same key is not shown. +fn roleLevel(comptime from: Role, comptime to: Role, comptime extra: []const Role) []const Node { + comptime { + @setEvalBranchQuota(100_000); + var nodes: []const Node = &.{}; + var roles: []const Role = extra; + for (@intFromEnum(from)..@intFromEnum(to) + 1) |i| roles = roles ++ .{@as(Role, @enumFromInt(i))}; + for (roles) |role| { + const key = roleKey(role) orelse continue; + for (nodes) |n| { + if (n.key == key) break; + } else nodes = nodes ++ .{Node{ .key = key, .label = roleLabel(role), .leaf = .{ .role = role }, .lsp = roleLsp(role) }}; + } + return sorted(nodes); + } +} + +const leader_tree: Node = .{ .key = ' ', .label = "SPC", .children = leaderLevel(""), .group = 0 }; +const goto_tree: Node = .{ .key = config.goto_prefix, .label = "goto", .children = roleLevel(.goto_file_start, .goto_callstack, &.{}), .group = rootGroup(.goto) }; +const match_tree: Node = .{ .key = config.match_prefix, .label = "match", .children = roleLevel(.match_inside, .surround_delete, &.{.match_prefix}), .group = rootGroup(.match) }; +const view_tree: Node = .{ .key = config.view_prefix, .label = "view", .children = roleLevel(.view_top, .view_scroll_up, &.{}), .group = rootGroup(.view) }; +const view_sticky_tree: Node = .{ .key = config.view_prefix_sticky, .label = "view", .children = roleLevel(.view_top, .view_scroll_up, &.{}), .group = rootGroup(.view_sticky) }; +const prev_tree: Node = .{ .key = config.prev_prefix, .label = "previous", .children = roleLevel(.goto_paragraph, .goto_xml_element, &.{}), .group = rootGroup(.prev) }; +const next_tree: Node = .{ .key = config.next_prefix, .label = "next", .children = roleLevel(.goto_paragraph, .goto_xml_element, &.{}), .group = rootGroup(.next) }; +const register_tree: Node = .{ .key = config.register_prefix, .label = "registers", .group = rootGroup(.register) }; +/// pardes's window mode (layout.windowKey): its moves, Collapse and Del; +/// a letter picks the pane its box shows. +const window_tree: Node = .{ .key = 'w', .label = "window", .group = rootGroup(.window), .children = window: { + var nodes: []const Node = &.{}; + for (config.window_keys) |wk| nodes = nodes ++ .{Node{ .key = @intCast(wk.letter.cp), .label = @tagName(wk.cmd), .leaf = .{ .builtin = wk.cmd } }}; + nodes = nodes ++ .{ + Node{ .key = config.window_collapse[0].cp, .label = "Collapse", .leaf = .{ .builtin = .Collapse } }, + Node{ .key = config.window_delete[0].cp, .label = "Del", .leaf = .{ .builtin = .Del } }, + }; + break :window sorted(nodes); +} }; + +/// The node `path` reaches under `root`, or null. +pub fn nodeAt(root: Root, path: []const u8) ?*const Node { + var n = info.get(root).node; + for (path) |k| n = for (n.children) |*c| { + if (c.key == k) break c; + } else return null; + return n; +} + +/// A level's child as which-key shows it: the tree's, or an addon's word +/// (SPC's alone), or an addon's path going on (a group of its words). +pub const Child = struct { + key: u8, + label: []const u8, + node: ?*const Node = null, + word: ?*const pardes.Kind.Word = null, + group: bool = false, + lsp: bool = false, +}; +/// The most children a level shows: SPC's top has 17, and an addon's +/// words (Kind.Registry's 64) may each start a key of their own. +pub const max_children = 96; + +/// The children of `path` under `root` this view takes, in which-key order: +/// the tree's (a builtin this view's frontend has not dropped), then the +/// addons' leader words joined in (SPC alone). Bounded by the level and the +/// registry's 64 words. +pub fn level(p: *const Pardes, root: Root, path: []const u8, out: *[max_children]Child) []Child { + var n: usize = 0; + if (nodeAt(root, path)) |node| for (node.children) |*c| { + if (c.leaf) |leaf| if (leaf == .builtin and !builtins.registry.here(p, leaf.builtin)) continue; + out[n] = .{ .key = c.key, .label = c.label, .node = c, .group = c.children.len > 0, .lsp = c.lsp }; + n += 1; + }; + if (root == .leader) for (p.kinds.words[0..p.kinds.nwords]) |*w| { + const keys = w.leader.slice(); + if (keys.len <= path.len or !std.mem.startsWith(u8, keys, path)) continue; + const k = keys[path.len]; + const last = keys.len == path.len + 1; + for (out[0..n]) |c| { + if (c.key == k) break; + } else if (n < out.len) { + out[n] = .{ .key = k, .label = if (last) w.name.slice() else "addon", .word = if (last) w else null, .group = !last }; + n += 1; + } + }; + const shown = out[0..n]; + for (1..@max(1, shown.len)) |i| { + var j = i; + while (j > 0 and rank(shown[j].key, shown[j].group) < rank(shown[j - 1].key, shown[j - 1].group)) : (j -= 1) + std.mem.swap(Child, &shown[j], &shown[j - 1]); + } + return shown; +} + +/// A key as a cell shows it: `SPC` for the space. +pub fn keyName(key: u8) []const u8 { + return if (key == ' ') "SPC" else @as(*const [1]u8, &printable[key - 0x20]); +} +const printable = blk: { + var all: [0x5f]u8 = undefined; + for (&all, 0x20..) |*c, i| c.* = i; + break :blk all; +}; + +/// A child's one-line documentation: a builtin's summary, an addon word's +/// own, a motion's description under its root's name. +pub fn docOf(root: Root, c: Child, buf: []u8) []const u8 { + if (c.word) |w| return w.doc.slice(); + const node = c.node orelse return ""; + if (node.children.len > 0) return "a group"; + return switch (node.leaf.?) { + .builtin => |b| builtins.registry.doc(b).summary, + .arg => |a| std.fmt.bufPrint(buf, "{s} {s}: {s}", .{ @tagName(config.leader_args[a].cmd), config.leader_args[a].arg, builtins.registry.doc(config.leader_args[a].cmd).summary }) catch "", + .role => |role| if (roleWordAt(role)) |b| builtins.registry.doc(b).summary else std.fmt.bufPrint(buf, "{s} {s}", .{ info.get(root).label, c.label }) catch c.label, + }; +} + +/// `roleWord` for a role known only when the program runs. +fn roleWordAt(role: Role) ?Builtin { + return switch (role) { + inline else => |r| comptime roleWord(r), + }; +} + +/// Whether child `c` is dimmed in pane `pane`: it asks a language server +/// and none speaks for the pane's text. +pub fn dimmed(pane: *const Pane, c: Child) bool { + if (!c.lsp) return false; + const f = pane.file orelse return true; + return f.output != null or f.mini != null or !pardes.lsp.speaks(f.path); +} + +/// The keys that type `path` under `root`, the root's first: a leaf run +/// from Help or describe-key is typed as its keys are. +pub fn keysOf(root: Root, path: []const u8, out: *[16]Key) []Key { + out[0] = info.get(root).key; + const n = @min(path.len, out.len - 1); + for (path[0..n], 1..) |k, i| out[i] = .{ .cp = k }; + return out[0 .. n + 1]; +} + +/// The root a key starts, if it starts one. +pub fn rootOf(key: Key) ?Root { + for (std.enums.values(Root)) |r| { + const k = info.get(r).key; + if (key.cp == k.cp and key.ctrl == k.ctrl and !key.alt) return r; + } + return null; +} + +/// `SPC l k`, `g d`, `C-w h`: a chord as Help's rows and describe-key spell +/// it. +pub fn chord(root: Root, path: []const u8, buf: []u8) []const u8 { + var w = std.Io.Writer.fixed(buf); + w.writeAll(if (root == .leader) "SPC" else info.get(root).cell) catch {}; + for (path) |k| w.print(" {s}", .{keyName(k)}) catch {}; + return w.buffered(); +} + +/// Every leaf of every root, Help's rows (SPEC §4.5): `chord · word · group`, +/// and the same in lowercase, which the scorer matches a lowercase query +/// against. +pub const Flat = struct { root: Root, path: []const u8, node: *const Node, row: []const u8, lower: []const u8 }; + +pub const flat: []const Flat = flat: { + @setEvalBranchQuota(1_000_000); + var all: []const Flat = &.{}; + for (std.enums.values(Root)) |r| all = all ++ flatten(r, info.get(r).node, "", info.get(r).label); + break :flat all; +}; + +fn flatten(comptime r: Root, comptime node: *const Node, comptime path: []const u8, comptime group: []const u8) []const Flat { + comptime { + var all: []const Flat = &.{}; + for (node.children) |*c| { + const here = path ++ .{c.key}; + if (c.children.len > 0) { + all = all ++ flatten(r, c, here, if (r == .leader) c.label else group ++ " " ++ c.label); + continue; + } + var spelled: []const u8 = if (r == .leader) "SPC" else info.get(r).cell; + for (here) |k| spelled = spelled ++ " " ++ keyName(k); + const row = spelled ++ " · " ++ c.label ++ " · " ++ (if (r == .leader and path.len == 0) "root" else group); + var lower: [row.len]u8 = undefined; + for (row, 0..) |ch, i| lower[i] = std.ascii.toLower(ch); + const low = lower; + all = all ++ .{Flat{ .root = r, .path = here, .node = c, .row = row, .lower = &low }}; + } + return all; + } +} + +test "SPC's tree is made from the leader paths, groups first, a key's lowercase before its capital" { + const top = nodeAt(.leader, "").?; + // Groups first: every group comes before every leaf. + var leaves = false; + for (top.children) |c| { + if (c.children.len == 0) leaves = true else try std.testing.expect(!leaves); + } + const l = nodeAt(.leader, "l").?; + try std.testing.expectEqualStrings("lsp", l.label); + try std.testing.expect(l.lsp == false and l.children.len >= 15); + // `d` Diagnostics before `D` WsDiagnostics, `s` before `S`. + var d: ?usize = null; + for (l.children, 0..) |c, i| { + if (c.key == 'd') d = i; + if (c.key == 'D') try std.testing.expectEqual(d.? + 1, i); + } + const hover = nodeAt(.leader, "lk").?; + try std.testing.expectEqualStrings("Hover", hover.label); + try std.testing.expect(hover.lsp and hover.leaf.?.builtin == .Hover); + // A path with an argument is a leaf of its own word. + try std.testing.expectEqualStrings("Panes", nodeAt(.leader, "bb").?.label); + try std.testing.expect(nodeAt(.leader, "lz") == null); +} + +test "the helix prefixes are trees of their roles: a builtin by its word, a motion by its description" { + try std.testing.expectEqualStrings("Def", nodeAt(.goto, "d").?.label); + try std.testing.expectEqualStrings("line start", nodeAt(.goto, "h").?.label); + try std.testing.expectEqualStrings("file start", nodeAt(.goto, "g").?.label); + try std.testing.expectEqualStrings("top", nodeAt(.view, "t").?.label); + try std.testing.expectEqualStrings("matching bracket", nodeAt(.match, "m").?.label); + try std.testing.expectEqualStrings("function", nodeAt(.next, "f").?.label); + try std.testing.expectEqualStrings("add newline", nodeAt(.prev, " ").?.label); + try std.testing.expectEqualStrings("Left", nodeAt(.window, "h").?.label); + // `zz` and `zc` both centre: one row, the first key. + var centres: usize = 0; + for (nodeAt(.view, "").?.children) |c| if (std.mem.eql(u8, c.label, "center")) { + centres += 1; + }; + try std.testing.expectEqual(@as(usize, 1), centres); +} + +test "Help's rows: every leaf of every root, spelled as its chord, its word and its group" { + var found: usize = 0; + for (flat) |f| { + if (std.mem.eql(u8, f.row, "SPC l k · Hover · lsp")) found += 1; + if (std.mem.eql(u8, f.row, "g d · Def · goto")) found += 1; + if (std.mem.eql(u8, f.row, "] f · function · next")) found += 1; + if (std.mem.eql(u8, f.row, "SPC q · Exit · root")) found += 1; + } + try std.testing.expectEqual(@as(usize, 4), found); + for (flat) |f| try std.testing.expectEqual(f.row.len, f.lower.len); +} diff --git a/core/builtins.zig b/core/builtins.zig index af53fa6f..56cd1e67 100644 --- a/core/builtins.zig +++ b/core/builtins.zig @@ -1622,6 +1622,19 @@ pub const Help = struct { } }; +/// Show what a key sequence runs: the next keys typed are replayed in the tag. +/// +/// The tag shows `Keys` and the keys as they are typed; a sequence that +/// reaches a leaf unrolls its level under the tag with the leaf on the +/// cursor and its documentation beside it, and Enter runs it. Every root +/// answers: SPC, g, m, z, Z, [, ], window mode's C-w. A sequence nothing +/// is bound to is shown struck, `runs nothing`. Esc leaves it. +pub const Keys = struct { + pub fn run(c: Ctx) void { + pardes.TagState.openDescribe(c.p, c.id); + } +}; + /// Open the startup file, `init` in the configuration directory, in a pane. /// /// Its pane when it is open, else the file; not there yet, a pane of that @@ -1816,6 +1829,7 @@ pub const Grep = struct { /// stays, its count 0; the write hears `not found`. fn search(c: Ctx, source: panes.Query.Source, miss: []const u8) void { const pat = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); + if (pardes.Pick.asked(c.p)) return pardes.Pick.open(c.p, c.id, if (source == .find) .find else .grep, "", pat, ""); const reused = panes.Query.ofOwner(c.p, c.pane.serial) != null; panes.Query.open(c.p, c.id, source, pat, pat.len == 0); if (pat.len == 0 or !c.p.fs.serving) return; @@ -1838,6 +1852,11 @@ pub const Search = struct { pub fn run(c: Ctx) void { const line = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); const asked = panes.Query.parse(line) orelse panes.Query.parse(std.mem.concat(c.p.scratch.allocator(), u8, &.{ "/", line }) catch return).?; + // `SPC b b`, `SPC s s`, `SPC /` and the like: a picker in the tag. + if (pardes.Pick.asked(c.p)) switch (asked.source) { + inline .find, .grep, .recent, .panes, .symbols, .all => |s| return pardes.Pick.open(c.p, c.id, @field(pardes.Pick.Source, @tagName(s)), "", asked.pat, ""), + else => {}, + }; panes.Query.open(c.p, c.id, asked.source, asked.pat, true); } }; @@ -1859,6 +1878,7 @@ pub const Panes = struct { pub const takes_arg = true; pub const quiet = true; pub fn run(c: Ctx) void { + if (pardes.Pick.asked(c.p)) return pardes.Pick.open(c.p, c.id, .panes, "", std.mem.trim(u8, c.arg orelse "", " \t\r\n"), ""); panes.Query.open(c.p, c.id, .panes, std.mem.trim(u8, c.arg orelse "", " \t\r\n"), true); } }; @@ -2013,6 +2033,27 @@ pub const Forward = struct { } }; +/// Reopen the last picker as it was: its rows, marks, cursor and query. +/// +/// In the tag of the pane its Enter lands in from this one: this pane if it +/// reads, else its reader. `SPC '`. +pub const Resume = struct { + pub fn run(c: Ctx) void { + pardes.Pick.resumeFrom(c.p, c.id); + } +}; + +/// Keep this pane: a reading pane, which a jump steps, is held from now on. +/// +/// Its walk leaves its tag (its places, its owner): the next jump from its +/// owner makes a new reader. Editing a reading pane keeps it too. +pub const Keep = struct { + pub fn run(c: Ctx) void { + if (!pardes.Trail.reading(c.p, c.pane)) return c.p.setMessage(.at(c.id), "Keep: this pane is held already"); + pardes.Trail.keep(c.pane); + } +}; + /// Select the next thing a Look would open: a place in a list, a word that /// names a file. /// @@ -2066,6 +2107,7 @@ pub const Recent = struct { // The query pane under the pane the keyboard is in, line 1 // `Recent `, typed into; what follows the word narrows the files. if (c.p.panes[c.id] == null) return c.p.reportFailure(c.id, "Recent: open a pane to search from"); + if (pardes.Pick.asked(c.p)) return pardes.Pick.open(c.p, c.id, .recent, "", std.mem.trim(u8, c.arg orelse "", " \t\r\n"), ""); panes.Query.open(c.p, c.id, .recent, std.mem.trim(u8, c.arg orelse "", " \t\r\n"), true); } }; @@ -2095,6 +2137,7 @@ pub const Jumplist = struct { pub const scope: Scope = .session; pub const output: OutputTraits = .{ .name = config.jumps_buffer, .steps = true, .locations = true }; pub fn run(c: Ctx) void { + if (pardes.Pick.asked(c.p)) return pardes.Pick.open(c.p, c.id, .jumplist, "", "", ""); panes.Output.openJumps(c.p, c.id) catch |err| c.p.reportError(.at(c.id), "jumplist", err); } }; diff --git a/core/colors.zig b/core/colors.zig index e239d717..88cc6ea4 100644 --- a/core/colors.zig +++ b/core/colors.zig @@ -287,6 +287,9 @@ pub const Theme = struct { lineno_active: ?[3]u8 = null, /// A tag's selection, where it differs from the body's (acme's #9eeeee). tag_sel_bg: ?[3]u8 = null, + /// The tag of a reading pane, one a jump steps (Trail.zig): unset, the + /// page tinted toward the search's ground, so it reads as the body's. + tag_reading_bg: ?[3]u8 = null, /// Each pointer button's sweep, select, exec and look (Mouse.Button /// order), and the ink over it. Unset, tints of `sel_bg` in `sel_fg`. sweep_bg: ?[3][3]u8 = null, @@ -543,6 +546,7 @@ pub const ChromeTheme = struct { empty_col: [3]u8, search_bg: [3]u8, search_fg: [3]u8, + tag_reading_bg: [3]u8, diagnostic_error: [3]u8, diagnostic_warning: [3]u8, diagnostic_info: [3]u8, @@ -579,6 +583,7 @@ pub const ChromeTheme = struct { .empty_col = th.empty_col orelse separatorOf(th), .search_bg = th.search_bg orelse th.sel_bg, .search_fg = th.search_fg orelse th.sel_fg, + .tag_reading_bg = th.tag_reading_bg orelse mixOklab(th.bg orelse th.tag_bg, th.search_bg orelse th.sel_bg, 0.4), .diagnostic_error = th.diagnostic_error orelse (th.fg orelse th.tag_fg), .diagnostic_warning = th.diagnostic_warning orelse (th.fg orelse th.tag_fg), .diagnostic_info = th.diagnostic_info orelse (th.fg orelse th.tag_fg), diff --git a/core/config.zig b/core/config.zig index dd8ad5d3..8bcf649f 100644 --- a/core/config.zig +++ b/core/config.zig @@ -115,6 +115,7 @@ pub const leader_path = paths: { .Changelog = "hc", .Build = "hb", .Messages = "hm", + .Keys = "hk", .Message = "e", .Newcol = "cn", .Delcol = "cd", @@ -145,6 +146,8 @@ pub const leader_path = paths: { .Unfollow = null, .Back = "jo", .Forward = "ji", + .Keep = "jk", + .Resume = "'", .Last = "jj", .Jumplist = "jl", .History = "fh", @@ -158,6 +161,7 @@ pub const leader_path = paths: { table.set(.TaglineSize, null); } table.set(.MessageLinger, null); + table.set(.Jumps, null); table.set(.DumpDir, null); if (builtins.capabilities.window_opacity) table.set(.WindowOpacity, null); if (builtins.capabilities.pixels) table.set(.CursorBlink, null); @@ -670,9 +674,16 @@ pub const Settings = struct { tab: u16 = tab_width, callstack_depth: u8 = @import("lsp/lsp.zig").callstack_default_depth, + /// A jump (a Look at a place, a definition, an error's place) steps + /// the pane it is made from, or its reader, as a walk (Trail.zig); or + /// opens a pane for each file, as before the walk, until the walk's + /// pickers and prompts are in (pick-ui SPEC §14.3). + jumps: Jumps = .@"new-pane", + /// A setting that is one of a few words, each an enum field of Settings. - pub const Choice = enum { pet }; + pub const Choice = enum { pet, jumps }; pub const Pet = enum { off, cat, frog }; + pub const Jumps = enum { walk, @"new-pane" }; pub const tagline_percent_min: u8 = 1; pub const tagline_percent_max: u8 = 100; @@ -800,6 +811,7 @@ pub const Settings = struct { .{ .word = "GripWidth", .action = .grip_width, .doc = "The grip and scrollbar width, as a percent of the theme's rail." }, .{ .word = "InactiveDim", .action = .inactive_dim, .doc = "Fade the unfocused panes' text by a percentage, 0 through 100, 0 off." }, .{ .word = "Pet", .action = .{ .choice = .pet }, .doc = "The window's companion in the workspace tag's blank space: off, cat or frog." }, + .{ .word = "Jumps", .action = .{ .choice = .jumps }, .doc = "A jump steps its pane or that pane's reader (walk), or opens a pane for each file (new-pane)." }, .{ .word = "MessageLinger", .action = .message_linger, .doc = "How long, in milliseconds, an echo or a notice stays bright before it dims; a warning twice as long." }, .{ .word = "DumpDir", .action = .dump_dir, .doc = "The directory of the state file, where Dump writes and Recent is kept. A relative Restore name is looked for there too; bare, the default." }, .{ .word = "Theme", .action = .theme, .doc = "Switch to the theme named: `Theme atelier`. Themes lists them, NextColor steps through them." }, @@ -1658,7 +1670,11 @@ test "Space-k is unbound while Exit, Kill and other k chords remain available" { while (p.nextEffect()) |_| {} p.update(.{ .key = .{ .cp = ' ' } }); try std.testing.expect(p.view().prefix == .leader); + // A key SPC has no child for is struck, the level kept (walk UI); Esc + // leaves it. p.update(.{ .key = .{ .cp = 'k' } }); + try std.testing.expect(p.view().prefix == .leader and p.view().tag_state.miss == 'k' and !p.quit); + p.update(.{ .key = .{ .cp = Key.escape } }); try std.testing.expect(p.view().prefix != .leader and !p.quit); try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row); while (p.nextEffect()) |effect| try std.testing.expect(effect != .quit); diff --git a/core/draw.zig b/core/draw.zig index 8baca6ca..f7b2cd3f 100644 --- a/core/draw.zig +++ b/core/draw.zig @@ -16,6 +16,7 @@ const edit = @import("edit.zig"); const tagline = @import("tagline.zig"); const body_layer = @import("body_layer.zig"); const Messages = @import("Messages.zig"); +const TagState = @import("TagState.zig"); const builtins = @import("builtins.zig"); const Color = @import("surface.zig").Color; const FontRole = @import("surface.zig").FontRole; @@ -229,7 +230,7 @@ fn joinNotice(p: *Pardes, s: *Surface, arena: std.mem.Allocator, region: Region) const kind = pane.notices.kinds[i]; const r = v.rects[id]; const chip = region.rect.w; - var leader_buf: [16]u8 = undefined; + var leader_buf: [Messages.leader_room]u8 = undefined; const text = Messages.noticeText(p, pane, i, &leader_buf); const bg = chrome.tag_bg; const fg = chrome.tag_fg; @@ -359,6 +360,18 @@ pub fn render(p: *Pardes, arena: std.mem.Allocator) !*Surface { for (s.regionList()) |region| { if (region.kind == .notice) try joinNotice(p, s, arena, region); } + // A tag out of rest: the other panes dim a little so the eye goes to + // it, but a pane showing a preview (walk UI SPEC §3.6). + if (TagState.hostOf(p)) |host| for (p.panes, 0..) |slot, id| { + if (slot == null or id == host or v.tag_state.previewing.isSet(id)) continue; + const r = v.rects[id]; + for (r.y..r.y + r.h) |y| for (r.x..r.x + r.w) |x| { + s.at(@intCast(x), @intCast(y)).style.dim = true; + }; + for ([_]*pardes.Layer{ &s.body_layers[id], &s.tag_layers[id] }) |layer| for (layer.cells[0 .. @as(usize, layer.cols) * layer.rows]) |*cell| { + cell.style.dim = true; + }; + }; try paintHeaders(p, s); try paintNoticeRow(p, s); @@ -455,7 +468,7 @@ fn renderPane(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, r: // its ring. A pixel shell draws the ring (gui.zig gripDecor); a grid, // which cannot, marks dirty in the grip's second cell with a bold `*` // on the dirty colour, a cue that survives any palette. - const band = if (active) chrome.tag_active_bg else chrome.tag_bg; + const band = tagGround(p, pane, active); const dirty = tagline.dirty(pane); const box_bg = gripBg(p, active); const box_style: CellStyle = .{ @@ -482,13 +495,19 @@ fn renderPane(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, r: }); // In window mode the box holds the pane's letter instead of its mode. const label: ?u8 = if (p.view().window_pick != null) layout.windowLabel(p, id) else null; - s.set(r.x, tag_y, if (label) |*letter| @as(*const [1]u8, letter) else switch (pane.body.mode) { + // A tag in a typing state is typed in: its box says so (walk UI SPEC + // §3.2), whatever the body's mode. + const typing = p.view().tag_state.kind != .rest and TagState.hostOf(p) == id; + s.set(r.x, tag_y, if (label) |*letter| @as(*const [1]u8, letter) else if (typing) config.tag_insert else switch (pane.body.mode) { .normal => config.tag_normal, .insert => config.tag_insert, .tty => config.tag_tty, }, box_style); try joinPaneTag(p, s, arena, pane, r, id, active); + // The keyboard is in the head's field: its caret, not the body's. + const head_caret = if (typing) s.cursor else null; + if (pane.band_rows > 0) try joinBand(p, s, arena, pane, r, id, active); // Folded panes retain their body state, but neither body pixels nor // its cursor belong outside the one-row tag rectangle. @@ -523,6 +542,10 @@ fn renderPane(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, r: } try body_layer.joinBody(p, s, arena, pane, r, id, active, rail.*); + if (typing) { + s.body_layers[id].cursor = null; + s.cursor = head_caret; + } if (pane.layers.heat > 0) @import("jj.zig").railHeat(p, s, pane, id, rail.rect); // A terminal panned to its cursor in a view shorter than it: an arrow // in the gutter's first body row says rows are above (views.zig). @@ -676,7 +699,7 @@ fn tagTintRange(pane: *const Pane, tag: []const u8, prefix_len: usize) ?struct { } return null; } - var start: usize = 0; + var start: usize = tagline.nameAt(pane); const name = if (pane.file) |file| if (pane.prompt == .name) pane.input.own orelse file.path else file.path else if (pane.addon) |k| blk: { @@ -723,7 +746,7 @@ fn renderHeaderLayer(p: *Pardes, layer: *pardes.Layer, kind: TagKind, id: u16, v const editing: ?*Text = if (v.header != null and switch (kind) { .workspace => p.headerColumn() == null, .column => p.headerColumn() == id, - .pane, .notice, .body, .notice_row => false, + .pane, .notice, .body, .band, .notice_row => false, }) tagline.focusedHeader(p) else null; const scroll = if (editing != null) v.header_scroll else 0; for (0..viewport.h) |index| { @@ -775,7 +798,7 @@ fn renderHeaderLayer(p: *Pardes, layer: *pardes.Layer, kind: TagKind, id: u16, v const mine = switch (kind) { .workspace => column == null, .column => column == id, - .pane, .notice, .body, .notice_row => false, + .pane, .notice, .body, .band, .notice_row => false, }; const swept = sweep.span(text.len); const start = modal.lineStartOffset(text, index + top); @@ -803,7 +826,8 @@ fn joinPaneTag(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, r const chrome = p.chromeTheme(); const region = s.region(.tag, id).?; const tag = (try tagline.shownTag(p, arena, pane)).text; - const rows = pane.tag_rows; + // The tag's text rows; the band's under them are its own layer. + const rows = pane.tag_rows - pane.band_rows; // As wide as the widest row it shows, and never narrower than its // viewport. var widest: usize = 0; @@ -833,7 +857,7 @@ fn joinPaneTag(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, r layer.cols = columns; layer.rows = rows; layer.context_rows = 0; - layer.bg = if (v.window_pick == id) p.theme().sel_bg else if (active) chrome.tag_active_bg else chrome.tag_bg; + layer.bg = if (v.window_pick == id) p.theme().sel_bg else tagGround(p, pane, active); layer.cursor = if (v.header != null) null else if (temporary.cursor) |cursor| .{ .x = cursor.x - TAG_TEXT_INSET, .y = cursor.y, .bar = cursor.bar } else @@ -850,16 +874,113 @@ fn joinPaneTag(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, r } } +/// The band under pane `id`'s tag text (Band.zig), painted once into its +/// layer at the tagline's pitch, a row to a line, and copied into the +/// grid: the spines and steps in the tag's tint, the keys in the key ink, +/// the cursor's row tinted as a selection. +fn joinBand(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, r: Rect, id: usize, active: bool) !void { + const layer = &s.tag_layers[pardes.BAND_LAYER]; + if (r.w <= TAG_TEXT_INSET) return; + const band = (try pardes.Band.of(p, arena, pane, id)) orelse return; + const th = p.theme(); + const chrome = p.chromeTheme(); + const tab = p.settings.tab; + const rows = pane.band_rows; + const columns = @max(band.columns, 1); + const bg = tagGround(p, pane, active); + const fg = if (active) chrome.tag_active_fg else chrome.tag_fg; + const storage = try arena.alloc(Cell, @as(usize, columns) * rows); + @memset(storage, .{}); + var t: Surface = .{ .cols = columns, .rows = rows, .cells = storage, .tab = tab }; + for (0..rows) |y| { + const row: u16 = @intCast(y); + t.fill(0, row, columns, 1, .{ .bg = .{ .rgb = bg }, .font_role = .tagline }); + const ln = try band.line(arena, tab, row); + _ = t.print(0, row, columns, ln.text, .{ .fg = .{ .rgb = fg }, .bg = .{ .rgb = bg }, .font_role = .tagline }); + // The spines and the rules between steps: the key ink. + var col: u16 = 0; + var at: usize = 0; + while (at < ln.text.len and col < columns) : (col += 1) { + const next = modal.nextGrapheme(ln.text, at); + if (std.mem.eql(u8, ln.text[at..next], "│")) t.at(col, row).style.fg = .{ .rgb = chrome.box }; + if (std.mem.eql(u8, ln.text[at..next], "▶")) t.at(col, row).style.fg = .{ .rgb = chrome.box }; + at = next; + } + for (ln.parts) |part| { + const end = @min(columns, part.col + part.width); + if (part.row.on and part.col < end) t.tint(part.col, row, end - part.col, th.tag_sel_bg orelse th.sel_bg, th.sel_fg); + var c = part.col; + var b: usize = 0; + while (b < part.row.text.len and c < end) : (c += 1) { + const next = modal.nextGrapheme(part.row.text, b); + const style = &t.at(c, row).style; + if (b < part.row.key) { + style.fg = .{ .rgb = chrome.box }; + style.bold = true; + } + if (b < part.row.pre) style.fg = .{ .rgb = if (active) chrome.tag_active_name_fg else chrome.tag_name_fg }; + if (part.row.dim or (b >= part.row.pre and b < part.row.pre + part.row.faint)) style.dim = true; + if (part.row.under) style.ul = .single; + for (part.row.marks) |m| if (m == b) { + style.bg = .{ .rgb = chrome.search_bg }; + }; + b = next; + } + } + } + const count = @as(usize, columns) * rows; + if (layer.cells.len != count) layer.cells = try p.gpa.realloc(layer.cells, count); + @memcpy(layer.cells, storage); + const y0 = p.tagTop(pane, r) + (pane.tag_rows - rows); + layer.kind = .band; + layer.id = @intCast(id); + layer.serial = pane.serial; + layer.viewport = .{ .x = r.x + TAG_TEXT_INSET, .y = y0, .w = r.w - TAG_TEXT_INSET, .h = rows }; + layer.cols = columns; + layer.rows = rows; + layer.context_rows = 0; + layer.bg = bg; + layer.cursor = null; + for (0..rows) |y| joinCells(s, r.x + TAG_TEXT_INSET, y0 + @as(u16, @intCast(y)), storage[y * columns ..][0..columns], 0, r.w - TAG_TEXT_INSET, .{ .rgb = fg }); +} + +/// Bytes `lo` to `hi` of a tag's text in `ink`, over whichever of its +/// shown rows (`lines`, from shown row `top`, drawn at `x`, `y`, `w` +/// wide) they wrapped onto. +fn inkTag(p: *Pardes, s: *Surface, shown: tagline.Shown, lines: []const []const u8, top: usize, x: u16, y: u16, w: u16, lo: usize, hi: usize, ink: [3]u8) void { + const a = modal.positionAt(shown.text, shown.fromReal(lo)); + const b = modal.positionAt(shown.text, shown.fromReal(hi)); + var row = @max(a.row, top); + while (row <= b.row and row < top + lines.len) : (row += 1) { + const line = lines[row - top]; + const from = if (row == a.row) a.col else 0; + const to = if (row == b.row) b.col else line.len; + var col = panes.File.rawDisplayCol(p.settings.tab, line, @min(from, line.len)); + const end = panes.File.rawDisplayCol(p.settings.tab, line, @min(to, line.len)); + const row_y = y + @as(u16, @intCast(row - top)); + while (col < end and col < w) : (col += 1) + s.at(x + @as(u16, @intCast(col)), row_y).style.fg = .{ .rgb = ink }; + } +} + +/// A pane's tag's ground: a reading pane's tint (its focus is its grip's), +/// else the focused tag's or the tag's. +fn tagGround(p: *Pardes, pane: *const Pane, active: bool) [3]u8 { + const chrome = p.chromeTheme(); + if (pardes.Trail.reading(p, pane)) return chrome.tag_reading_bg; + return if (active) chrome.tag_active_bg else chrome.tag_bg; +} + fn paintPaneTag(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, r: Rect, id: usize, active: bool) !void { const th = p.theme(); const chrome = p.chromeTheme(); const tx = r.x + @min(TAG_TEXT_INSET, r.w); const tw = r.w -| TAG_TEXT_INSET; const tag_y = p.tagTop(pane, r); - const rows = pane.tag_rows; + const rows = pane.tag_rows - pane.band_rows; const page_rgb = th.bg orelse th.tag_bg; // Focus is visible along the tag without changing its live text grid. - const tag_bg = if (active) chrome.tag_active_bg else chrome.tag_bg; + const tag_bg = tagGround(p, pane, active); const tag_fg = if (active) chrome.tag_active_fg else chrome.tag_fg; const tag_style: CellStyle = .{ .fg = .{ .rgb = tag_fg }, .bg = .{ .rgb = tag_bg }, .font_role = .tagline }; // Padding belongs to the same font row but keeps its default ink: a @@ -869,7 +990,9 @@ fn paintPaneTag(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, .font_role = .tagline, }); const whole = try tagline.tagText(p, arena, pane); - const tail = tagline.curTail(pane); + // Out of rest, the head in place of the tag's own text (TagState). + const head = try TagState.head(p, arena, pane); + const tail = if (head) |h| h.text else tagline.curTail(pane); const prefix_len = whole.len - tail.len; // A row per line shown, from `tag_top`: the tag's first line carries // the prefix, the rest are the tag's own text alone. @@ -889,10 +1012,10 @@ fn paintPaneTag(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, else if (pane.prompt == .name) caret: { // A drafted name is the prefix: its caret is on row 0 of the tag, // the rows it wrapped onto included. - const at = modal.positionAt(shown.text, shown.fromReal(@intCast(@max(0, pane.input.cur_col)))); + const at = modal.positionAt(shown.text, shown.fromReal(tagline.nameAt(pane) + @as(usize, @intCast(@max(0, pane.input.cur_col))))); if (at.row < top or at.row >= top + rows) break :caret null; break :caret .{ .row = at.row - top, .at = @min(lines[at.row - top].len, at.col) }; - } else if (pane.focus == .tag and pane.prompt == .none) caret: { + } else if (pane.focus == .tag and pane.prompt == .none and head == null) caret: { const real = modal.offsetAt(whole, .{ .row = @intCast(@max(0, pane.tag.cur_row)), .col = @intCast(@max(0, pane.tag.cur_col)) }); const at = modal.positionAt(shown.text, shown.fromReal(real)); if (at.row < top or at.row >= top + rows) break :caret null; @@ -920,10 +1043,16 @@ fn paintPaneTag(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, // The name's tint, in the tag's first line, over whichever rows it // wrapped onto. const first_line = whole[0 .. std.mem.indexOfScalar(u8, whole, '\n') orelse whole.len]; - if (tagTintRange(pane, first_line, prefix_len)) |name| if (name.lo < name.hi) { - const name_fg = if (active) chrome.tag_active_name_fg else chrome.tag_name_fg; - const a = modal.positionAt(shown.text, shown.fromReal(name.lo)); - const b = modal.positionAt(shown.text, shown.fromReal(@min(name.hi, first_line.len))); + if (tagTintRange(pane, first_line, prefix_len)) |name| if (name.lo < name.hi) + inkTag(p, s, shown, lines[0..rows], top, tx, tag_y, tw, name.lo, @min(name.hi, first_line.len), if (active) chrome.tag_active_name_fg else chrome.tag_name_fg); + // A walk's forward steps, after the name, dimmed (Trail.zig). + const ahead = tagline.forwardSpan(pane); + if (ahead[0] < ahead[1]) inkTag(p, s, shown, lines[0..rows], top, tx, tag_y, tw, ahead[0], @min(ahead[1], first_line.len), chrome.lineno); + // The head's keys in the key ink, its dimmed, underlined and struck + // words (TagState.Span), over whichever rows they wrapped onto. + if (head) |h| for (h.spans) |span| { + const a = modal.positionAt(shown.text, shown.fromReal(prefix_len + span.lo)); + const b = modal.positionAt(shown.text, shown.fromReal(prefix_len + span.hi)); var row = @max(a.row, top); while (row <= b.row and row < top + rows) : (row += 1) { const line = lines[row - top]; @@ -932,13 +1061,23 @@ fn paintPaneTag(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, var col = panes.File.rawDisplayCol(p.settings.tab, line, @min(from, line.len)); const end = panes.File.rawDisplayCol(p.settings.tab, line, @min(to, line.len)); const y = tag_y + @as(u16, @intCast(row - top)); - while (col < end and col < tw) : (col += 1) - s.at(tx + @as(u16, @intCast(col)), y).style.fg = .{ .rgb = name_fg }; + while (col < end and col < tw) : (col += 1) { + const style = &s.at(tx + @as(u16, @intCast(col)), y).style; + switch (span.style) { + .key => { + style.fg = .{ .rgb = chrome.box }; + style.bold = true; + }, + .dim => style.dim = true, + .under => style.ul = .single, + .strike => style.strikethrough = true, + } + } } }; // The tag's own selections, while it has the keyboard, a line at a // time. A range of one grapheme is the block cursor, not a selection. - if (pane.focus == .tag) { + if (pane.focus == .tag and head == null) { var ranges: [Text.max_selections]modal.Selection = undefined; const got = pane.tag.ranges(whole, 0, &ranges); for (ranges[0..got.n]) |range| { @@ -958,6 +1097,15 @@ fn paintPaneTag(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, } } } + // A head typed in: its caret a bar at the field's. + if (head) |h| if (h.caret) |c| if (active) { + const at = modal.positionAt(shown.text, shown.fromReal(prefix_len + c)); + if (at.row >= top and at.row < top + rows) { + const line = lines[at.row - top]; + const col = panes.File.rawDisplayCol(p.settings.tab, line, @min(at.col, line.len)); + if (col < tw) s.cursor = .{ .x = tx + @as(u16, @intCast(col)), .y = tag_y + @as(u16, @intCast(at.row - top)), .bar = true }; + } + }; // the caret: bar while typing, block in normal mode (same rule as a body) if (caret) |at| { const col = panes.File.rawDisplayCol(p.settings.tab, lines[at.row], at.at) -| pane.tag_scroll; @@ -1114,7 +1262,7 @@ test "a tag of three rows has its grip on the first, and band under it that stil const top = p.tagTop(pane, r); try std.testing.expect(pane.tag_rows >= 3); const chrome = p.chromeTheme(); - const band = chrome.tag_active_bg; + const band = tagGround(p, pane, true); for (0..config.GUTTER) |dx| { const x = r.x + @as(u16, @intCast(dx)); try std.testing.expectEqual(Color{ .rgb = chrome.box }, s.at(x, top).style.bg); diff --git a/core/dump.zig b/core/dump.zig index b4561ae2..683f043a 100644 --- a/core/dump.zig +++ b/core/dump.zig @@ -405,20 +405,19 @@ fn loadKnowing(gpa: std.mem.Allocator, opts: Options, bytes: []const u8, notes: l.allocs = .{ .image = p.image_gpa, .terminal = terminal_gpa }; try l.into(Pardes, p); const read = l.shared.items.len; - const mounts = try l.get([]const filesystem.Mount); + // What is read after the core (its mounts, its theme) is freed here, + // what the load made for it once each, and no rollback of it: a + // damaged dump's reference to a slice the core holds is the core's, + // never freed here (a theme that was one was freed by hand and again + // by the rollback). defer { - for (mounts) |m| { - gpa.free(m.name); - gpa.free(m.dial); - } - gpa.free(mounts); - // Freed here: no rollback of them. + for (l.shared.items[read..]) |m| if (m.bytes.len > 0) m.gpa.rawFree(m.bytes, m.alignment, @returnAddress()); l.shared.shrinkRetainingCapacity(read); } + const mounts = try l.get([]const filesystem.Mount); const was = try l.get(OnDisk); if (on_disk) |out| out.* = was; const theme = try l.get([]const u8); - defer gpa.free(theme); // This build's place for that theme; one it has not, its first. p.settings.theme = for (colors.themes, 0..) |t, i| { if (std.mem.eql(u8, t.name, theme)) break i; @@ -452,8 +451,8 @@ fn loadKnowing(gpa: std.mem.Allocator, opts: Options, bytes: []const u8, notes: else => return err, }; views.undumped(p, others); - for (others) |o| gpa.free(o.panes); - gpa.free(others); + // What it made, as the mounts' (above). + for (l.shared.items[at..]) |m| if (m.bytes.len > 0) m.gpa.rawFree(m.bytes, m.alignment, @returnAddress()); l.shared.shrinkRetainingCapacity(at); afterLoad(p); p.readSessionFacts(); diff --git a/core/edit.zig b/core/edit.zig index ca9cbd91..ac78fd32 100644 --- a/core/edit.zig +++ b/core/edit.zig @@ -680,6 +680,11 @@ fn setEditTextSpan(e: Editor, t: *Text, new: []u8, known_end: ?modal.Cursor, spa // caller reads the new text back, as a body's is kept. defer retireEditText(e, new); const pane = t.pane() orelse return; + // Out of rest the tag shows its head, which is no one's to edit. + if (try pardes.TagState.head(e.p, e.scratch, pane) != null) { + t.refused = true; + return; + } const prefix = try tagline.pathPrefix(e.p, e.scratch, pane); if (!std.mem.startsWith(u8, new, prefix)) { t.refused = true; diff --git a/core/exec.zig b/core/exec.zig index 6b05cb8e..5a5ff725 100644 --- a/core/exec.zig +++ b/core/exec.zig @@ -880,6 +880,8 @@ pub fn executeBuiltinLine(p: *Pardes, id: usize, txt: []const u8) bool { const raw = commandText(txt); if (raw.len == 0 or p.exec_depth >= max_exec_depth) return false; if (isComment(raw)) return true; + // A live picker's act and source words are its own (Pick.zig). + if (pardes.Pick.execWord(p, raw)) return true; // `+` too, so an old `Tty+fish` is renamed as `Tty fish` is. const word_end = std.mem.indexOfAny(u8, raw, " \t+") orelse raw.len; var renamed: [1024 + 16]u8 = undefined; diff --git a/core/fuzz.zig b/core/fuzz.zig index 616636ab..c68c7810 100644 --- a/core/fuzz.zig +++ b/core/fuzz.zig @@ -777,6 +777,8 @@ test "a dump and an image cut, flipped and grown: refused or loaded, never a pan const gpa = testing.allocator; const p = try th.withFile(gpa, "alpha beta\ngamma\n\tdelta \xe6\x97\xa5\n"); defer p.deinit(); + // A reader's walk in it: a union, a fixed array held to its length. + p.panes[0].?.trail = pardes.Trail.reader(7, "/x/rank.zig", .{ .line = 3, .col = 2 }); // The byte dump a join streams, and the image a Dump keeps. const bytes = try pardes.dump.byteDump(p); defer gpa.free(bytes); @@ -785,6 +787,9 @@ test "a dump and an image cut, flipped and grown: refused or loaded, never a pan // Seconds a road, each core used (`use`). The image's past 1779 seeds // reach xitdb's own reader (a slot's tag past its kinds: a `switch` on // it), a dependency's. + // Join seed 19224: the theme read after the core a reference to a + // slice the core holds, freed by hand and again by the rollback. + try loadSeed(bytes, .join, 19224); for ([_][]const u8{ bytes, image }, [_]Road{ .join, .restore }, [_]u64{ 2048, 1024 }) |whole, road, n| { try loadSeed(whole, road, 0); for (1..n + 1) |seed| try loadSeed(whole, road, seed); diff --git a/core/keys.zig b/core/keys.zig index 68e3585d..c30ef233 100644 --- a/core/keys.zig +++ b/core/keys.zig @@ -18,6 +18,8 @@ const ctlfs = @import("ninep/tree.zig"); const Macro = @import("Macro.zig"); const Pipe = @import("Pipe.zig"); const Registers = @import("Registers.zig"); +const bindings = @import("bindings.zig"); +const TagState = @import("TagState.zig"); const Pardes = pardes.Pardes; const Pane = panes.Pane; const Text = panes.Text; @@ -191,6 +193,9 @@ pub fn answerQuestion(p: *Pardes, id: usize, choice: ?u8) bool { } pub fn handleKey(p: *Pardes, key: Key) void { + // A root this key strikes starts its which-key delay; one it ends + // takes its level away (TagState). + defer TagState.follow(p); // A double-click is two clicks with nothing between them. p.view().last_click = null; if (p.macro.recording != 0 and p.macro.replaying == 0) Macro.append(&p.macro.recorded, p.gpa, key) catch |err| p.reportError(.at(p.view().active), "macro", err); @@ -223,6 +228,8 @@ pub fn handleKey(p: *Pardes, key: Key) void { return; } p.view().answering = 0; + // A tag in a typing state takes every key (TagState: Help, describe-key). + if (p.view().tag_state.kind != .rest) return tagStateKey(p, key); if (p.view().window_pick != null) return layout.windowKey(p, key); const pane = p.panes[p.view().active] orelse return; layout.noteTyped(p); @@ -385,6 +392,9 @@ pub fn handleKey(p: *Pardes, key: Key) void { if (normal.selRegexArmed(pane)) |a| if (panes.promptTarget(p, pane)) |answered| normal.applySelRegex(p, pane, answered, a.pat, a.mode); return; } + if (header == null) if (TagState.current(p, p.view())) |cur| if (cur.root != .leader and cur.root != .window) { + if (prefixKey(p, t, cur.root, key)) return; + }; if (t == &pane.body and pane.jump.items.len > 0) return normal.jumpKey(p, pane, t, key); // A query pane's line 1 answers Enter, Esc and the stepping keys // itself (Query.zig). @@ -492,45 +502,222 @@ pub fn leaderTaken(keys: []const u8) bool { return keys.len > 0 and keys[0] == config.leader_help; } +/// A key in SPC's level: which-key's own (levelKey), else the child it +/// names. A group goes down a level; a leaf runs and remembers it ran +/// (TagState.used); a key the level has no child for is struck and the +/// level stays; any other key (Esc) leaves it. fn leaderKey(p: *Pardes, key: Key) void { const v = p.view(); - v.prefix = .none; // only "still a prefix" below re-arms it - if (key.ctrl or key.alt or key.cp < 0x20 or key.cp > 0x7e) return; - const c: u8 = @intCast(key.cp); - if (c == config.leader_help) { - panes.Output.openHelp(p, v.active, v.leader_keys[0..p.view().leader_n]) catch |err| - p.reportError(.at(v.active), "help", err); - return; + switch (levelKey(p, .leader, v.leader_keys[0..v.leader_n], key)) { + .taken => return, + .up => { + if (v.leader_n == 0) v.prefix = .none else v.leader_n -= 1; + v.tag_state.hi = 0; + v.tag_state.miss = 0; + }, + .take => |c| leaderTake(p, c), + .pass => { + if (key.ctrl or key.alt or key.cp < 0x20 or key.cp > 0x7e) { + v.prefix = .none; + return; + } + leaderTake(p, @intCast(key.cp)); + }, } - if (v.leader_n >= v.leader_keys.len) return; - v.leader_keys[v.leader_n] = c; - v.leader_n += 1; - const pfx = v.leader_keys[0..p.view().leader_n]; - // A path that runs a builtin with its argument (the query pane's - // sources with no word of their own). - for (config.leader_args) |la| if (std.mem.eql(u8, la.path, pfx)) return exec.runBuiltin(p, la.cmd, v.active, "", la.arg); - for (config.leader_args) |la| if (std.mem.startsWith(u8, la.path, pfx)) { +} + +fn leaderTake(p: *Pardes, c: u8) void { + const v = p.view(); + const s = &v.tag_state; + v.prefix = .none; // only "still a level" below re-arms it + // `SPC ?`: Help over every root's leaves; `?` down a level, Help for + // that level's (SPEC §4.5). + if (c == config.leader_help) return TagState.openHelp(p, if (v.leader_n == 0) null else .leader, v.leader_keys[0..v.leader_n]); + const path = v.leader_keys[0..v.leader_n]; + var children: [bindings.max_children]bindings.Child = undefined; + const child = for (bindings.level(p, .leader, path, &children)) |child| { + if (child.key == c) break child; + } else { v.prefix = .leader; + s.miss = c; + return; }; - // a path-less builtin is a row here too (it is the same index Help - // reads), and SPC cannot reach one — so both scans skip it; and a - // window's own word is no path in a terminal's view - for (builtin_rows) |row| { - if (!builtins.registry.here(p, row.cmd)) continue; - if (std.mem.eql(u8, row.path orelse continue, pfx)) return exec.runBuiltin(p, row.cmd, v.active, "", null); + s.miss = 0; + if (child.group) { + v.prefix = .leader; + if (v.leader_n == v.leader_keys.len) return; + v.leader_keys[v.leader_n] = c; + v.leader_n += 1; + s.hi = 0; + return; } - for (builtin_rows) |row| { - if (!builtins.registry.here(p, row.cmd)) continue; - if (std.mem.startsWith(u8, row.path orelse continue, pfx)) { + TagState.ran(v, .leader, path, c); + if (child.word) |w| return exec.runWord(p, v.active, w, w.name.slice(), ""); + switch (child.node.?.leaf.?) { + .builtin => |b| exec.runBuiltin(p, b, v.active, "", null), + .arg => |a| exec.runBuiltin(p, config.leader_args[a].cmd, v.active, "", config.leader_args[a].arg), + .role => unreachable, // SPC's leaves are words + } +} + +/// A key in a tag's typing state: Esc back to rest; Enter runs the row, +/// typed as its keys; the rows' cursor; the field; Backspace on an empty +/// field back to the level `?` was struck from. +fn tagStateKey(p: *Pardes, key: Key) void { + const v = p.view(); + const s = &v.tag_state; + if (TagState.hostOf(p) == null or hit(key, config.escape)) return TagState.toRest(p); + switch (s.kind) { + .rest => unreachable, + .describe => { + const plain = !key.ctrl and !key.alt; + if (plain and key.cp == Key.enter and s.found) { + var out: [16]Key = undefined; + var path: [8]u8 = undefined; + const n = s.scope_n; + @memcpy(path[0..n], s.scope[0..n]); + const typed = bindings.keysOf(s.scope_root.?, path[0..n], &out); + TagState.toRest(p); + for (typed) |k| handleKey(p, k); + return; + } + if (plain and key.cp == Key.backspace) { + if (s.scope_n > 0 and s.scope_root != null) { + s.scope_n -= 1; + } else s.scope_root = null; + if (s.scope_root == null) s.scope_n = 0; + s.found = false; + s.missed = false; + return; + } + TagState.describeKey(p, key); + }, + .pick => return @import("Pick.zig").key(p, key), + .help => { + const plain = !key.ctrl and !key.alt; + if (plain and key.cp == Key.enter) { + if (s.nhits == 0) return; + var buf: [TagState.row_max]u8 = undefined; + const leaf = TagState.helpLeaf(p, s.hits[s.rows.at], &buf); + var out: [16]Key = undefined; + const typed = bindings.keysOf(leaf.root, leaf.path, &out); + TagState.toRest(p); + for (typed) |k| handleKey(p, k); + return; + } + if (plain and key.cp == Key.backspace and s.field.len == 0) return helpBack(p); + if (s.rows.key(key, s.nhits)) return; + if (s.field.key(key)) TagState.filter(p); + }, + } +} + +/// Help left by Backspace on its empty field: the level it was struck +/// from, unrolled, as `?` found it; rest from `SPC ?`. +fn helpBack(p: *Pardes) void { + const v = p.view(); + const s = &v.tag_state; + const root = s.scope_root orelse .leader; + var path: [4]u8 = undefined; + const n = s.scope_n; + @memcpy(path[0..n], s.scope[0..n]); + TagState.toRest(p); + const pane = p.panes[v.active] orelse return; + switch (root) { + .leader => { v.prefix = .leader; - return; - } + @memcpy(v.leader_keys[0..n], path[0..n]); + v.leader_n = n; + }, + .goto, .match, .view, .view_sticky, .next, .prev => { + const t = if (pane.focus == .tag) &pane.tag else &pane.body; + t.normal.prefix = switch (root) { + .goto => .goto_prefix, + .match => .match_prefix, + .view, .view_sticky => .view_prefix, + .next => .next_prefix, + .prev => .prev_prefix, + else => unreachable, + }; + t.normal.sticky = root == .view_sticky; + }, + .window, .register => return, } - // An addon's word, after the core's (a path the core has is no addon's). - switch (p.kinds.leader(pfx)) { - .word => |w| exec.runWord(p, v.active, w, w.name.slice(), ""), - .prefix => v.prefix = .leader, - .none => {}, + s.root = root; + s.unrolled = true; +} + +/// What a key does to a which-key level before its root reads it: `up` a +/// level (Backspace, and Left or Alt-h unrolled), `take` a child (Enter: +/// the cursor's, or rolled the leaf the group ran last; Right or Alt-l +/// unrolled: the cursor's group), `taken` (Down unrolls, then moves the +/// cursor; Up moves it, and on the first row rolls up), or `pass`: the +/// root's own key. A key a root binds is its own (helix's z Down scrolls). +const LevelStep = union(enum) { pass, taken, up, take: u8 }; + +fn levelKey(p: *Pardes, root: bindings.Root, path: []const u8, key: Key) LevelStep { + const s = &p.view().tag_state; + var buf: [bindings.max_children]bindings.Child = undefined; + const children = bindings.level(p, root, path, &buf); + if (children.len == 0) return .pass; + const node = bindings.nodeAt(root, path); + const used = if (node) |n| s.used[n.group] else 0; + const plain = !key.ctrl and !key.alt; + const down = (plain and key.cp == Key.down) or (key.ctrl and !key.alt and key.cp == 'j'); + const up = (plain and key.cp == Key.up) or (key.ctrl and !key.alt and key.cp == 'k'); + const right = (plain and key.cp == Key.right) or (key.alt and !key.ctrl and key.cp == 'l'); + const left = (plain and key.cp == Key.left) or (key.alt and !key.ctrl and key.cp == 'h'); + if ((root == .view or root == .view_sticky) and plain and (key.cp == Key.down or key.cp == Key.up)) return .pass; + if (plain and key.cp == Key.backspace) return .up; + // The cursor: its child, else the leaf the group ran last, else the first. + var at: usize = 0; + for (children, 0..) |c, i| if (c.key == (if (s.hi != 0) s.hi else used)) { + at = i; + }; + if (down) { + if (!s.unrolled) { + s.unrolled = true; + } else at = (at + 1) % children.len; + s.hi = children[at].key; + return .taken; + } + if (up) { + if (s.unrolled and at == 0) s.unrolled = false else if (s.unrolled) s.hi = children[at - 1].key; + return .taken; + } + if (s.unrolled and right) return if (children[at].group) .{ .take = children[at].key } else .taken; + if (s.unrolled and left) return .up; + if (plain and key.cp == Key.enter) { + if (s.unrolled) return .{ .take = children[at].key }; + return if (used != 0) .{ .take = used } else .taken; + } + return .pass; +} + +/// A key while a helix prefix waits in text `t` (g m z Z [ ]): which-key's +/// own, else the prefix's, the leaf it runs remembered. True when taken here. +fn prefixKey(p: *Pardes, t: *Text, root: bindings.Root, key: Key) bool { + if (root != .register and key.cp == config.leader_help and !key.ctrl and !key.alt) { + TagState.openHelp(p, root, ""); + return true; + } + switch (levelKey(p, root, "", key)) { + .taken => return true, + .up => { + t.normal = .{}; + return true; + }, + .take => |c| { + handleKey(p, .{ .cp = c }); + return true; + }, + .pass => { + if (!key.ctrl and !key.alt and key.cp >= 0x20 and key.cp < 0x7f) { + const k: u8 = @intCast(key.cp); + if (bindings.nodeAt(root, &.{k}) != null) TagState.ran(p.view(), root, "", k); + } + return false; + }, } } diff --git a/core/layout.zig b/core/layout.zig index ff14a789..c12780d8 100644 --- a/core/layout.zig +++ b/core/layout.zig @@ -860,8 +860,46 @@ fn blankRows(p: *const Pardes, id: usize) u16 { } /// What a new pane is, and who asked: each rule places them differently. -/// `scratch` is New's, `fs` 9P's pane/new, `errors` a +Errors pane. -pub const NewPane = enum { scratch, fs, shell, doc, command, errors }; +/// `scratch` is New's, `fs` 9P's pane/new, `errors` a +Errors pane, +/// `reader` a held pane's reader (Trail.zig). +pub const NewPane = enum { scratch, fs, shell, doc, command, errors, reader }; + +/// The body rows a held pane keeps above its reader: with fewer, the +/// reader goes to the next column (pick-ui SPEC §6.1). +pub const reader_keeps = 8; + +/// A reader's place (pick-ui SPEC §6.1): under its held pane `from`, +/// taking half its rows, unless that leaves it fewer than `reader_keeps` +/// body rows; then at the bottom of the next column, the previous one +/// when `from`'s is the last, as New takes the bottom of a column. +fn readerPlace(p: *Pardes, from: usize, id: usize) void { + const v = p.view(); + const c = columnOf(p, from); + const r = v.rects[from]; + if (findPane(p, from) != null and r.h / 2 >= p.panes[from].?.tag_rows + reader_keeps) return splitAt(p, c, id, r.y + r.h / 2); + acmePlace(p, if (c + 1 < v.ncol) c + 1 else c -| 1, null, id); +} + +/// Pane `new` in pane `old`'s place in every view, with its rows: a +/// reader's step to another file (Trail.zig). `old` leaves no layout. +pub fn replacePane(p: *Pardes, old: usize, new: usize) void { + const was = p.panes[old].?; + const now = p.panes[new].?; + now.vweight = was.vweight; + now.collapsed = was.collapsed; + for (0..pardes.views.max) |k| if (now.pv_known & was.pv_known & (@as(u8, 1) << @intCast(k)) != 0) { + now.pv[k].vweight = was.pv[k].vweight; + now.pv[k].collapsed = was.pv[k].collapsed; + }; + for (&p.views) |*slot| { + const v = &(slot.* orelse continue); + for (v.cols[0..v.ncol]) |*col| for (col.panes[0..col.n]) |*k| if (k.* == old) { + k.* = new; + }; + v.rects[new] = v.rects[old]; + if (v.active == old) v.active = new; + } +} /// Put new pane `id` in the layout: every new pane comes through here, as /// acme's makenewwindow places it, and every one but a command pane takes @@ -888,6 +926,7 @@ pub fn placeNew(p: *Pardes, from: usize, origin: ?usize, id: usize, kind: NewPan // makenewwindow(nil) for 9P's new (acme.c:877), else (t). .fs => acmePlace(p, acmeColumn(p, from), null, id), .shell, .doc => acmePlace(p, acmeColumn(p, from), asked, id), + .reader => readerPlace(p, from, id), } // No pane is made shorter than its tag and two rows: where the place // chosen has not the room, the column's tallest pane gives it, and @@ -1431,9 +1470,14 @@ pub fn compute(p: *Pardes) void { /// The fewest rows a pane is laid out with: a terminal keeps its tag and /// `min_body_rows` (a shorter one loses its prompt and reads busy for -/// ever), a text pane may shrink to its tag, as acme's windows do. +/// ever), a text pane may shrink to its tag, as acme's windows do. A tag +/// out of rest keeps its band and four body rows, borrowed from the +/// column's other panes, which shrink to their tags until it rolls up +/// (walk UI SPEC §3.6). fn floorRows(p: *Pardes, id: usize) u16 { const pane = p.panes[id] orelse return 0; + const band = pardes.Band.takes(p, id); + if (band > 0) return @max(1, pane.tag_rows -| pane.band_rows) + band + 4; return if (pane.isTerminal()) @max(1, pane.tag_rows) + min_body_rows else 1; } @@ -1640,7 +1684,7 @@ pub fn tagCapacity(p: *const Pardes, physical_width: u16) u16 { /// A frontend's tag hit, if what it names is still there: resolved on /// the place it carries (Layer.Place), not on this process's frame. pub fn reprojectTagHit(p: *const Pardes, tag_hit: TagHit) ?TagHit { - if (tag_hit.kind == .pane) { + if (tag_hit.kind == .pane or tag_hit.kind == .band) { if (tag_hit.id >= p.panes.len) return null; const pane = p.panes[tag_hit.id] orelse return null; if (pane.serial != tag_hit.serial) return null; diff --git a/core/look.zig b/core/look.zig index 8356dca8..b8d70fc2 100644 --- a/core/look.zig +++ b/core/look.zig @@ -20,6 +20,7 @@ const Color = @import("surface.zig").Color; const Pane = panes.Pane; const MAX_PANES = pardes.MAX_PANES; const Layer = @import("Layer.zig"); +const Trail = @import("Trail.zig"); const TagHit = pardes.TagHit; const BOX_H = pardes.BOX_H; const TAG_TEXT_INSET = pardes.TAG_TEXT_INSET; @@ -1164,14 +1165,14 @@ fn lookAddress(p: *Pardes, id: usize, path: []const u8, expr: []const u8) void { // own clean start would collapse its dot (and the looker's) before the // address ever read it, so `f:/re/` again would find the same match. var realbuf: [4096]u8 = undefined; - const open: ?usize = if (path.len == 0) null else switch (resolveLookTarget(p, id, path, &realbuf)) { + const there: ?usize = if (path.len == 0) null else switch (resolveLookTarget(p, id, path, &realbuf)) { .pane => |t| if (t.id < MAX_PANES and p.panes[t.id] != null) t.id else null, else => null, }; // `@p<serial>:<address>`: that pane, or, not open, a miss said as one. const by_serial = std.mem.startsWith(u8, path, config.pane_addr); - if (by_serial and open == null) return missed(p, id, "no pane {s}", .{path[0..@min(path.len, 32)]}); - if (open) |o| target = o else if (path.len > 0) { + if (by_serial and there == null) return missed(p, id, "no pane {s}", .{path[0..@min(path.len, 32)]}); + if (there) |o| target = o else if (path.len > 0) { // A path that names nothing to open: the whole of what was written // is looked for, as `zzq:2` is, and a miss quotes it as written. if (!by_serial and resolveLookTarget(p, id, path, &realbuf) == .none) @@ -1189,7 +1190,7 @@ fn lookAddress(p: *Pardes, id: usize, path: []const u8, expr: []const u8) void { } const pane = p.panes[target] orelse return; const f = pane.file orelse { - if (pane.addon != null) return lookKind(p, id, target, expr, open == null and target != id); + if (pane.addon != null) return lookKind(p, id, target, expr, there == null and target != id); if ((by_serial or path.len == 0) and pane.isTerminal()) return lookTerminalAddress(p, id, target, expr); // Named as the pane is, the bare `:addr` (path empty) included. var serial_name: [32]u8 = undefined; @@ -1206,7 +1207,7 @@ fn lookAddress(p: *Pardes, id: usize, path: []const u8, expr: []const u8) void { const name = missText(f.path, &cut); // A look whose address fails opens nothing: a pane it opened to read // the address in goes again, the miss said from the pane it came from. - const opened_here = open == null and target != id; + const opened_here = there == null and target != id; const r = a.address(ninep_pane.fileDot(pane)) orelse { // A line past the end says so as `file:N` does, whichever way it // was written: `<file>:N has no line N`. @@ -1497,6 +1498,90 @@ fn settleLine(p: *Pardes, id: usize, path: []const u8, at: Spot, before: usize, } } +/// Where a jump lands: in the pane it walks (`replace`), or always in a +/// new pane under the asking one (`below`, as `Jumps new-pane` opens one). +pub const How = enum { replace, below }; + +/// What a jump did: nothing (refused, said), showed it in a pane there +/// was, or opened a pane for it, which a miss of its line closes again. +pub const Landed = union(enum) { none, shown, opened: usize }; + +/// A jump from pane `from` to `path` at `at`, the keyboard with it: a +/// Look at a place, a definition, an error's place, a list's row (pick-ui +/// SPEC §6.1). With `Jumps walk`: a held pane showing the file is focused +/// and nothing replaced; the asking pane showing it moves in it (a step +/// when it is reading); a reading pane steps in place, a held one steps +/// its reader (Trail.zig), made under it on its first jump. With +/// `Jumps new-pane` as before the walk: a pane showing the file focused, +/// else a new one. +pub fn open(p: *Pardes, from: usize, path: []const u8, at: Spot, how: How) Landed { + if (how == .replace and p.settings.jumps == .walk and path.len <= Trail.max_text and p.panes[from] != null) return walk(p, from, path, at); + if (how == .replace and focusPaneByPath(p, path, at)) return .shown; + return if (openNew(p, from, path, at, .doc)) |free| .{ .opened = free } else .none; +} + +fn walk(p: *Pardes, from: usize, path: []const u8, at: Spot) Landed { + const src = p.panes[from].?; + for (p.panes, 0..) |slot, k| { + const held = slot orelse continue; + if (k == from or !Trail.isFile(held) or Trail.reading(p, held) or !std.mem.eql(u8, held.file.?.path, path)) continue; + clearNavigationSelection(p, held); + focusPaneLine(p, k, at, .center); + return .shown; + } + const reads = Trail.reading(p, src); + if (!reads and if (src.file) |f| std.mem.eql(u8, f.path, path) else false) { + clearNavigationSelection(p, src); + focusPaneLine(p, from, at, .center); + return .shown; + } + const into = if (reads) from else Trail.readerOf(p, src) orelse { + const free = openNew(p, from, path, at, .reader) orelse return .none; + p.panes[free].?.trail = Trail.reader(src.serial, path, at); + return .{ .opened = free }; + }; + _ = Trail.step(p, into, path, at) catch |err| { + switch (err) { + error.LineMissing => missedLine(p, from, path, at.line), + error.NoPaneSlots => p.reportError(.at(from), "look", err), + else => lookOpenFailed(p, from, path, err), + } + return .none; + }; + return .shown; +} + +/// `path` opened at `at` in a new pane placed as `kind` places one from +/// `from`, its line half its body's rows down; null when it is not +/// (refused, said). +fn openNew(p: *Pardes, from: usize, path: []const u8, at: Spot, kind: layout.NewPane) ?usize { + const v = p.view(); + const free = p.freeSlot() orelse { + p.reportError(.at(from), "look", error.NoPaneSlots); + return null; + }; + const nt = panes.File.open(p, free, path, at.line) catch |err| { + lookOpenFailed(p, from, path, err); + return null; + }; + nt.body.cur_col = columnOn(nt, nt.body.cur_row, at.col); + const failures = p.fs.failures; + layout.placeNew(p, from, from, free, kind); + // Refused a place: that is the look's one failure, not a miss of its + // line too. + if (p.fs.failures != failures) return null; + layout.compute(p); + // Its line half the body's rows down, a wrapped line's rows above it + // counted. + const centered = panes.File.walkRows(p.settings.tab, nt, .{ .line = nt.file.?.scroll }, -@as(i64, @max(1, v.rects[free].h -| BOX_H) / 2)).to; + panes.File.setTop(nt, centered); + if (at.end_line != 0) { + selectSpan(p, nt, at); + panes.File.setTop(nt, centered); + } + return free; +} + fn focusPaneByPath(p: *Pardes, path: []const u8, at: Spot) bool { const target = openPaneTarget(p, path, at) orelse return false; clearNavigationSelection(p, p.panes[target.pane.id].?); @@ -1654,6 +1739,16 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { // A directory's pane, looked at again: read again. if (target.file) |f| if (f.listing != null) return panes.Dir.show(p, id, t.id); const before = v.active; + // A file's pane found by its path, not named `@pN`: a jump to + // the file, which walks (open). + if (p.settings.jumps == .walk and Trail.isFile(target) and !std.mem.startsWith(u8, pl.path, config.pane_addr)) { + switch (open(p, id, target.file.?.path, t.at, .replace)) { + .none => {}, + .shown => settleLine(p, id, trimmed, t.at, before, null), + .opened => |free| settleLine(p, id, trimmed, t.at, before, free), + } + return; + } clearNavigationSelection(p, target); focusPaneLine(p, t.id, t.at, .center); settleLine(p, id, trimmed, t.at, before, null); @@ -1673,34 +1768,15 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { .file => |target| { // An open pane on this path too short for the line: a miss that // touches nothing. - if (openPaneTarget(p, target.path, target.at)) |open| if (p.panes[open.pane.id].?.file) |*f| + if (openPaneTarget(p, target.path, target.at)) |there| if (p.panes[there.pane.id].?.file) |*f| if (target.at.line > panes.File.nlines(p.gpa, f)) return missedLine(p, id, target.path, target.at.line); - // focus an existing pane on this path (rescrolled), else open const before = v.active; - var opened: ?usize = null; - if (!focusPaneByPath(p, target.path, target.at)) { - const free = p.freeSlot() orelse return p.reportError(.at(id), "look", error.NoPaneSlots); - const nt = panes.File.open(p, free, target.path, target.at.line) catch |err| - return lookOpenFailed(p, id, target.path, err); - nt.body.cur_col = columnOn(nt, nt.body.cur_row, target.at.col); - const failures = p.fs.failures; - layout.placeNew(p, id, id, free, .doc); - // Refused a place: that is the look's one failure, not a - // miss of its line too. - if (p.fs.failures != failures) return; - layout.compute(p); - // Its line half the body's rows down, a wrapped line's - // rows above it counted. - const centered = panes.File.walkRows(p.settings.tab, nt, .{ .line = nt.file.?.scroll }, -@as(i64, @max(1, v.rects[free].h -| BOX_H) / 2)).to; - panes.File.setTop(nt, centered); - if (target.at.end_line != 0) { - selectSpan(p, nt, target.at); - panes.File.setTop(nt, centered); - } - opened = free; + switch (open(p, id, target.path, target.at, .replace)) { + .none => {}, + .shown => settleLine(p, id, target.path, target.at, before, null), + .opened => |free| settleLine(p, id, target.path, target.at, before, free), } - settleLine(p, id, target.path, target.at, before, opened); }, .kind => |target| { var place: [41]u8 = undefined; diff --git a/core/lsp/Ask.zig b/core/lsp/Ask.zig index 62248304..2b599c76 100644 --- a/core/lsp/Ask.zig +++ b/core/lsp/Ask.zig @@ -366,6 +366,12 @@ pub fn lspResponse(p: *Pardes, id: u32, response: ?[]const u8) void { return; } + // Symbols and diagnostics asked from the keyboard, where jumps walk: a + // picker in the tag of the pane its Enter lands in (Pick.zig). + if (pardes.Pick.asked(p)) switch (w.kind) { + .document_symbols, .workspace_symbols, .diagnostics, .workspace_diagnostics => return pardes.Pick.open(p, asked, .list, lspWord(w.kind), "", rows), + else => {}, + }; // The lists of places: into the asking text's query pane (made or // reused), line 1 their word, the places in that text its places. const listed: ?panes.Query.Source = switch (w.kind) { diff --git a/core/mouse.zig b/core/mouse.zig index aab8a752..b6e99300 100644 --- a/core/mouse.zig +++ b/core/mouse.zig @@ -706,6 +706,7 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void { if (m.kind == .press) { tagline.exitHeader(p); } + if (m.kind == .press) if (bandPoint(p, mcol, mrow)) |point| return bandPress(p, m.button, point); switch (m.button) { .none, .back, .forward => {}, // hover and navigation handled above @@ -886,6 +887,55 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void { } } +const BandPoint = struct { id: usize, line: u16, col: u16 }; + +/// The band row and column (at the tagline's pitch) a press is on: a +/// window's layer hit, or a terminal's grid cell under a tag's text rows. +fn bandPoint(p: *Pardes, mcol: u16, mrow: u16) ?BandPoint { + const v = p.view(); + if (v.pointer_tag_hit) |hit| return if (hit.kind == .band) .{ .id = hit.id, .line = hit.line, .col = hit.col } else null; + const id = paneAt(p, mcol, mrow) orelse return null; + const pane = p.panes[id].?; + if (pane.band_rows == 0) return null; + const r = v.rects[id]; + const top = p.tagTop(pane, r) + (pane.tag_rows - pane.band_rows); + if (mrow < top or mrow >= top + pane.band_rows or mcol < r.x + TAG_TEXT_INSET) return null; + return .{ .id = id, .line = mrow - top, .col = mcol - (r.x + TAG_TEXT_INSET) }; +} + +/// A press on a band (Band.zig), read-only text: the select button puts +/// the rows' cursor on the row it is on; execute runs the word under it +/// and look looks at it, as on a tag, the tag back at rest first. +fn bandPress(p: *Pardes, button: Mouse.Button, point: BandPoint) void { + const v = p.view(); + const arena = p.scratch.allocator(); + if (button == config.select_button) { + const band = (pardes.Band.of(p, arena, p.panes[point.id].?, point.id) catch return) orelse return; + const ln = band.line(arena, p.settings.tab, point.line) catch return; + for (ln.parts) |part| if (point.col >= part.col -| 2 and point.col < part.col + part.width) { + pardes.TagState.point(p, part.row.index); + }; + return; + } + if (button != config.exec_button and button != config.look_button) return; + const word = (pardes.Band.wordAt(p, arena, point.id, point.line, point.col) catch return) orelse return; + const kept = arena.dupe(u8, word) catch return; + // A picker's band: B2 runs the word with the picker live (an act's word + // acts, Pick.execWord); B3 on a row lands on it. + if (v.tag_state.kind == .pick) { + if (button == config.exec_button) return exec.runBuiltin(p, config.exec_cmd, v.active, "", kept); + const band = (pardes.Band.of(p, arena, p.panes[point.id].?, point.id) catch return) orelse return; + const ln = band.line(arena, p.settings.tab, point.line) catch return; + for (ln.parts) |part| if (point.col >= part.col and point.col < part.col + part.width) { + pardes.TagState.point(p, part.row.index); + return pardes.Pick.landHere(p); + }; + return; + } + pardes.TagState.toRest(p); + exec.runBuiltin(p, if (button == config.exec_button) config.exec_cmd else config.look_cmd, v.active, "", kept); +} + /// Index of the pane pair in column `c` whose seam (see seamRowOf) is screen /// row `mrow`. Out-of-range columns simply have no seam. fn seamIdxAt(p: *const Pardes, c: usize, mrow: u16) ?usize { @@ -1226,8 +1276,12 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { // click on the path, if it can be renamed, drafts a name. const row: usize = @intCast(@max(0, sl.r1)); const col: usize = @intCast(@max(0, sl.c1)); - if (!dragged and tagline.onName(p.settings.tab, pane, row, col)) { - tagline.draftName(p, pane, col); + // A plain click on a word of its walk is its Look + // (pick-ui SPEC §6.3): the one place B1 does more than + // select. + if (!dragged and tagline.trailClick(p, s.id, row, col, false)) return; + if (if (dragged) null else tagline.onName(p.settings.tab, pane, row, col)) |at| { + tagline.draftName(p, pane, at); } else if (tagline.tagOffsetAt(p, pane, row, col)) |cursor| { pane.tag.cur_row = @intCast(cursor.row); pane.tag.cur_col = @intCast(cursor.col); @@ -1293,6 +1347,14 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { return; } }; + // On a word of the tag's walk: that step's Look or Exec + // (Trail.zig), not the word's. + if (clk.r0 >= 0 and clk.r0 < pane.tag_rows and clk.r0 == clk.r1 and clk.c0 == clk.c1 and clk.c0 >= 0 and + tagline.trailClick(p, s.id, @intCast(clk.r0), @intCast(clk.c0), s.button == config.exec_button)) + { + pane.sel[b].state = .none; + return; + } var operand = exec.operandAt(p, pane, clk, true, s.button == config.look_button); if (operand.expanded) |expanded| pane.sel[b] = expanded diff --git a/core/normal.zig b/core/normal.zig index 3dade7a6..981a3f3b 100644 --- a/core/normal.zig +++ b/core/normal.zig @@ -1392,6 +1392,8 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error! return look.lookWalk(p, if (a.role == .search_next) 1 else -1, false) else if (t.what == .body and pane.file != null and pane.places.answersN(p, pane)) return pane.places.step(p, pane, a.role == .search_next, a.count, t.select) + else if (t.what == .body and panes.Pick.walkList(p, v.active, a.role == .search_next)) + return else return searchStep(p.editor(), t, text, a.role == .search_next, a.count), .goto_word => return startJump(p, pane, t), diff --git a/core/panes.zig b/core/panes.zig index 479d4702..47765d90 100644 --- a/core/panes.zig +++ b/core/panes.zig @@ -15,6 +15,7 @@ const dump = @import("dump.zig"); const memory = @import("memory.zig"); const ctlfs = @import("ninep/tree.zig"); const Pipe = @import("Pipe.zig"); +const Trail = @import("Trail.zig"); const Key = pardes.Key; const Cell = pardes.Cell; const BOX_H = pardes.BOX_H; @@ -31,7 +32,7 @@ pub const Pane = struct { /// it (views.zig). (The 9P server's part of `fs` says so in its type.) pub const replica = .{ .local = .{ "pv", "pv_known" }, - .derived = .{ "wrap_line", "wrap_col", "wrap_pad", "wrap_n", "body_wrapped", "context_rows", "body_rows", "body_visible_rows", "context_row_limit", "geometry_key", "geometry_len", "top_skip", "notices", "pan" }, + .derived = .{ "band_rows", "wrap_line", "wrap_col", "wrap_pad", "wrap_n", "body_wrapped", "context_rows", "body_rows", "body_visible_rows", "context_row_limit", "geometry_key", "geometry_len", "top_skip", "notices", "pan" }, .len = .{ .{ "question", "question_len" }, .{ "shell_tail", "shell_tail_len" }, .{ "sel_snap", "nsel_snap" } }, // A picture's memory is its own allocator's (a dump loaded makes // it there). @@ -267,6 +268,9 @@ pub const Pane = struct { /// the current one selected (Places.zig). places: Places = .{}, look_at: ?LookSpot = null, + /// Its walk: the places it stepped through, its owner when it is a + /// reader, whether it is held (Trail.zig, pick-ui SPEC §6). + trail: Trail = .{}, /// `gw`'s words, labelled in order while it waits for a label to be /// typed (gpa-owned); `jump_first` is the label's first letter once typed. jump: std.ArrayList(modal.Selection) = .empty, @@ -286,7 +290,9 @@ pub const Pane = struct { /// Rows the tag takes on screen: one per line of it, as many as the pane /// has room for with a body row to spare. Set with the geometry in sync. /// Pointer rows count from the tag's first, so a body starts at this one. + /// Its last `band_rows` are the band unrolled under its text (Band.zig). tag_rows: u16 = 1, + band_rows: u16 = 0, /// The tag's first line on screen. A tag with more lines than rows /// scrolls to keep its caret in view while it has the keyboard; pointer /// rows count from this line, not the tag's first. @@ -1072,6 +1078,7 @@ pub const Places = @import("Places.zig"); pub const Tables = @import("Tables.zig"); pub const Query = @import("Query.zig"); +pub const Pick = @import("Pick.zig"); pub const Dir = @import("Dir.zig"); @@ -1444,6 +1451,9 @@ pub fn removePane(p: *Pardes, id: usize, to: ?usize) error{OutOfMemory}!void { try p.removePane(k, id); layout.compute(p); }; + // A held pane's reader is its tether: it closes with it (pick-ui + // SPEC §11), its rows going where a closed pane's go. + if (Trail.readerOf(p, pane)) |r| try p.removePane(r, null); // A docked pane's rows go back to its owner and nobody else. const owner = layout.ownerOf(p, id); const place = layout.findPane(p, id); diff --git a/core/root.zig b/core/root.zig index 5c49a038..61c236ae 100644 --- a/core/root.zig +++ b/core/root.zig @@ -89,6 +89,10 @@ pub const Kind = @import("Kind.zig"); /// The terminal, as the core calls it (core/term/ behind it). pub const Term = @import("Term.zig"); pub const keys = @import("keys.zig"); +pub const bindings = @import("bindings.zig"); +pub const TagState = @import("TagState.zig"); +pub const Band = @import("Band.zig"); +pub const Pick = @import("Pick.zig"); pub const Addon = @import("Addon.zig"); pub const dump = @import("dump.zig"); pub const lsp = @import("lsp/lsp.zig"); @@ -114,6 +118,7 @@ pub const font_picker = platform == .gui or platform == .macos; pub var turn: Turn = .{}; pub const Turn = @import("Turn.zig"); pub const Jump = @import("Jump.zig"); +pub const Trail = @import("Trail.zig"); const Loc = Jump.Loc; pub const can_attach = platform == .tui or platform == .gui; @@ -138,11 +143,15 @@ pub const TagKind = Layer.Kind; /// too long for its width. pub const MAX_TAG_ROWS = 8; /// Panes, then columns, then the workspace bar, then each pane's notice -/// bands: a band to a tag, however many lines it has. -pub const MAX_TAG_LAYERS = MAX_PANES + MAX_COLS + 2 + MAX_PANES * Pane.Notices.max; +/// bands: a band to a tag, however many lines it has; then the rows +/// unrolled under the one tag out of rest (Band.zig: a view has one, the +/// keyboard's, SPEC §3.4). A frame makes many a temporary Surface, each +/// with every layer: a layer to a pane here cost every frame 0.9%. +pub const MAX_TAG_LAYERS = BAND_LAYER + 1; /// The notice row's layer, after the workspace tag's. pub const NOTICE_ROW_LAYER = MAX_PANES + MAX_COLS + 1; pub const NOTICE_LAYER_BASE = MAX_PANES + MAX_COLS + 2; +pub const BAND_LAYER = NOTICE_LAYER_BASE + MAX_PANES * Pane.Notices.max; /// Columns a session holds (each costs about 8 KB of state, a column tag /// being most of it). pub const MAX_COLS = 16; @@ -405,7 +414,13 @@ test { _ = @import("Plumb.zig"); _ = @import("lsp/Ask.zig"); _ = @import("Jump.zig"); + _ = @import("Trail.zig"); _ = @import("keys.zig"); + _ = @import("bindings.zig"); + _ = @import("TagState.zig"); + _ = @import("Band.zig"); + _ = @import("Pick.zig"); + _ = @import("Field.zig"); _ = @import("Effect.zig"); _ = @import("tape.zig"); _ = @import("replica.zig"); @@ -757,6 +772,7 @@ const kept_out = [_]struct { []const u8, []const u8, []const u8 }{ .{ "panes.zig", "pv pv_known", "the views' shares as this process parks them (views.zig)" }, .{ "panes.zig", "wrap_line wrap_col wrap_pad wrap_n body_wrapped context_rows body_rows body_visible_rows context_row_limit geometry_key geometry_len top_skip", "File.geometry's, made by whoever asks first (a frame or a step) from everything its key hashes of the step's state (the tab's width too); top_skip, keyed by the geometry it is of, read only through File.topSkip, which walks one of another key again" }, .{ "panes.zig views.zig", "notices", "made again from the step's state at the top of update and presented, and at sync (Messages.collectNotices); a frame's are its own" }, + .{ "panes.zig views.zig", "band_rows", "the band's rows under a tag (Band.takes), made again from the view's tag state at every sync before anything reads them (layout.floorRows reads the last sync's, as it reads tag_rows)" }, .{ "panes.zig views.zig", "pan", "written by steps only (sync, a view unparked) from the pane and its terminal" }, .{ "File.zig", "cap line_starts line_cap widest", "the text's line index, of its bytes, and the widest line it found (an upper bound: which walk answers, never what)" }, .{ "File.zig", "highlights highlight_start syntax_dirty", "how a text looks, painted by frames: read by frames, and by a query's rows for colours only (out of their digest; what a step asks a worker to paint is never decided by them, Stream.paintRows)" }, diff --git a/core/tagline.zig b/core/tagline.zig index a389bb6d..9e9b9757 100644 --- a/core/tagline.zig +++ b/core/tagline.zig @@ -11,6 +11,7 @@ const exec = @import("exec.zig"); const config = @import("config.zig"); const Layer = @import("Layer.zig"); const layout = @import("layout.zig"); +const TagState = @import("TagState.zig"); const Pane = panes.Pane; const Text = panes.Text; const TAG_TEXT_INSET = pardes.TAG_TEXT_INSET; @@ -153,8 +154,23 @@ pub fn pathPrefix(p: *const Pardes, arena: std.mem.Allocator, pane: *Pane) ![]co // 3/27` (Query.zig): its owner is right above it. if (pane.query) |q| if (pane.file) |f| if (pane.prompt != .name) return panes.Query.tagPrefix(q, arena, f.path); // Unsaved text shows on the grip, as acme's modbutton does, not as a - // mark in the text: the prefix is the name alone. - if (pane.file) |f| return if (pane.prompt == .name) pane.input.own orelse f.path else f.path; + // mark in the text: the prefix is the name alone, and Keep after it + // while a jump would step it (Trail.zig). + if (pane.file) |f| { + const name = if (pane.prompt == .name) pane.input.own orelse f.path else f.path; + const keep = pardes.Trail.reading(p, pane); + if (pane.trail.n == 0 and !keep) return name; + // Its walk's back steps before the name, its forward steps after + // it (Trail.zig), in the room `bytes` measures them. + const keep_word = if (keep) " Keep" else ""; + const room = try arena.alloc(u8, pane.trail.bytes(.back) + name.len + pane.trail.bytes(.forward) + keep_word.len); + var w: std.Io.Writer = .fixed(room); + pane.trail.write(.back, &w) catch return error.OutOfMemory; + w.writeAll(name) catch return error.OutOfMemory; + pane.trail.write(.forward, &w) catch return error.OutOfMemory; + w.writeAll(keep_word) catch return error.OutOfMemory; + return w.buffered(); + } // A terminal showing kitty graphics says how it draws them, as an image // pane does, and so does one drawing them as glyph art by choice. if (pane.terminal != null) { @@ -166,6 +182,38 @@ pub fn pathPrefix(p: *const Pardes, arena: std.mem.Allocator, pane: *Pane) ![]co return (try shownDir(arena, pane)); } +/// Where a file's name starts in its tag: after its walk's back steps. +pub fn nameAt(pane: *const Pane) usize { + return if (pane.file != null and pane.trail.n > 0) pane.trail.bytes(.back) else 0; +} + +/// The bytes of a file's tag its walk's forward steps take, after its name. +pub fn forwardSpan(pane: *const Pane) [2]usize { + const f = pane.file orelse return .{ 0, 0 }; + if (pane.trail.n == 0) return .{ 0, 0 }; + const name = if (pane.prompt == .name) pane.input.own orelse f.path else f.path; + const lo = pane.trail.bytes(.back) + name.len; + return .{ lo, lo + pane.trail.bytes(.forward) }; +} + +/// A click at shown row `row`, display column `col` of pane `id`'s tag on +/// a word of its walk: that step's Look, or with `run` its Exec +/// (Trail.zig, pick-ui SPEC §6.3). True when it was on one. +pub fn trailClick(p: *Pardes, id: usize, row: usize, col: usize, run: bool) bool { + const pane = p.panes[id] orelse return false; + if (pane.trail.n == 0 or pane.file == null) return false; + const at = tagOffsetAt(p, pane, row, col) orelse return false; + if (at.row != 0) return false; + const lead = nameAt(pane); + const ahead = forwardSpan(pane); + const step = if (at.col < lead) + pane.trail.stepAt(.back, at.col) + else if (at.col >= ahead[0] and at.col < ahead[1]) pane.trail.stepAt(.forward, at.col - ahead[0]) else null; + const i = step orelse return false; + if (run) pardes.Trail.execStep(p, id, i) else pardes.Trail.lookStep(p, id, i); + return true; +} + pub fn tagPrefix(p: *Pardes, pane: *Pane) ![]u8 { return prefixIn(p, p.scratch.allocator(), pane); } @@ -215,10 +263,19 @@ pub fn defaultTail(pane: *const Pane) []const u8 { return pane_tail; } +/// What the tag shows after its prefix: its own text, or while the pane +/// is out of rest in this view the head (TagState.head: the keys, the +/// level, the field), computed and read-only, the own text untouched under +/// it and back at rest (walk UI R1). +pub fn shownTail(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) ![]const u8 { + if (try TagState.head(p, arena, pane)) |h| return h.text; + return curTail(pane); +} + /// The tag as it is shown, read and pointed at: its computed prefix and -/// its own text after it. +/// what follows it (shownTail). pub fn tagText(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) ![]u8 { - return std.mem.concat(arena, u8, &.{ try tagPrefix(p, pane), curTail(pane) }); + return std.mem.concat(arena, u8, &.{ try tagPrefix(p, pane), try shownTail(p, arena, pane) }); } /// Give the keyboard to the tag in normal mode (`:`), its cursor where @@ -347,14 +404,20 @@ pub fn tagOffsetAt(p: *Pardes, pane: *Pane, row: usize, col: usize) ?modal.Curso return modal.positionAt(whole, @min(shown.toReal(off), whole.len)); } -/// Whether display column `col` of the tag's shown row `row` is on a name -/// a click drafts: a saving file's path. -pub fn onName(tab: u16, pane: *Pane, row: usize, col: usize) bool { - if (row + pane.tag_top != 0) return false; - const f = pane.file orelse return false; - if (!panes.Output.fileTraits(f.output).saves) return false; +/// The display column in the name a click drafts at display column `col` +/// of the tag's shown row `row`: on a saving file's path, after its walk's +/// words; null off it. +pub fn onName(tab: u16, pane: *Pane, row: usize, col: usize) ?usize { + if (row + pane.tag_top != 0) return null; + const f = pane.file orelse return null; + if (!panes.Output.fileTraits(f.output).saves) return null; const name = if (pane.prompt == .name) pane.input.own orelse f.path else f.path; - return col < panes.File.displayWidth(tab, name); + var room: [pardes.Trail.max_steps * (pardes.Trail.max_text + 32)]u8 = undefined; + var w: std.Io.Writer = .fixed(&room); + pane.trail.write(.back, &w) catch return null; + const lead = panes.File.displayWidth(tab, w.buffered()); + if (col < lead or col >= lead + panes.File.displayWidth(tab, name)) return null; + return col - lead; } /// A key typed into a saving file's path, with the tag's cursor there, @@ -364,7 +427,10 @@ pub fn onName(tab: u16, pane: *Pane, row: usize, col: usize) bool { pub fn typedIntoName(p: *Pardes, pane: *Pane, key: pardes.Key) bool { const f = pane.file orelse return false; if (!panes.Output.fileTraits(f.output).saves or pane.tag.cur_row != 0) return false; - const at: usize = @intCast(@max(0, pane.tag.cur_col)); + // The name starts after its walk's words. + const col: usize = @intCast(@max(0, pane.tag.cur_col)); + if (col < nameAt(pane)) return false; + const at = col - nameAt(pane); const back = key.cp == pardes.Key.backspace or pardes.hit(key, config.insert_backspace_alias); const forward = key.cp == pardes.Key.delete or pardes.hit(key, config.insert_delete_alias); const typed = key.text.len > 0 and !key.ctrl and !key.alt; diff --git a/core/themes/acme.zig b/core/themes/acme.zig index 4e4e9a43..34d99805 100644 --- a/core/themes/acme.zig +++ b/core/themes/acme.zig @@ -49,6 +49,8 @@ pub const theme = .{ .box_dirty = .{ 0x00, 0x00, 0x99 }, .rail_px = 12, .tag_sel_bg = .{ 0x9e, 0xee, 0xee }, + // A reading pane's tag: the page's yellow, a shade down (pick-ui's). + .tag_reading_bg = .{ 0xf3, 0xf0, 0xcc }, .sweep_bg = .{ .{ 0xee, 0xee, 0x9e }, .{ 0xaa, 0x00, 0x00 }, .{ 0x00, 0x66, 0x00 } }, .sweep_fg = .{ .{ 0x00, 0x00, 0x00 }, .{ 0xff, 0xff, 0xff }, .{ 0xff, 0xff, 0xff } }, .column_box = .{ 0x88, 0x88, 0xcc }, diff --git a/core/views.zig b/core/views.zig index e5f2038e..b05a116b 100644 --- a/core/views.zig +++ b/core/views.zig @@ -41,7 +41,7 @@ pub const away_kept_ns: u64 = 30 * std.time.ns_per_s; /// layout, which of its texts has the keyboard, how far it is scrolled (a /// terminal's history too), and what the view's step measured of it (its /// tag's rows, its bands). -const pane_fields = [_][:0]const u8{ "focus", "vweight", "collapsed", "docked_to", "hscroll", "tag_scroll", "tag_top", "tag_rows", "view", "layers", "notices", "pan", "follow_scroll", "scrolled_to" }; +const pane_fields = [_][:0]const u8{ "focus", "vweight", "collapsed", "docked_to", "hscroll", "tag_scroll", "tag_top", "tag_rows", "band_rows", "view", "layers", "notices", "pan", "follow_scroll", "scrolled_to" }; /// The body's: its cursor, selections and mode. Its undo stays the pane's. const body_fields = [_][:0]const u8{ "mode", "cur_pinned", "cur_row", "cur_col", "vsel", "sels", "nsel", "select", "sticky_col", "restore_cursor", "last_edit", "reg_wait", "normal", "find_op", "find_ch" }; @@ -56,6 +56,7 @@ pub const PaneView = struct { tag_scroll: u16 = 0, tag_top: u16 = 0, tag_rows: u16 = 1, + band_rows: u16 = 0, view: Pane.SessionView = .{}, layers: File.Layers = .{}, notices: Pane.Notices = .{}, @@ -73,7 +74,7 @@ pub const PaneView = struct { /// In a dump (`Shares`): what a pane's step works out again. Its `view` /// is dumped: the step after `unpark` reads it before it syncs. - pub const replica = .{ .derived = .{ "notices", "pan" } }; + pub const replica = .{ .derived = .{ "notices", "pan", "band_rows" } }; }; /// The panes' shares of a view not live, as a session's dump keeps them diff --git a/core/walk.zig b/core/walk.zig index 7a77fdb6..6734c0b7 100644 --- a/core/walk.zig +++ b/core/walk.zig @@ -2742,6 +2742,12 @@ pub const Get = struct { l.made.items[at].dead = true; return err; }; + // A damaged count past the elements the list holds: the rest would + // be undefined (a restored image's 256 rows of 0xAA). + if (l.filled < n) { + l.made.items[at].dead = true; + return error.BadDump; + } return many; } diff --git a/docs/typ/builtins-gui.json b/docs/typ/builtins-gui.json index 3d8819a0..a4016429 100644 --- a/docs/typ/builtins-gui.json +++ b/docs/typ/builtins-gui.json @@ -57,6 +57,9 @@ {"name": "Joincol", "leader": "SPC c j", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Fold the keyboard's column into the one on its right, keeping its panes.", "text": "Fold the keyboard's column into the one on its right, keeping its panes.\nRefused for the last column, and where the joined column could not give each pane its tag and 2 rows."}, {"name": "JumpTrail", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "A jump of the cursor leaves a short trail that fades, on or off.", "text": "A jump of the cursor leaves a short trail that fades, on or off."}, {"name": "Jumplist", "leader": "SPC j l", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "List the places jumped from in a +Jumps, each a place to go.", "text": "List the places jumped from in a +Jumps, each a place to go."}, + {"name": "Jumps", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "walk, new-pane", "doc": "A jump steps its pane or that pane's reader (walk), or opens a pane for each file (new-pane).", "text": "A jump steps its pane or that pane's reader (walk), or opens a pane for each file (new-pane)."}, + {"name": "Keep", "leader": "SPC j k", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Keep this pane: a reading pane, which a jump steps, is held from now on.", "text": "Keep this pane: a reading pane, which a jump steps, is held from now on.\nIts walk leaves its tag (its places, its owner): the next jump from its owner makes a new reader. Editing a reading pane keeps it too."}, + {"name": "Keys", "leader": "SPC h k", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Show what a key sequence runs: the next keys typed are replayed in the tag.", "text": "Show what a key sequence runs: the next keys typed are replayed in the tag.\nThe tag shows `Keys` and the keys as they are typed; a sequence that reaches a leaf unrolls its level under the tag with the leaf on the cursor and its documentation beside it, and Enter runs it. Every root answers: SPC, g, m, z, Z, [, ], window mode's C-w. A sequence nothing is bound to is shown struck, `runs nothing`. Esc leaves it."}, {"name": "Kill", "leader": null, "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Stop the commands pardes started that are still running.", "text": "Stop the commands pardes started that are still running.\nThey are the lines pardes typed into a terminal (from an exec, a middle click, a pty/run) and its command panes. Bare, every one; `Kill make ls`, those whose line starts with one of the words. Each gets SIGTERM: a command pane's whole command, a terminal's foreground job, never its shell, which stays."}, {"name": "Last", "leader": "SPC j j", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Go back to the last place jumped from in another pane.", "text": "Go back to the last place jumped from in another pane.\nWith none, to the pane beside this one."}, {"name": "Left", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Move the keyboard to the pane, or column tag, to the left.", "text": "Move the keyboard to the pane, or column tag, to the left."}, @@ -89,6 +92,7 @@ {"name": "Rename", "leader": "SPC l r", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Rename the symbol under the cursor to its argument, wherever the language server finds it.", "text": "Rename the symbol under the cursor to its argument, wherever the language server finds it.\nBare, it asks for the new name. Within this file it is done at once, saying how many places changed; one that reaches other files changes nothing and lists its edits in a +Search to look over."}, {"name": "Repl", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Bind this terminal as a language's REPL: an exec on that language's files is typed into it.", "text": "Bind this terminal as a language's REPL: an exec on that language's files is typed into it.\n`Repl python` binds it (the language named as a code fence names it: `py`, `Python`, `sh`); `Repl -` unbinds it; bare, it says what it is bound as. An exec made on the body of a file in that language (a middle click, the execute key, a single word like `ls` as much as a selection), and one made on this terminal's own body, is typed into it (bracketed paste if its program asked for that, else line by line, then Enter) instead of run. With several bound for a language, the exec asks which.\nStill commands, whatever is bound: a word in a tag, `Exec <text>`, a ctl line, and a command word @`cmd` in the text, looked at or clicked."}, {"name": "Restore", "leader": "SPC s r", "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Replace every pane with those of a dump.", "text": "Replace every pane with those of a dump.\n`Restore <label>`: the state file's dump of that label (History lists them); `Restore <file>`: a dump file's, a path, or the name of a file in the DumpDir or the directory pardes runs in. Bare: the last one this session made, else the newest. A file that is not a dump is said first; then, as Exit, it is refused once while a pane holds unsaved text."}, + {"name": "Resume", "leader": "SPC '", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Reopen the last picker as it was: its rows, marks, cursor and query.", "text": "Reopen the last picker as it was: its rows, marks, cursor and query.\nIn the tag of the pane its Enter lands in from this one: this pane if it reads, else its reader. `SPC '`."}, {"name": "Right", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Move the keyboard to the pane, or column tag, to the right.", "text": "Move the keyboard to the pane, or column tag, to the right."}, {"name": "Save", "leader": "SPC f s", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Write the pane's text to its file, or to the file its argument names.", "text": "Write the pane's text to its file, or to the file its argument names.\n`Save <path>` writes it there. Bare, a pane with no file of its own (a +New, a list, a terminal) asks for a path; a file at a revision is read-only, written only to a path. Over a file changed on disk since it was read, it warns once."}, {"name": "Search", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Search in a query pane under this pane, its line 1 the argument.", "text": "Search in a query pane under this pane, its line 1 the argument.\nLine 1's first word names what it searches: `/re` this pane's text, `Find`, `Grep`, `Recent`, `Panes`, `Symbols`, `All` (every open pane's text), `Refs`, `Def`, `Impl`, `Diagnostics`; a line with none of them is a `/`: `Search lay` is `/lay`. Bare, `/`, typed into. `SPC b b`, `SPC s s` and `SPC /` open it with Panes, Symbols and All."}, diff --git a/docs/typ/builtins-tui.json b/docs/typ/builtins-tui.json index 1e7c80f7..38d87b19 100644 --- a/docs/typ/builtins-tui.json +++ b/docs/typ/builtins-tui.json @@ -53,6 +53,9 @@ {"name": "Joincol", "leader": "SPC c j", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Fold the keyboard's column into the one on its right, keeping its panes.", "text": "Fold the keyboard's column into the one on its right, keeping its panes.\nRefused for the last column, and where the joined column could not give each pane its tag and 2 rows."}, {"name": "JumpTrail", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "A jump of the cursor leaves a short trail that fades, on or off.", "text": "A jump of the cursor leaves a short trail that fades, on or off."}, {"name": "Jumplist", "leader": "SPC j l", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "List the places jumped from in a +Jumps, each a place to go.", "text": "List the places jumped from in a +Jumps, each a place to go."}, + {"name": "Jumps", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "walk, new-pane", "doc": "A jump steps its pane or that pane's reader (walk), or opens a pane for each file (new-pane).", "text": "A jump steps its pane or that pane's reader (walk), or opens a pane for each file (new-pane)."}, + {"name": "Keep", "leader": "SPC j k", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Keep this pane: a reading pane, which a jump steps, is held from now on.", "text": "Keep this pane: a reading pane, which a jump steps, is held from now on.\nIts walk leaves its tag (its places, its owner): the next jump from its owner makes a new reader. Editing a reading pane keeps it too."}, + {"name": "Keys", "leader": "SPC h k", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Show what a key sequence runs: the next keys typed are replayed in the tag.", "text": "Show what a key sequence runs: the next keys typed are replayed in the tag.\nThe tag shows `Keys` and the keys as they are typed; a sequence that reaches a leaf unrolls its level under the tag with the leaf on the cursor and its documentation beside it, and Enter runs it. Every root answers: SPC, g, m, z, Z, [, ], window mode's C-w. A sequence nothing is bound to is shown struck, `runs nothing`. Esc leaves it."}, {"name": "Kill", "leader": null, "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Stop the commands pardes started that are still running.", "text": "Stop the commands pardes started that are still running.\nThey are the lines pardes typed into a terminal (from an exec, a middle click, a pty/run) and its command panes. Bare, every one; `Kill make ls`, those whose line starts with one of the words. Each gets SIGTERM: a command pane's whole command, a terminal's foreground job, never its shell, which stays."}, {"name": "Last", "leader": "SPC j j", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Go back to the last place jumped from in another pane.", "text": "Go back to the last place jumped from in another pane.\nWith none, to the pane beside this one."}, {"name": "Left", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Move the keyboard to the pane, or column tag, to the left.", "text": "Move the keyboard to the pane, or column tag, to the left."}, @@ -84,6 +87,7 @@ {"name": "Rename", "leader": "SPC l r", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Rename the symbol under the cursor to its argument, wherever the language server finds it.", "text": "Rename the symbol under the cursor to its argument, wherever the language server finds it.\nBare, it asks for the new name. Within this file it is done at once, saying how many places changed; one that reaches other files changes nothing and lists its edits in a +Search to look over."}, {"name": "Repl", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Bind this terminal as a language's REPL: an exec on that language's files is typed into it.", "text": "Bind this terminal as a language's REPL: an exec on that language's files is typed into it.\n`Repl python` binds it (the language named as a code fence names it: `py`, `Python`, `sh`); `Repl -` unbinds it; bare, it says what it is bound as. An exec made on the body of a file in that language (a middle click, the execute key, a single word like `ls` as much as a selection), and one made on this terminal's own body, is typed into it (bracketed paste if its program asked for that, else line by line, then Enter) instead of run. With several bound for a language, the exec asks which.\nStill commands, whatever is bound: a word in a tag, `Exec <text>`, a ctl line, and a command word @`cmd` in the text, looked at or clicked."}, {"name": "Restore", "leader": "SPC s r", "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Replace every pane with those of a dump.", "text": "Replace every pane with those of a dump.\n`Restore <label>`: the state file's dump of that label (History lists them); `Restore <file>`: a dump file's, a path, or the name of a file in the DumpDir or the directory pardes runs in. Bare: the last one this session made, else the newest. A file that is not a dump is said first; then, as Exit, it is refused once while a pane holds unsaved text."}, + {"name": "Resume", "leader": "SPC '", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Reopen the last picker as it was: its rows, marks, cursor and query.", "text": "Reopen the last picker as it was: its rows, marks, cursor and query.\nIn the tag of the pane its Enter lands in from this one: this pane if it reads, else its reader. `SPC '`."}, {"name": "Right", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Move the keyboard to the pane, or column tag, to the right.", "text": "Move the keyboard to the pane, or column tag, to the right."}, {"name": "Save", "leader": "SPC f s", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Write the pane's text to its file, or to the file its argument names.", "text": "Write the pane's text to its file, or to the file its argument names.\n`Save <path>` writes it there. Bare, a pane with no file of its own (a +New, a list, a terminal) asks for a path; a file at a revision is read-only, written only to a path. Over a file changed on disk since it was read, it warns once."}, {"name": "Search", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Search in a query pane under this pane, its line 1 the argument.", "text": "Search in a query pane under this pane, its line 1 the argument.\nLine 1's first word names what it searches: `/re` this pane's text, `Find`, `Grep`, `Recent`, `Panes`, `Symbols`, `All` (every open pane's text), `Refs`, `Def`, `Impl`, `Diagnostics`; a line with none of them is a `/`: `Search lay` is `/lay`. Bare, `/`, typed into. `SPC b b`, `SPC s s` and `SPC /` open it with Panes, Symbols and All."}, diff --git a/test/behaviour/keys.zig b/test/behaviour/keys.zig index 49c85512..8bf187f8 100644 --- a/test/behaviour/keys.zig +++ b/test/behaviour/keys.zig @@ -381,12 +381,12 @@ test "keys: a PDF in normal mode keeps : (its tag and back), SPC (a leader, canc try std.testing.expect(std.mem.endsWith(u8, try s.read(s.at("/pane/{d}/ctl", .{n})), " mode:normal ")); try s.keys(":"); try std.testing.expect(try s.cursor() == null); - // The leader shows its keys until one it has not (over the panes: the - // notice row under them names SPC h m). + // The leader shows its key cell in the tag at once (walk UI) until a + // key the PDF takes, which takes the leader away. try s.keys(" "); - try std.testing.expect(std.mem.indexOf(u8, try panesShown(&s), " SPC") != null); + try std.testing.expect(std.mem.indexOf(u8, try panesShown(&s), " ␣ ") != null); try s.keys("!"); - try std.testing.expect(std.mem.indexOf(u8, try panesShown(&s), " SPC") == null); + try std.testing.expect(std.mem.indexOf(u8, try panesShown(&s), " ␣ ") == null); try s.keys("/"); try std.testing.expect(try s.cursor() != null); try std.testing.expectEqual(n, try s.focused()); diff --git a/test/behaviour/modes.zig b/test/behaviour/modes.zig index e615920d..a50cfb0e 100644 --- a/test/behaviour/modes.zig +++ b/test/behaviour/modes.zig @@ -118,11 +118,13 @@ fn threePanes(s: *Session) ![3]u32 { return .{ a, b, c }; } -/// The panes whose tag (`name Save`) is drawn in `lit`, the outline's colour. +/// The panes whose tag (`name `: the pane with the keyboard shows window +/// mode's head after its name, the others their own words) is drawn in +/// `lit`, the outline's colour. fn outlined(s: *Session, lit: []const u8, names: []const []const u8) ![]const u8 { var found: []const u8 = ""; for (names) |name| { - const x, const y = try s.where(s.at("{s} Save", .{name})); + const x, const y = try s.where(s.at("{s} ", .{name})); if (std.mem.eql(u8, lit, try s.bg(x, y))) found = s.at("{s}{s}", .{ found, name }); } return found; @@ -134,7 +136,7 @@ test "modes: Ctrl-w outlines a pane, h j k l move the outline, and Enter, Esc, : const a, const b, const c = try threePanes(&s); const names = &[_][]const u8{ "/a.txt", "/b.txt", "/c.txt" }; try s.keys("\x17"); - const x, const y = try s.where("/a.txt Save"); + const x, const y = try s.where("/a.txt "); const lit = try s.bg(x, y); try std.testing.expectEqualStrings("/a.txt", try outlined(&s, lit, names)); // Each pane's box shows its letter: the left column's is a. @@ -198,7 +200,7 @@ test "modes: in window mode d deletes the outlined pane, asking k or j between t try std.testing.expectEqualStrings("/mid", try outlined(&s, lit, names)); try s.keys("c"); try std.testing.expect(std.mem.indexOf(u8, try s.read(s.at("/pane/{d}/ctl", .{mid})), " collapsed ") == null); - try expectEqual(row_low, (try s.where("/low Save"))[1]); + try expectEqual(row_low, (try s.where("/low "))[1]); // d between two panes asks, as SPC d does; Esc takes it back, the // outline where it was. try s.keys("d"); @@ -210,7 +212,7 @@ test "modes: in window mode d deletes the outlined pane, asking k or j between t try s.keys("dj"); try std.testing.expect(!try listed(&s, mid)); try expectEqual(row_top, (try s.where("/test.txt Save"))[1]); - try expectEqual(row_mid, (try s.where("/low Save"))[1]); + try expectEqual(row_mid, (try s.where("/low "))[1]); try std.testing.expectEqualStrings("/low", try outlined(&s, lit, &.{ "/test.txt", "/low" })); // With one neighbour nothing is asked: d closes it, the outline on the // pane that grew. diff --git a/test/daemon.py b/test/daemon.py index 97b0de76..f9cbc9e1 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -340,7 +340,7 @@ class Replica: """A replica's connection (abi/wire.zig): length-prefixed messages, a tag byte and a little-endian u32 length. It is a near client: its first word after the hello says so.""" - WIRE = 35 + WIRE = 36 def __init__(self, path, timeout=10): self.path, self.timeout = path, timeout diff --git a/test/panes.zig b/test/panes.zig index 60bff538..2d3c345f 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -2073,7 +2073,8 @@ const OutputTests = struct { try std.testing.expect(help.body.vsel.active); try std.testing.expect(help.body.vsel.row > 5); try std.testing.expect(help.body.cur_row != help.body.vsel.row); - for (" h?") |key| p.update(.{ .key = .{ .cp = key } }); + // `Help h`, the word (SPC h ? is Help in the tag now: walk UI). + try std.testing.expect(p.executeBuiltinLine(id, "Help h")); try std.testing.expectEqual(id, p.view().active); const content = help.file.?.content; try std.testing.expect(std.mem.startsWith(u8, content, "pardes builtins under SPC h\n")); diff --git a/test/perf.zig b/test/perf.zig index f36d64ac..17098f3d 100644 --- a/test/perf.zig +++ b/test/perf.zig @@ -70,6 +70,31 @@ const Op = enum { /// the window: a kind's frame costs its window's cells, never its /// picture (docs: architecture §16.1, its trigger 5% of a frame). image_frame, + /// The walk UI's tag states (TagState.zig), each key pumped and the + /// frame that draws it: SPC struck at rest, its level shown when its + /// delay is up, Esc back to rest (three frames, two keys). + spc, + /// A Down in SPC's unrolled level: its cursor a row on, the band drawn. + spc_down, + /// A character typed in Help's field and a Backspace: its rows + /// filtered again each time (two keys). + help_type, + /// describe-key's `g d` replayed: the level and the leaf's doc under the + /// tag (two keys). + describe, + /// `j` and `k` at rest in the same loop (two keys, two frames): what + /// the tag states' keys compare with (key-down's frames each draw + /// another place of the file). + rest_keys, + + /// Run only when named (`--op`): a full run, its cells and the sums a + /// gate takes over them (perfops' "terminal on all") are as before. + fn named(o: Op) bool { + return switch (o) { + .spc, .spc_down, .help_type, .describe, .rest_keys => true, + else => false, + }; + } fn label(o: Op) []const u8 { return switch (o) { @@ -88,6 +113,11 @@ const Op = enum { .body_appends => "body-appends", .deep_selection => "deep-sel", .image_frame => "image-frame", + .spc => "spc", + .spc_down => "spc-down", + .help_type => "help-type", + .describe => "describe", + .rest_keys => "rest-keys", }; } }; @@ -394,6 +424,8 @@ const Options = struct { mini: bool = false, /// The scans a frame's slice bounds, a call at a time (`measureSearch`). search: bool = false, + /// A picker's key and frame (`measurePick`). + pick: bool = false, terminal_mib: ?usize = null, /// The real binary's keystroke-to-present, `yes` stream and big open /// (a tty pardes), or its keystrokes alone (a pardes-gui). @@ -410,7 +442,7 @@ const Options = struct { while (i < args.len) : (i += 1) { const arg = args[i]; if (!std.mem.startsWith(u8, arg, "--")) return error.UnknownOption; - const option = std.meta.stringToEnum(enum { json, creation, startup, mini, search, @"terminal-mib", @"self-test", reps, cols, rows, base, only, op, @"max-ratio", live, @"live-gui" }, arg[2..]) orelse + const option = std.meta.stringToEnum(enum { json, creation, startup, mini, search, pick, @"terminal-mib", @"self-test", reps, cols, rows, base, only, op, @"max-ratio", live, @"live-gui" }, arg[2..]) orelse return error.UnknownOption; switch (option) { .json => opts.json = true, @@ -418,6 +450,7 @@ const Options = struct { .startup => opts.startup = true, .mini => opts.mini = true, .search => opts.search = true, + .pick => opts.pick = true, .@"self-test" => opts.self_test = true, else => { i += 1; @@ -480,6 +513,7 @@ pub fn main(init: std.process.Init) !void { if (opts.terminal_mib) |mib| return measureTerminalSession(init.io, mib, reps, opts.json); if (opts.mini) return measureMini(init.io, init.gpa, reps, opts.json); if (opts.search) return measureSearch(init.io); + if (opts.pick) return measurePick(init.io); if (opts.live) |exe| return measureLive(init.io, exe, false, reps, opts.json); if (opts.live_gui) |exe| return measureLive(init.io, exe, true, reps, opts.json); // The image-frame cells load the image addon by the path the build baked @@ -524,6 +558,7 @@ pub fn main(init: std.process.Init) !void { for (fixtures, 0..) |fx, fi| { if (only) |name| if (!std.mem.eql(u8, name, fx.name)) continue; if (opts.op) |o| if (o != op) continue; + if (op.named() and opts.op == null) continue; cells[oi][fi] = try measure(op, fx, paths[fi], bytes[fi], reps); } } @@ -538,7 +573,7 @@ pub fn main(init: std.process.Init) !void { } } - if (opts.json) try reportJson(init.io, &cells, &term_cells, &bytes, opts) else reportText(&cells, &term_cells, &bytes, reps, opts.base, base); + if (opts.json) try reportJson(init.io, &cells, &term_cells, &bytes, opts) else reportText(&cells, &term_cells, &bytes, reps, opts.op, opts.base, base); if (opts.max_ratio) |ratio| try gate(&cells, &base.?, ratio); } @@ -583,6 +618,7 @@ fn measure(op: Op, fx: Fixture, path: []const u8, expected_bytes: usize, reps: u switch (op) { .image_frame => return measureImage(std.fs.path.dirname(path).?, samples, warmup), .client_key_down, .client_edit_char, .client_delete_undo => return measureClient(op, path, reps), + .spc, .spc_down, .help_type, .describe, .rest_keys => return measureTag(op, path, reps), else => {}, } if (op == .open) { @@ -637,7 +673,7 @@ fn measure(op: Op, fx: Fixture, path: []const u8, expected_bytes: usize, reps: u const wheel_row = rect.y + pardes.BOX_H; const t0 = nowNs(); switch (op) { - .open, .image_frame, .client_key_down, .client_edit_char, .client_delete_undo => unreachable, + .open, .image_frame, .client_key_down, .client_edit_char, .client_delete_undo, .spc, .spc_down, .help_type, .describe, .rest_keys => unreachable, .render, .deep_selection => {}, .key_down => core.update(.{ .key = .{ .cp = 'j', .text = "j" } }), .key_right => core.update(.{ .key = .{ .cp = 'l', .text = "l" } }), @@ -651,7 +687,7 @@ fn measure(op: Op, fx: Fixture, path: []const u8, expected_bytes: usize, reps: u _ = try frame(core); const dt = nowNs() -| t0; switch (op) { - .open, .image_frame, .client_key_down, .client_edit_char, .client_delete_undo => unreachable, + .open, .image_frame, .client_key_down, .client_edit_char, .client_delete_undo, .spc, .spc_down, .help_type, .describe, .rest_keys => unreachable, .body_write => if (pane.file.?.content.len != before.len + 8 * body_chunk.len) return error.BodyWriteWasNotAppended, .body_appends => if (pane.file.?.content.len != before.len + append_count * append_chunk_len) return error.BodyAppendsWereNotAppended, .render, .deep_selection => if (pane.body.cur_row != before.row or pane.body.cur_col != before.col or pane.file.?.content.len != before.len) @@ -736,6 +772,68 @@ fn clientKey(a: *pardes.replica.Authority, r: *pardes.replica.Replica, ev: parde r.settle(); } +/// A tag state's keys on the fixture's pane, each pumped and its frame +/// drawn, from the state the op starts in (entered untimed); the state +/// checked after each repetition. +fn measureTag(op: Op, path: []const u8, reps: usize) !Cell { + const Key = pardes.Key; + const warmup = 3; + const samples = try gpa.alloc(u64, reps); + defer gpa.free(samples); + const core = try boot(); + defer core.deinit(); + pardes.look.lookAt(core, 0, path); + pump(core); + const id = filePane(core) orelse return error.OpenDidNotOpenFile; + core.view().active = id; + const enter: []const Key = switch (op) { + .spc, .rest_keys => &.{}, + .spc_down => &.{ .{ .cp = ' ', .text = " " }, .{ .cp = Key.down } }, + .help_type => &.{ .{ .cp = ' ', .text = " " }, .{ .cp = '?', .text = "?" } }, + .describe => &.{ .{ .cp = ' ', .text = " " }, .{ .cp = 'h', .text = "h" }, .{ .cp = 'k', .text = "k" } }, + else => unreachable, + }; + for (enter) |k| core.update(.{ .key = k }); + pump(core); + _ = try frame(core); + const keys: []const Key = switch (op) { + .spc => &.{ .{ .cp = ' ', .text = " " }, .{ .cp = Key.escape } }, + .spc_down => &.{.{ .cp = Key.down }}, + .help_type => &.{ .{ .cp = 'e', .text = "e" }, .{ .cp = Key.backspace } }, + .describe => &.{ .{ .cp = 'g', .text = "g" }, .{ .cp = 'd', .text = "d" } }, + .rest_keys => &.{ .{ .cp = 'j', .text = "j" }, .{ .cp = 'k', .text = "k" } }, + else => unreachable, + }; + const s = &core.view().tag_state; + for (0..warmup + samples.len) |n| { + const t0 = nowNs(); + for (keys) |k| { + core.update(.{ .key = k }); + pump(core); + _ = try frame(core); + // SPC's level when its delay is up: the frame that shows it. + if (op == .spc and k.cp == ' ') { + core.advance(core.clock.now_ns); + core.clock.now_ns = s.due_ns; + if (!pardes.TagState.shown(core, core.view())) return error.LevelNotShown; + _ = try frame(core); + } + } + const dt = nowNs() -| t0; + const held = switch (op) { + .spc => s.kind == .rest and s.root == null, + .spc_down => s.unrolled and core.panes[id].?.band_rows > 0, + .help_type => s.kind == .help and s.field.len == 0 and s.nhits > 0, + .describe => s.kind == .describe and s.found, + .rest_keys => s.kind == .rest and s.root == null and core.panes[id].?.body.cur_row == 0, + else => unreachable, + }; + if (!held) return error.TagStateLost; + if (n >= warmup) samples[n - warmup] = dt / 1000; + } + return summarize(samples); +} + fn measureImage(dir: []const u8, samples: []u64, warmup: usize) !Cell { const path = try std.fmt.allocPrint(gpa, "{s}/picture.ppm", .{dir}); defer gpa.free(path); @@ -1824,6 +1922,81 @@ fn measureSearch(io: std.Io) !void { } } +/// `--pick`: a picker's hot paths (core/Pick.zig, walk UI line D), each +/// a step and the frame that draws it, timed and its instructions counted +/// (user space, this thread): a key typed into a Find of 50,000 paths and +/// the frames after it while its names are scored; a cursor move over rows +/// that are files, and the frame after it that loads the preview into the +/// landing pane's body (a 2,000-line file read from the disk). +fn measurePick(io: std.Io) !void { + var random: [12]u8 = undefined; + io.random(&random); + const dir = try std.fmt.allocPrint(gpa, "/tmp/pardes-pick-{x}", .{random}); + defer gpa.free(dir); + try std.Io.Dir.createDirAbsolute(io, dir, .default_dir); + defer std.Io.Dir.cwd().deleteTree(io, dir) catch {}; + var counter: Instructions = try .open(); + defer counter.close(); + var body: std.ArrayList(u8) = .empty; + defer body.deinit(gpa); + for (0..2000) |i| try body.print(gpa, " const value_{d} = compute(value_{d}, \"a line of the preview\");\n", .{ i, i -| 1 }); + var name: [160]u8 = undefined; + for (0..20) |i| try writeFile(try std.fmt.bufPrint(&name, "{s}/pickme_{d}.zig", .{ dir, i }), body.items); + const start = try std.fmt.allocPrint(gpa, "{s}/start.zig", .{dir}); + defer gpa.free(start); + try writeFile(start, "const start = 1;\n"); + const core = try boot(); + defer core.deinit(); + core.settings.jumps = .walk; + pardes.look.lookAt(core, 0, start); + pump(core); + const id = filePane(core) orelse return error.OpenDidNotOpenFile; + pardes.Pick.open(core, id, .find, "", "", ""); + const pk = pardes.Pick.live(core) orelse return error.NoPicker; + // The listing as the disk engine would give it: 50,000 paths, the + // real files among them. + _ = core.stream.stop(); + pk.names.reset(); + const dirs = [_][]const u8{ "core", "dev/gui", "dev/tui", "runtime", "test/behaviour", "addons/pdf", "zig-pkg/ghostty/src/terminal" }; + const words = [_][]const u8{ "layout", "places", "names", "query", "stream", "surface", "replica", "tape", "kitty", "render" }; + for (0..50_000) |i| { + const path = if (i % 2500 == 0) try std.fmt.bufPrint(&name, "pickme_{d}.zig", .{i / 2500}) else try std.fmt.bufPrint(&name, "{s}/module_{d}/{s}_{d}.zig", .{ dirs[i % dirs.len], i / 64 % 997, words[i * 7 % words.len], i }); + try pk.names.add(gpa, path, 0, path.len, @TypeOf(pk.names).baseOf(path), 0); + } + pk.names.typed(gpa, ""); + while (pk.names.busy()) pk.names.rescore(gpa); + try frame(core); + const Step = struct { + fn run(c: *pardes.Pardes, ev: pardes.Event, n: *Instructions, s: *Slowest, hits: usize) !void { + const was = n.read(); + const t0 = nowNs(); + c.update(ev); + try frame(c); + s.add(nowNs() -| t0, n.read() -| was, hits); + } + }; + var keys: Slowest = .{}; + var after: Slowest = .{}; + for ("pickme") |ch| { + try Step.run(core, .{ .key = .{ .cp = ch, .text = &[_]u8{ch} } }, &counter, &keys, pk.names.hits.items.len); + while (pk.names.busy()) try Step.run(core, .tick, &counter, &after, pk.names.hits.items.len); + } + keys.report("pick key + frame", "pickme", pk.names.hits.items.len); + after.report("pick tick + frame while scoring", "pickme", pk.names.hits.items.len); + // The first preview, then the cursor moved and the preview after it. + try Step.run(core, .tick, &counter, &after, 0); + var moves: Slowest = .{}; + var previews: Slowest = .{}; + for (0..19) |_| { + try Step.run(core, .{ .key = .{ .cp = pardes.Key.down } }, &counter, &moves, 0); + try Step.run(core, .tick, &counter, &previews, 0); + } + moves.report("pick Down + frame", "pickme", pk.names.hits.items.len); + previews.report("pick preview tick + frame", "pickme", pk.names.hits.items.len); + const landing = core.panes[core.paneBySerial(pk.landing) orelse return error.NoLanding].?; + if (!std.mem.endsWith(u8, landing.file.?.path, ".zig") or std.mem.indexOf(u8, landing.file.?.path, "pickme_") == null) return error.NoPreview; +} + /// The longest of a scan's calls. const Slowest = struct { calls: usize = 0, @@ -1988,6 +2161,7 @@ fn reportText( term_cells: *const [std.enums.values(TermOp).len][term_fixtures.len]Cell, bytes: *const [fixtures.len]usize, reps: usize, + named: ?Op, base_path: ?[]const u8, base: ?Base, ) void { @@ -2011,6 +2185,7 @@ fn reportText( o("\n{s}\n", .{if (base != null) &@as([12 + fixtures.len * 20]u8, @splat('-')) else &@as([12 + fixtures.len * 13]u8, @splat('-'))}); var worst_jitter: f64 = 0; for (std.enums.values(Op), 0..) |op, oi| { + if (op.named() and named != op) continue; o("{s:<12}", .{op.label()}); for (0..fixtures.len) |fi| { const c = cells[oi][fi]; @@ -2100,6 +2275,7 @@ fn writeJson( for (fixtures, 0..) |fx, fi| { if (opts.only) |name| if (!std.mem.eql(u8, name, fx.name)) continue; if (opts.op) |o| if (o != op) continue; + if (op.named() and opts.op == null) continue; const c = cells[oi][fi]; try out.print("{s}{{\"op\":\"{s}\",\"fixture\":\"{s}\",\"min_us\":{d},\"med_us\":{d},\"p90_us\":{d},\"max_us\":{d}}}", .{ if (first) "" else ",", op.label(), fx.name, c.min_us, c.med_us, c.p90_us, c.max_us, @@ -2204,7 +2380,7 @@ fn parseBase(src: []const u8, opts: Options, bytes: *const [fixtures.len]usize) } for (fixtures, 0..) |fixture, fi| { if (opts.only) |name| if (!std.mem.eql(u8, name, fixture.name)) continue; - for (file_seen) |row| if (!row[fi]) return error.BaselineCoverage; + for (file_seen, std.enums.values(Op)) |row, op| if (!row[fi] and !op.named()) return error.BaselineCoverage; } if (opts.only == null) for (term_seen) |row| { for (row) |seen| if (!seen) return error.BaselineCoverage; diff --git a/test/process/tty_boot.zig b/test/process/tty_boot.zig index 01b35a24..e342ea46 100644 --- a/test/process/tty_boot.zig +++ b/test/process/tty_boot.zig @@ -114,14 +114,17 @@ fn boot(gpa: std.mem.Allocator, exe: [:0]const u8) !void { fn builtins(gpa: std.mem.Allocator, exe: [:0]const u8) !void { var t = try Tty.init(gpa, exe, "builtins"); defer t.deinit(); - try t.lines("notes.txt", 6, ""); + // SPC ? is Help in the tag now (pick-ui SPEC §4.5): the +Help index is + // the word's, `Help` run from the workspace's tag, `Help c` swept here. + try t.file("notes.txt", "Help c Help h\nline 2\nline 3\nline 4\nline 5\nline 6\n"); try t.start(67, 120, &.{"notes.txt"}); try t.wait(8000, "notes.txt"); try t.stable(700, 20000); try t.snap("boot"); // The full index includes commands without leader paths. - try t.key("space ?"); + try t.press("middle", "@Help", 1); + try t.release("middle", "@Help", 1); try t.wait(10000, "pardes builtins: each one's keys and its name"); try t.wait(10000, "ClipPasteBefore"); // The words with no SPC path come last, each under its documentation: @@ -141,19 +144,20 @@ fn builtins(gpa: std.mem.Allocator, exe: [:0]const u8) !void { try t.key("space j n space j n space j n"); try t.wait(10000, "Look enter, right-click"); try t.wait(10000, "Look at its argument as B3 does"); - try t.key("space c ?"); + try sweepHelp(&t, "@Help#1", 4); try t.wait(10000, "under SPC c"); try t.wait(10000, "Joincol"); try t.stable(700, 15000); try t.snap("column-group"); - try t.key("space h ?"); + try sweepHelp(&t, "@Help#2", 4); try t.wait(10000, "Tutor"); try t.stable(700, 15000); try t.snap("docs-group"); - // Tutor's row, under the documentation of the three before it - try t.press("middle", "@Tutor", 24); - try t.release("middle", "@Tutor", 24); + // Tutor's row, under the documentation of the four before it (Keys, + // describe-key, is SPC h k) + try t.press("middle", "@Tutor", 30); + try t.release("middle", "@Tutor", 30); try t.wait(10000, "PARDES TUTOR"); try t.stable(700, 15000); try t.snap("tutor-from-index"); @@ -472,13 +476,18 @@ fn topbarexec(gpa: std.mem.Allocator, exe: [:0]const u8) !void { fn leader(gpa: std.mem.Allocator, exe: [:0]const u8) !void { var t = try Tty.init(gpa, exe, "leader"); defer t.deinit(); - try t.file("cmds.txt", "Help"); + // SPC ? and `?` down a level are Help in the tag now (pick-ui SPEC + // §4.5): the +Help index for a group is the word's, `Help h` swept here. + try t.file("cmds.txt", "Help Help h Help t Help c Help l"); try t.start(41, 100, &.{"cmds.txt"}); try t.wait(8000, "Newcol Joincol"); try t.wait(8000, "cmds.txt"); try t.stable(700, 20000); + // SPC's level, rolled in the tag once its delay is up (a frame on the + // clock, which a quiet screen does not wait for) try t.key("space"); + try t.wait(5000, "↓ unroll"); try t.stable(400, 5000); try t.snap("spc"); try t.key("h"); @@ -489,15 +498,21 @@ fn leader(gpa: std.mem.Allocator, exe: [:0]const u8) !void { try t.stable(400, 5000); try t.snap("abandoned"); try t.key("space x"); + try t.wait(5000, "↓ unroll"); try t.stable(400, 5000); try t.snap("unmapped"); + // A key the level has no child for is struck and the level stays + // (which-key); Esc leaves it. + try t.key("esc"); + try t.settle(100); + try t.stable(400, 5000); // Executing Help as text opens the full index, not a filtered group. try t.press("middle", "@Help", 4); try t.release("middle", "@Help", 4); try t.wait(10000, "pardes builtins: each one's keys and its name"); try t.wait(10000, "ClipPasteBefore"); - try t.key("space h ?"); + try sweepHelp(&t, "@Help#2", 4); try t.wait(10000, "under SPC h"); try t.stable(700, 15000); try t.snap("help-group"); @@ -517,23 +532,24 @@ fn leader(gpa: std.mem.Allocator, exe: [:0]const u8) !void { try t.key("space d"); try t.stable(700, 15000); - try t.key("space ?"); + try t.press("middle", "@Help", 4); + try t.release("middle", "@Help", 4); try t.wait(10000, "pardes builtins: each one's keys and its name"); try t.wait(10000, "ClipPasteBefore"); // PDF commands depend on the build; these toggles do not. - try t.key("space t ?"); + try sweepHelp(&t, "@Help#3", 4); try t.wait(10000, "under SPC t"); // its first rows: each word's documentation under it, the rest below try t.wait(10000, "SPC t a Ascii"); try t.wait(10000, "SPC t c Changes"); // SPC w is Window itself now, not a group; the column group stands in - try t.key("space c ?"); + try sweepHelp(&t, "@Help#4", 4); try t.wait(10000, "under SPC c"); try t.wait(10000, "Joincol"); try t.stable(700, 15000); try t.snap("help-column"); - try t.key("space l ?"); + try sweepHelp(&t, "@Help#5", 4); try t.wait(10000, "WsDiagnostics"); try t.stable(700, 15000); try t.snap("help-language"); @@ -544,6 +560,15 @@ fn leader(gpa: std.mem.Allocator, exe: [:0]const u8) !void { try t.done(); } +/// B2 swept over `Help <key>` from the word `at` on `row` (its six +/// cells): the word and its argument run, as a sweep anywhere runs them. +fn sweepHelp(t: *Tty, at: []const u8, row: u16) !void { + const end = try std.fmt.allocPrint(t.arena, "{s}+6", .{at}); + try t.press("middle", at, row); + try t.drag("middle", end, row); + try t.release("middle", end, row); +} + fn mini(gpa: std.mem.Allocator, exe: [:0]const u8) !void { var t = try Tty.init(gpa, exe, "mini"); defer t.deinit(); diff --git a/test/process/tty_editing.zig b/test/process/tty_editing.zig index efb5dc9b..896a3634 100644 --- a/test/process/tty_editing.zig +++ b/test/process/tty_editing.zig @@ -609,9 +609,12 @@ fn find(gpa: std.mem.Allocator, exe: [:0]const u8) !void { try t.start(41, 120, &.{"here.txt"}); try t.wait(8000, "here.txt"); try t.stable(700, 20000); - // SPC f is a group (Find, New, Save, Recent, Grep): the indicator waits + // SPC f is a group (Find, New, Save, Recent, Grep): its level rolled in + // the tag once SPC's delay is up (a frame on the clock, which a quiet + // screen does not wait for) try t.key("space"); try t.key("f"); + try t.wait(5000, "↓ unroll"); try t.stable(400, 5000); try t.snap("group"); // the second f opens the query pane: every file listed, line 1 `Find ` diff --git a/test/process/tty_terminals.zig b/test/process/tty_terminals.zig index 550d5922..838b2aea 100644 --- a/test/process/tty_terminals.zig +++ b/test/process/tty_terminals.zig @@ -226,12 +226,13 @@ fn ttyhelp(gpa: std.mem.Allocator, exe: [:0]const u8) !void { // row 0, which is not a pane, so the terminal never saw it. try t.key("c-b"); try t.stable(600, 10000); + // SPC ? is Help in the focused pane's tag (pick-ui SPEC §4.5): a field + // typed in, the leaves it matches in rows under the tag, the cursor's + // documentation beside them. try t.key("space"); try t.key("?"); - // The bare-tty boot now opens an empty pane under the shell, so the index is - // half as tall: wait on a row that is on screen. What the leader route - // produced is the snapshot below, not this. - try t.wait(10000, "SPC ? Help"); + try t.send("tutor"); + try t.wait(10000, "SPC h t · Tutor · help"); try t.stable(700, 15000); try t.snap("leaderworks"); try t.done(); diff --git a/test/snapshots/builtins.golden b/test/snapshots/builtins.golden index 86d26b29..81a445e1 100644 --- a/test/snapshots/builtins.golden +++ b/test/snapshots/builtins.golden @@ -2,7 +2,7 @@ | Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config History Debug Exit | New Term Find Grep Joincol Delcol | /tmp/pardes-snap/builtins/cwd/notes.txt Save Term Collapse Follow Del -| 1 line 1 +| 1 Help c Help h | 2 line 2 | 3 line 3 | 4 line 4 @@ -91,8 +91,8 @@ |30: ~ |56: +Search 1/1 Save Undock Del |57: /^ +Look -|58: @p2:224:1 Look enter, right-click -|66: /tmp/pardes-snap/builtins/cwd/+Help:1 +|58: @p2:236:1 Look enter, right-click +|66: ✓ /tmp/pardes-snap/builtins/cwd/notes.txt Help 3 messages · SPC h m == snap docs-group grid=120x67 cursor=7,10 |10: 1 pardes builtins under SPC h |12: 3 SPC h b Build @@ -102,49 +102,46 @@ |17: 7 SPC h c Changelog topbar |18: 8 Show this build's version and what changed to reach it, in a +Changelog. |19: 9 -|20: 10 SPC h m Messages -|21: 11 Show the messages said so far in a +Messages, the newest first, an error's places under it. -|22: 12 -|23: 13 SPC h t Tutor topbar -|24: 14 Open the tutor, a document to work through. -|25: 15 -|26: ~ -|27: -|28: -|29: -|30: -== snap tutor-from-index grid=120x67 cursor=7,37 -|26: +Search 1/1 Save Undock Del -|27: /^ +Look -|28: @p2:224:1 Look enter, right-click -|36: /tmp/pardes-snap/builtins/cwd/+Tutor Save Term Collapse Follow Del -|37: 1 -|38: 2 PARDES TUTOR -|39: 3 -|40: 4 This pane is +Tutor, a copy: edit it freely; there is no need to -|41: 5 Save it (a bare Save asks for a path to write a copy to). -|42: 6 `Del` in its tag closes it; once you have edited it, `Del` refuses -|43: 7 once and the second `Del` discards. `Tutor` or SPC h t opens a -|44: 8 fresh copy. -|45: 9 -|46: 10 The guide (docs/typ/guide.typ) explains; this is the hands-on part. -|47: 11 Each lesson is a few things to do, then names its guide section. -|48: 12 Words in backticks, like `Save`, are builtins. -|49: 13 `Exec` (B2) runs the builtin a word names, or else runs it as a -|50: 14 shell line; `Look` (B3) opens what the text names, or else finds -|51: 15 it. Type a builtin in any tag and `Exec` it. Lines starting with -|52: 16 "| " are tags. -|53: 17 -|54: 18 Press j until you reach part 1. -|55: 19 -|56: 20 -|57: 21 ================================================================= -|58: 22 = PART 1 — MODES = -|59: 23 ================================================================= -|60: 24 -|61: 25 1. The box left of this pane's tag is blank, so you are in -|62: 26 NORMAL mode. Press i: it shows ^ (INSERT). Type a word, then -|63: 27 Esc: blank again. -|64: 28 2. Press Esc once more, in NORMAL: the keyboard goes back to the -|65: 29 pane you were in before (not what helix does). Come back with -|66: ✓ /tmp/pardes-snap/builtins/cwd/+Help Tutor 2 messages · SPC h m +|20: 10 SPC h k Keys +|21: 11 Show what a key sequence runs: the next keys typed are replayed in the tag. +|22: 12 The tag shows `Keys` and the keys as they are typed; a sequence that reaches a leaf unrolls its level under the ↩ +|23: tag with the leaf on the cursor and its documentation beside it, and Enter runs it. Every root answers: SPC, g, ↩ +|24: m, z, Z, [, ], window mode's C-w. A sequence nothing is bound to is shown struck, `runs nothing`. Esc leaves it. +|25: 13 +|26: 14 SPC h m Messages +|27: 15 Show the messages said so far in a +Messages, the newest first, an error's places under it. +|28: 16 +|29: 17 SPC h t Tutor topbar +|30: 18 Open the tutor, a document to work through. +|31: 19 +|32: ~ +|66: ✓ /tmp/pardes-snap/builtins/cwd/notes.txt Help 5 messages · SPC h m +== snap tutor-from-index grid=120x67 cursor=7,43 +|32: +Search 1/1 Save Undock Del +|33: /^ +Look +|34: @p2:236:1 Look enter, right-click +|42: /tmp/pardes-snap/builtins/cwd/+Tutor Save Term Collapse Follow Del +|43: 1 +|44: 2 PARDES TUTOR +|45: 3 +|46: 4 This pane is +Tutor, a copy: edit it freely; there is no need to +|47: 5 Save it (a bare Save asks for a path to write a copy to). +|48: 6 `Del` in its tag closes it; once you have edited it, `Del` refuses +|49: 7 once and the second `Del` discards. `Tutor` or SPC h t opens a +|50: 8 fresh copy. +|51: 9 +|52: 10 The guide (docs/typ/guide.typ) explains; this is the hands-on part. +|53: 11 Each lesson is a few things to do, then names its guide section. +|54: 12 Words in backticks, like `Save`, are builtins. +|55: 13 `Exec` (B2) runs the builtin a word names, or else runs it as a +|56: 14 shell line; `Look` (B3) opens what the text names, or else finds +|57: 15 it. Type a builtin in any tag and `Exec` it. Lines starting with +|58: 16 "| " are tags. +|59: 17 +|60: 18 Press j until you reach part 1. +|61: 19 +|62: 20 +|63: 21 ================================================================= +|64: 22 = PART 1 — MODES = +|65: 23 ================================================================= +|66: ✓ /tmp/pardes-snap/builtins/cwd/+Help Tutor 7 messages · SPC h m diff --git a/test/snapshots/find.golden b/test/snapshots/find.golden index 176a8d42..cad1b229 100644 --- a/test/snapshots/find.golden +++ b/test/snapshots/find.golden @@ -1,9 +1,9 @@ -== snap group grid=120x41 cursor=7,3 +== snap group grid=120x41 cursor=7,4 | Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config History Debug Exit | New Term Find Grep Joincol Delcol -| /tmp/pardes-snap/find/cwd/here.txt Save Term Collapse Follow Del -| 1 Find zqm SPC f -| +| /tmp/pardes-snap/find/cwd/here.txt ␣ f ▸ c Config f Find g Grep h History n New r Recent s Save ↓ unroll · ? h +| elp +| 1 Find zqm | | | @@ -41,7 +41,9 @@ | | /tmp/pardes-snap/find/cwd/here.txt:1 == snap armed grid=120x41 cursor=7,22 +|2: /tmp/pardes-snap/find/cwd/here.txt Save Term Collapse Follow Del |3: 1 Find zqm +|4: |21: ^ +Search 1/5 Del |22: Find |23: here.txt diff --git a/test/snapshots/leader.golden b/test/snapshots/leader.golden index 8c45af73..2714ad2c 100644 --- a/test/snapshots/leader.golden +++ b/test/snapshots/leader.golden @@ -1,10 +1,10 @@ -== snap spc grid=100x41 cursor=7,3 +== snap spc grid=100x41 cursor=7,5 | Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config History Debug Exit | New Term Find Grep Joincol Delcol -| /tmp/pardes-snap/leader/cwd/cmds.txt Save Term Collapse Follow Del -| 1 Help SPC -| -| +| /tmp/pardes-snap/leader/cwd/cmds.txt ␣ ▸ b buffer… c column… f file… h help… j jump… l lsp… +| n new… s session… t view… ' Resume / All ? Help d Del e Message p ClipPaste P ClipPasteBe +| fore q Exit R ClipReplace w Window y ClipYank Y ClipYankMain ↓ unroll · ? help +| 1 Help Help h Help t Help c Help l | | | @@ -40,12 +40,24 @@ | | | /tmp/pardes-snap/leader/cwd/cmds.txt:1 -== snap spc-h grid=100x41 cursor=7,3 -|3: 1 Help SPC h +== snap spc-h grid=100x41 cursor=7,4 +|2: /tmp/pardes-snap/leader/cwd/cmds.txt ␣ h ▸ b Build c Changelog k Keys m Messages t Tutor ↓ u +|3: nroll · ? help +|4: 1 Help Help h Help t Help c Help l +|5: == snap abandoned grid=100x41 cursor=7,3 -|3: 1 Help -== snap unmapped grid=100x41 cursor=7,3 +|2: /tmp/pardes-snap/leader/cwd/cmds.txt Save Term Collapse Follow Del +|3: 1 Help Help h Help t Help c Help l +|4: +== snap unmapped grid=100x41 cursor=7,5 +|2: /tmp/pardes-snap/leader/cwd/cmds.txt ␣ ▸ b buffer… c column… f file… h help… j jump… l lsp… +|3: n new… s session… t view… ' Resume / All ? Help d Del e Message p ClipPaste P ClipPasteBe +|4: fore q Exit R ClipReplace w Window y ClipYank Y ClipYankMain x ↓ unroll · ? help +|5: 1 Help Help h Help t Help c Help l == snap help-group grid=100x41 cursor=7,6 +|2: /tmp/pardes-snap/leader/cwd/cmds.txt Save Term Collapse Follow Del +|3: 1 Help Help h Help t Help c Help l +|4: |5: /tmp/pardes-snap/leader/cwd/+Help Save Term Collapse Follow Del |6: 1 pardes builtins under SPC h |7: 2 @@ -57,14 +69,21 @@ |13: 7 SPC h c Changelog topbar |14: 8 Show this build's version and what changed to reach it, in a +Changelog. |15: 9 -|16: 10 SPC h m Messages -|17: 11 Show the messages said so far in a +Messages, the newest first, an error's places under it. -|18: 12 -|19: 13 SPC h t Tutor topbar -|20: 14 Open the tutor, a document to work through. -|21: 15 -|22: ~ -|40: ✓ /tmp/pardes-snap/leader/cwd/cmds.txt Help 2 messages · SPC h m +|16: 10 SPC h k Keys +|17: 11 Show what a key sequence runs: the next keys typed are replayed in the tag. +|18: 12 The tag shows `Keys` and the keys as they are typed; a sequence that reaches a leaf unrolls ↩ +|19: its level under the tag with the leaf on the cursor and its documentation beside it, and Ent↩ +|20: er runs it. Every root answers: SPC, g, m, z, Z, [, ], window mode's C-w. A sequence nothing↩ +|21: is bound to is shown struck, `runs nothing`. Esc leaves it. +|22: 13 +|23: 14 SPC h m Messages +|24: 15 Show the messages said so far in a +Messages, the newest first, an error's places under it. +|25: 16 +|26: 17 SPC h t Tutor topbar +|27: 18 Open the tutor, a document to work through. +|28: 19 +|29: ~ +|40: ✓ /tmp/pardes-snap/leader/cwd/cmds.txt Help 4 messages · SPC h m == snap tutor grid=100x41 cursor=7,23 |22: /tmp/pardes-snap/leader/cwd/+Tutor Save Term Collapse Follow Del |23: 1 @@ -84,7 +103,7 @@ |37: 15 it. Type a builtin in any tag and `Exec` it. Lines starting with |38: 16 "| " are tags. |39: 17 -|40: ✓ /tmp/pardes-snap/leader/cwd/+Help Tutor 3 messages · SPC h m +|40: ✓ /tmp/pardes-snap/leader/cwd/+Help Tutor 5 messages · SPC h m == snap deleted grid=100x41 cursor=7,3 |5: |6: @@ -115,13 +134,13 @@ |31: 7 SPC h c Changelog topbar |32: 8 Show this build's version and what changed to reach it, in a +Changelog. |33: 9 -|34: 10 SPC h m Messages -|35: 11 Show the messages said so far in a +Messages, the newest first, an error's places under it. -|36: 12 -|37: 13 SPC h t Tutor topbar -|38: 14 Open the tutor, a document to work through. -|39: 15 -|40: ✓ /tmp/pardes-snap/leader/cwd/+Tutor Del 4 messages · SPC h m +|34: 10 SPC h k Keys +|35: 11 Show what a key sequence runs: the next keys typed are replayed in the tag. +|36: 12 The tag shows `Keys` and the keys as they are typed; a sequence that reaches a leaf unrolls ↩ +|37: its level under the tag with the leaf on the cursor and its documentation beside it, and Ent↩ +|38: er runs it. Every root answers: SPC, g, m, z, Z, [, ], window mode's C-w. A sequence nothing↩ +|39: is bound to is shown struck, `runs nothing`. Esc leaves it. +|40: ✓ /tmp/pardes-snap/leader/cwd/+Tutor Del 6 messages · SPC h m == snap help-column grid=100x41 cursor=7,6 |5: /tmp/pardes-snap/leader/cwd/+Help Save Term Collapse Follow Del |6: 1 pardes builtins under SPC c @@ -158,7 +177,7 @@ |37: |38: |39: -|40: ✓ /tmp/pardes-snap/leader/cwd/+Help Del 6 messages · SPC h m +|40: ✓ /tmp/pardes-snap/leader/cwd/cmds.txt Help 14 messages · SPC h m == snap help-language grid=100x41 cursor=7,6 |6: 1 pardes builtins under SPC l |8: 3 SPC l C Callees @@ -193,6 +212,7 @@ |37: 29 SPC l h SelectRefs |38: 30 Select every reference to the symbol under the cursor. |39: 31 +|40: ✓ /tmp/pardes-snap/leader/cwd/cmds.txt Help 16 messages · SPC h m == snap del-output grid=100x41 cursor=7,3 |5: |6: @@ -229,4 +249,4 @@ |37: |38: |39: -|40: ✓ /tmp/pardes-snap/leader/cwd/+Help Del 7 messages · SPC h m +|40: ✓ /tmp/pardes-snap/leader/cwd/+Help Del 17 messages · SPC h m diff --git a/test/snapshots/ttyhelp.golden b/test/snapshots/ttyhelp.golden index 7f7413ec..200aab50 100644 --- a/test/snapshots/ttyhelp.golden +++ b/test/snapshots/ttyhelp.golden @@ -37,15 +37,31 @@ |8: from a shell. `Help <name>` shows one builtin alone; `Help <keys>` (or SPC, those keys, the↩ |9: n ?) the builtins under SPC and those keys. |10: 2 -|11: 3 SPC ? Help topbar -|12: 4 Show every builtin with its keys and documentation, or one builtin's alone. -|13: 5 `Help <name>`: that builtin alone, its keys spelled out, what it acts on and its line for a ↩ -|14: shell (`Help Diff`); a setting or an addon's word the same. `Help <keys>`: the builtins unde↩ -|15: r SPC and those keys (`Help l`, as `SPC l ?` shows them). Each fills the one +Help: a second↩ -|16: Help replaces its text. -|17: 6 -|18: 7 SPC P ClipPasteBefore -|19: 8 Paste the system clipboard before the selection. -|20: 9 +|11: 3 SPC ' Resume +|12: 4 Reopen the last picker as it was: its rows, marks, cursor and query. +|13: 5 In the tag of the pane its Enter lands in from this one: this pane if it reads, else its rea↩ +|14: der. `SPC '`. +|15: 6 +|16: 7 SPC ? Help topbar +|17: 8 Show every builtin with its keys and documentation, or one builtin's alone. +|18: 9 `Help <name>`: that builtin alone, its keys spelled out, what it acts on and its line for a ↩ +|19: shell (`Help Diff`); a setting or an addon's word the same. `Help <keys>`: the builtins unde↩ +|20: r SPC and those keys (`Help l`, as `SPC l ?` shows them). Each fills the one +Help: a second |30: ✓ @p1 Help 1 message · SPC h m -== snap leaderworks grid=100x31 cursor=7,6 +== snap leaderworks grid=100x31 cursor=47,5 +|5: ^ /tmp/pardes-snap/ttyhelp/cwd/+Help Help tutor 1/136 +|6: ▶ SPC h t · Tutor · help│ t Tutor +|7: │ Open the tutor, a document to work through. +|8: │ keys SPC h t +|9: │ +|10: 1 pardes builtins: each one's keys and its name, then what it does. Run one by its keys, or by↩ +|11: its name anywhere: B2 on the word, Exec <name>, a line of a ctl file, or `pardes do <name>`↩ +|12: from a shell. `Help <name>` shows one builtin alone; `Help <keys>` (or SPC, those keys, the↩ +|13: n ?) the builtins under SPC and those keys. +|14: 2 +|15: 3 SPC ' Resume +|16: 4 Reopen the last picker as it was: its rows, marks, cursor and query. +|17: 5 In the tag of the pane its Enter lands in from this one: this pane if it reads, else its rea↩ +|18: der. `SPC '`. +|19: 6 +|20: 7 SPC ? Help topbar |
