From abe3817e8dd0af41e6b5786bdbeb631219b58c23 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 24 Nov 2026 20:33:01 -0300 Subject: Prompt: a body's text prompts ask in its tag's head (walk UI, pick-ui SPEC.md §7.1, §7.2, item 1 of line E): `s S K A-K | A-| ! A-! $` from a body are a typing state of the view's tag (TagState.Kind.prompt, its state Prompt.zig, its field A's Field), drawn after the prefix in place of the tag's own text (R1): box `^`, the prompt's key cell, the field, the plain word it stands for (`= Exec Edit x/self/`, `Edit g/re/`, `Edit |tr a-z A-Z`, `Edit >cmd`; none for `! A-! $`), its count (`2 selections in 3 lines`, `keeps 1 of 2`, `0` for no match, the selections it began with back), the hints; the live machinery as it was (normal.applySelRegex, now returning what it found; the pipe off the loop, Pipe.submit split from the notice band's submitPipe); a pattern that is no regex changes nothing, the last result drawn dimmed (body_layer) and the reason at the count's place in the error ink (TagState.Style.err, regexp's message); Up/Down recall the history inline, Ctrl-r unrolls it as a band step filtered by the field (three session histories, Pardes.prompt_history: search and select's, the pipes', the command line's, 16 lines each, in the digest and the dump); Esc and Backspace on an empty field put the body back; Enter keeps the line in its history and the pattern in `/`, the command in `|`; a paste goes into the field; a prompt for a tag's or a header's text, Save's path, a terminal's `/` still ask on the notice band; wire 37; TEST FIRST: Prompt.zig "s asks in the tag's head ..." and "Enter keeps what s found ... a pipe from the body asks in the tag and runs off the loop"; Pipe.zig's and panes.zig's prompt tests and test/behaviour/keys.zig's two read the head; goldens pipe, selregex, msg (the prompt in the tag head, no chip); core-test 1014/1180 (166 skipped), shell-test 1227/1230, pane-test 182/184 (the 1 failure A's: `SPC h ?` is Help in the tag now), behaviour-test 274/277 (the 3 failures A's: window mode's head, a struck leader key), process-test the 6 of A's report plus none of mine, term-test 17/17, kitty-test 45/45 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- abi/wire.zig | 5 +- core/Band.zig | 8 + core/Core.zig | 3 + core/Pipe.zig | 32 ++- core/Prompt.zig | 533 +++++++++++++++++++++++++++++++++++++++++ core/TagState.zig | 13 +- core/body_layer.zig | 7 +- core/draw.zig | 1 + core/edit.zig | 9 +- core/keys.zig | 13 +- core/lib_editor.zig | 2 +- core/look.zig | 3 +- core/normal.zig | 48 ++-- core/panes.zig | 16 +- core/root.zig | 2 + test/behaviour/keys.zig | 18 +- test/daemon.py | 2 +- test/snapshots/msg.golden | 14 +- test/snapshots/pipe.golden | 6 +- test/snapshots/selregex.golden | 27 ++- 20 files changed, 685 insertions(+), 77 deletions(-) create mode 100644 core/Prompt.zig diff --git a/abi/wire.zig b/abi/wire.zig index d07e6a57..cbe255f4 100644 --- a/abi/wire.zig +++ b/abi/wire.zig @@ -10,6 +10,9 @@ const pardes = @import("core"); const config = @import("pardes_options"); const build_info = @import("build_info"); +/// 37: a view's text prompt in its tag (walk UI: `TagState.prompt`, which +/// prompt, its history's place, what its field found) and the session's +/// prompt histories (`prompt_history`) in the dump and the digest; /// 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 @@ -80,7 +83,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 = 36; +pub const version: u16 = 37; /// 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 index 079a1bcc..7f9cfc7b 100644 --- a/core/Band.zig +++ b/core/Band.zig @@ -27,6 +27,7 @@ const panes = @import("panes.zig"); const builtins = @import("builtins.zig"); const TagState = @import("TagState.zig"); const Names = @import("Names.zig"); +const Prompt = @import("Prompt.zig"); const Pardes = pardes.Pardes; const Pane = pardes.Pane; const File = panes.File; @@ -89,6 +90,7 @@ pub fn takes(p: *Pardes, id: usize) u16 { .rest => {}, .help => return @max(doc_rows, @max(1, @min(Cursor.shown, s.nhits))), .describe => return 0, + .prompt => return Prompt.takes(p), } if (!s.unrolled) return 0; const cur = TagState.current(p, v) orelse return 0; @@ -117,6 +119,12 @@ pub fn of(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, id: usize) !?Band { return band; }, .describe => return null, + .prompt => { + var steps: [max_steps]Step = undefined; + for (try Prompt.steps(p, arena, &steps)) |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 diff --git a/core/Core.zig b/core/Core.zig index 11f254ab..987c4f85 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -437,6 +437,9 @@ in_head: usize = 0, in_len: usize = 0, registers: Registers = .{}, +/// The text prompts' histories (Prompt.zig): search and select's, the +/// pipes', the command line's. +prompt_history: pardes.Prompt.History = .{}, macro: Macro = .{}, /// an edited text nothing kept (a tag's shown text): see edit.retireEditText retired_edit: ?[]u8 = null, diff --git a/core/Pipe.zig b/core/Pipe.zig index 012ce689..70d551d0 100644 --- a/core/Pipe.zig +++ b/core/Pipe.zig @@ -88,14 +88,10 @@ pub const PendingPipe = struct { } }; +/// The notice band's pipe prompt answered (a tag's text, a header's). pub fn submitPipe(p: *Pardes, id: usize) void { const pane = p.panes[id] orelse return; const t = panes.promptTarget(p, pane) orelse return; - if (t.what == .body) { - const f = pane.file orelse return; - if (!panes.Output.fileTraits(f.output).saves) return; - } - const content = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(.at(id), "pipe", err); const how = switch (pane.prompt) { .pipe => |pipe| pipe, else => return, @@ -103,7 +99,18 @@ pub fn submitPipe(p: *Pardes, id: usize) void { const armed = pane.promptText() orelse return; const marker = pipeMarker(how); if (!std.mem.startsWith(u8, armed, marker)) return; - const command = armed[marker.len..]; + submit(p, id, t, how, armed[marker.len..]); +} + +/// Pipe text `t` of pane `id` through `command`, `how` says: one run per +/// selection, off the loop. +pub fn submit(p: *Pardes, id: usize, t: *Text, how: modal.Normal.PipeBehavior, command: []const u8) void { + const pane = p.panes[id] orelse return; + if (t.what == .body) { + const f = pane.file orelse return; + if (!panes.Output.fileTraits(f.output).saves) return; + } + const content = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(.at(id), "pipe", err); if (command.len == 0) return; var ranges: [panes.Text.max_selections]modal.Selection = undefined; @@ -344,12 +351,11 @@ test "selection pipe prompt submits exact request and Escape cancels" { pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; p.update(.{ .key = .{ .cp = '|' } }); - try std.testing.expect(pane.focus == .body and pane.prompt == .pipe); - try std.testing.expectEqualStrings(config.pipe_marker, pane.promptText().?); + try std.testing.expect(pane.focus == .body and p.view().tag_state.kind == .prompt); try std.testing.expect(nextPipeEffect(p) == null); p.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); p.update(.{ .key = .{ .cp = Key.enter } }); - try std.testing.expect(pane.focus == .body and pane.prompt != .pipe and pane.input.own == null); + try std.testing.expect(pane.focus == .body and p.view().tag_state.kind == .rest); const id = nextPipeEffect(p) orelse return error.MissingPipeEffect; const request = p.pipe.pipeRequest(id) orelse return error.MissingPipeRequest; try std.testing.expectEqualStrings("tr a-z A-Z", request.command); @@ -361,7 +367,7 @@ test "selection pipe prompt submits exact request and Escape cancels" { p.update(.{ .key = .{ .cp = '|' } }); p.update(.{ .key = .{ .cp = 'c', .text = "cat" } }); p.update(.{ .key = .{ .cp = Key.escape } }); - try std.testing.expect(pane.focus == .body and pane.prompt != .pipe); + try std.testing.expect(pane.focus == .body and p.view().tag_state.kind == .rest); try std.testing.expectEqualSlices(u8, before, pane.file.?.content); try std.testing.expect(nextPipeEffect(p) == null); } @@ -404,7 +410,7 @@ test "$ keeps the selections the command exits 0 on, and a real shell gives that }; pane.body.setRanges(config.tab_width, pane.file.?.content, &ranges, &.{}, 1, true); p.update(.{ .key = .{ .cp = '$' } }); - try std.testing.expectEqualStrings(config.pipe_marker_keep, pane.promptText().?); + try std.testing.expectEqual(pardes.Prompt.Op.keep_pipe, p.view().tag_state.prompt.op); p.update(.{ .key = .{ .cp = 'g', .text = "grep -v b" } }); p.update(.{ .key = .{ .cp = Key.enter } }); const id = nextPipeEffect(p) orelse return error.MissingPipeEffect; @@ -663,10 +669,10 @@ test "selection pipe binding is file-normal-only" { pane.file.?.output = .{ .from = .search }; p.update(.{ .key = .{ .cp = '|' } }); - try std.testing.expect(pane.prompt != .pipe); + try std.testing.expect(p.view().tag_state.kind != .prompt); pane.file.?.output = null; pane.body.mode = .insert; p.update(.{ .key = .{ .cp = '|', .text = "|" } }); - try std.testing.expect(pane.prompt != .pipe); + try std.testing.expect(p.view().tag_state.kind != .prompt); try std.testing.expectEqualSlices(u8, "|x", pane.file.?.content); } diff --git a/core/Prompt.zig b/core/Prompt.zig new file mode 100644 index 00000000..e5fac06c --- /dev/null +++ b/core/Prompt.zig @@ -0,0 +1,533 @@ +//! A text prompt in a pane's tag (walk UI, pick-ui SPEC.md §7): `s S K A-K` +//! select by a pattern, `| A-| ! A-! $` pipe through a command, typed in +//! the head's field after the prompt's key cell, the plain word it stands +//! for and its count beside it (`s self = Exec Edit x/self/ 4 selections in +//! 6 lines`), its effect drawn live in the body on every key; Enter applies +//! it and keeps the line in its history, Esc puts the body back. +//! +//! A view's own (TagState.prompt, the coordinator's R4): its field the +//! head's (TagState.field); its histories the session's, three of them +//! (`/ ? s S K A-K` share one, the pipes another, `:` its own). A prompt for +//! a tag's text or a header's still asks on the notice band (panes.zig +//! startPrompt), as does Save's. +const Prompt = @This(); + +const std = @import("std"); +const pardes = @import("root.zig"); +const config = @import("config.zig"); +const modal = @import("modal.zig"); +const panes = @import("panes.zig"); +const normal = @import("normal.zig"); +const edit = @import("edit.zig"); +const regexp = @import("regexp.zig"); +const tagline = @import("tagline.zig"); +const Pipe = @import("Pipe.zig"); +const Field = @import("Field.zig"); +const Band = @import("Band.zig"); +const TagState = @import("TagState.zig"); +const Kind = @import("Kind.zig"); +const Pardes = pardes.Pardes; +const Pane = panes.Pane; +const Text = panes.Text; +const Key = pardes.Key; +const hit = pardes.hit; + +pub const Op = enum(u8) { search, search_back, select, split, keep, remove, pipe, pipe_to, insert, append, keep_pipe, command }; + +op: Op = .select, +/// Up and Down's place in its history: 0 the field as typed, n the n-th +/// newest line. +recall: u8 = 0, +/// Ctrl-r: its history unrolled under the tag, filtered by the field. +history: bool = false, +/// The field is no regex: the body keeps the last result, dimmed, and the +/// count says why. +bad: bool = false, +/// The ranges the last pattern found (0: none, the selections it started +/// from back), and the lines those it started from cover. +found: u16 = 0, +scope: u32 = 0, + +/// The session's prompt histories: the lines Enter took, newest last. +pub const History = struct { + search: Ring = .{}, + pipe: Ring = .{}, + command: Ring = .{}, +}; + +pub const Ring = struct { + pub const replica = .{ .len = .{.{ "lines", "n" }} }; + /// The lines a history keeps; past it the oldest goes. + pub const max = 16; + lines: [max]Kind.Buf(Field.max) = undefined, + n: u8 = 0, + + /// `line` the newest, an older copy of it gone. + pub fn add(r: *Ring, line: []const u8) void { + if (line.len == 0) return; + var w: u8 = 0; + for (r.lines[0..r.n]) |l| if (!std.mem.eql(u8, l.slice(), line)) { + r.lines[w] = l; + w += 1; + }; + r.n = w; + if (r.n == max) { + std.mem.copyForwards(Kind.Buf(Field.max), r.lines[0 .. max - 1], r.lines[1..]); + r.n -= 1; + } + r.lines[r.n].set(line); + r.n += 1; + } + + /// The `back`-th newest line, 1 the newest. + pub fn get(r: *const Ring, back: u8) ?[]const u8 { + if (back == 0 or back > r.n) return null; + return r.lines[r.n - back].slice(); + } +}; + +const Info = struct { + /// Its key cell. + cell: []const u8, + hint: []const u8, +}; + +const info = std.EnumArray(Op, Info).init(.{ + .search = .{ .cell = "/", .hint = "⏎ land · C-r history · esc" }, + .search_back = .{ .cell = "?", .hint = "⏎ land · C-r history · esc" }, + .select = .{ .cell = "s", .hint = "⏎ select · C-r history · esc" }, + .split = .{ .cell = "S", .hint = "⏎ select · C-r history · esc" }, + .keep = .{ .cell = "K", .hint = "⏎ keep · C-r history · esc" }, + .remove = .{ .cell = "A-K", .hint = "⏎ keep · C-r history · esc" }, + .pipe = .{ .cell = "|", .hint = "⏎ replace · C-r history · esc" }, + .pipe_to = .{ .cell = "A-|", .hint = "⏎ run · C-r history · esc" }, + .insert = .{ .cell = "!", .hint = "⏎ insert · C-r history · esc" }, + .append = .{ .cell = "A-!", .hint = "⏎ append · C-r history · esc" }, + .keep_pipe = .{ .cell = "$", .hint = "⏎ keep · C-r history · esc" }, + .command = .{ .cell = ":", .hint = "⏎ run · C-r history · esc" }, +}); + +/// The history `op` reads and Enter adds to. +fn ring(p: *Pardes, op: Op) *Ring { + return switch (op) { + .search, .search_back, .select, .split, .keep, .remove => &p.prompt_history.search, + .pipe, .pipe_to, .insert, .append, .keep_pipe => &p.prompt_history.pipe, + .command => &p.prompt_history.command, + }; +} + +pub fn ofMode(m: modal.Normal.RegexMode) Op { + return switch (m) { + .select => .select, + .split => .split, + .keep => .keep, + .remove => .remove, + }; +} + +fn mode(op: Op) ?modal.Normal.RegexMode { + return switch (op) { + .select => .select, + .split => .split, + .keep => .keep, + .remove => .remove, + else => null, + }; +} + +pub fn ofBehavior(how: modal.Normal.PipeBehavior) Op { + return switch (how) { + .replace => .pipe, + .ignore => .pipe_to, + .insert => .insert, + .append => .append, + .keep => .keep_pipe, + }; +} + +fn behavior(op: Op) ?modal.Normal.PipeBehavior { + return switch (op) { + .pipe => .replace, + .pipe_to => .ignore, + .insert => .insert, + .append => .append, + .keep_pipe => .keep, + else => null, + }; +} + +/// Prompt `op` in the tag of `pane`, the pane with the keyboard, for its +/// body: its field empty, the body's selections as they are (`s S K A-K` +/// select inside them, Esc puts them back). +pub fn open(p: *Pardes, pane: *Pane, op: Op) void { + // Nobody is at the keyboard to answer a command a script wrote to a + // ctl file: the write fails instead (core/ninep/ctl.zig). + if (p.fs.no_prompt) { + p.fs.refused = true; + p.fs.failures +%= 1; + return; + } + const t = &pane.body; + // A body is piped only when it is a file that saves. + if (behavior(op) != null) { + const f = pane.file orelse return; + if (!panes.Output.fileTraits(f.output).saves) return; + } + var scope: u32 = 0; + if (mode(op) != null) { + const text = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(.at(p.view().active), "prompt", err); + const got = t.ranges(text, 0, &pane.sel_snap); + pane.nsel_snap = @intCast(got.n); + pane.sel_snap_pri = @intCast(got.pri); + pane.sel_snap_expl = t.vsel.active and t.vsel.explicit; + for (pane.sel_snap[0..got.n]) |r| { + const lo = @min(r.anchor, r.head, text.len); + const hi = @min(@max(r.anchor, r.head), text.len); + scope += @intCast(std.mem.count(u8, text[lo..hi -| @intFromBool(hi > lo and text[hi - 1] == '\n')], "\n") + 1); + } + } + pane.focus = .body; + tagline.exitHeader(p); + t.mode = .normal; + t.normal.clear(); + TagState.toRest(p); + const s = &p.view().tag_state; + s.kind = .prompt; + s.host = pane.serial; + s.field.clear(); + s.rows = .{}; + s.prompt = .{ .op = op, .scope = scope }; +} + +/// A key in the prompt of the live view's tag: the field's editing keys, +/// and the prompt's own. +pub fn key(p: *Pardes, k: Key) void { + const v = p.view(); + const s = &v.tag_state; + const id = TagState.hostOf(p) orelse return TagState.toRest(p); + const pane = p.panes[id].?; + const plain = !k.ctrl and !k.alt; + const ctrl = k.ctrl and !k.alt; + if (hit(k, config.escape)) return cancel(p, pane); + if (plain and k.cp == Key.enter) return commit(p, id, pane); + // Backspace on an empty field: the prompt goes, as Esc. + if (plain and k.cp == Key.backspace and s.field.len == 0) return cancel(p, pane); + // Up and Down bring its history's lines into the field, the newest first. + if (plain and (k.cp == Key.up or k.cp == Key.down)) { + const r = ring(p, s.prompt.op); + const to: u8 = if (k.cp == Key.up) @min(r.n, s.prompt.recall + 1) else s.prompt.recall -| 1; + if (to == s.prompt.recall) return; + s.prompt.recall = to; + s.field.set(r.get(to) orelse ""); + return live(p, pane); + } + if (ctrl and k.cp == 'r') { + s.prompt.history = !s.prompt.history; + return; + } + if (!s.field.key(k)) return; + s.prompt.recall = 0; + live(p, pane); +} + +/// What the field says now, done to the body: the selections a pattern +/// finds inside the ones the prompt began with; none, or no pattern, those +/// it began with. A pattern that is no regex changes nothing, and the +/// prompt says why. +fn live(p: *Pardes, pane: *Pane) void { + const s = &p.view().tag_state; + const m = mode(s.prompt.op) orelse return; + const pat = s.field.text(); + s.prompt.bad = pat.len > 0 and if (regexp.Regex.compile(pat)) |_| false else |_| true; + if (s.prompt.bad) return; + s.prompt.found = @intCast(normal.applySelRegex(p, pane, &pane.body, pat, m)); +} + +/// Enter: what the field says, applied, and the line kept in its history +/// and its register (`/` a pattern's, `|` a command's). +fn commit(p: *Pardes, id: usize, pane: *Pane) void { + const s = &p.view().tag_state; + const op = s.prompt.op; + const line = s.field.text(); + // The field is the view's: what is kept of it is copied before rest. + var kept: [Field.max]u8 = undefined; + @memcpy(kept[0..line.len], line); + const typed = kept[0..line.len]; + const bad = s.prompt.bad; + s.kind = .rest; + TagState.toRest(p); + if (typed.len == 0) return undo(p, pane, op); + ring(p, op).add(typed); + if (mode(op) != null) { + // No regex: the selections it began with, and why. + if (bad) { + undo(p, pane, op); + return p.setMessage(.at(id), regexMessage(typed)); + } + // helix keeps the pattern in `/` + p.registers.put(p.gpa, '/', typed, 0, 1, true) catch |err| return p.reportError(.at(id), "prompt", err); + p.registers.last_search = '/'; + return; + } + if (behavior(op)) |how| { + p.registers.put(p.gpa, '|', typed, 0, 1, true) catch |err| return p.reportError(.at(id), "prompt", err); + return Pipe.submit(p, id, &pane.body, how, typed); + } +} + +/// Esc: the prompt goes and the body is as it was before it. +fn cancel(p: *Pardes, pane: *Pane) void { + const op = p.view().tag_state.prompt.op; + p.view().tag_state.kind = .rest; + TagState.toRest(p); + undo(p, pane, op); +} + +/// The live effect of prompt `op` on `pane`'s body taken back. +fn undo(p: *Pardes, pane: *Pane, op: Op) void { + if (mode(op)) |m| _ = normal.applySelRegex(p, pane, &pane.body, "", m); + pane.nsel_snap = 0; +} + +/// The prompt left by something else than its keys (TagState.toRest: a +/// click, a word run from the band): its effect taken back, as Esc's. +pub fn leave(p: *Pardes) void { + const s = &p.view().tag_state; + const pane = p.panes[TagState.hostOf(p) orelse return] orelse return; + s.kind = .rest; + undo(p, pane, s.prompt.op); +} + +/// A paste into the field: its first line. +pub fn paste(p: *Pardes, bytes: []const u8) void { + const s = &p.view().tag_state; + const pane = p.panes[TagState.hostOf(p) orelse return] orelse return; + const line = bytes[0 .. std.mem.indexOfAny(u8, bytes, "\r\n") orelse bytes.len]; + s.field.insert(line[0..modal.graphemeStart(line, @min(line.len, Field.max - s.field.len))]); + s.prompt.recall = 0; + live(p, pane); +} + +/// Whether `pane`'s body shows a selecting prompt's live result: its +/// selections drawn as a preview (body_layer), dimmed while the field is +/// no regex. +pub fn selecting(p: *const Pardes, pane: *const Pane) ?struct { dim: bool } { + const s = &p.view().tag_state; + if (s.kind != .prompt or mode(s.prompt.op) == null or s.host != pane.serial) return null; + return .{ .dim = s.prompt.bad }; +} + +fn regexMessage(pat: []const u8) []const u8 { + return if (regexp.Regex.compile(pat)) |_| "" else |err| regexp.Regex.message(err); +} + +/// The sam command a pattern prompt is (`s S K A-K` are sam's `x y g v`), +/// its `/` written `\/`. +fn samWord(w: *std.Io.Writer, c: u8, pat: []const u8) !void { + try w.print("{c}/", .{c}); + for (pat) |b| if (b == '/') try w.writeAll("\\/") else try w.writeByte(b); + try w.writeByte('/'); +} + +/// The plain word prompt `op` with field `line` stands for: what Look or +/// Exec would do typed in a tag. None for `! A-! $`, which sam cannot say. +fn plainWord(w: *std.Io.Writer, op: Op, line: []const u8) !?[]const u8 { + switch (op) { + .search => try w.print("/{s}/", .{line}), + .search_back => try w.print("?{s}?", .{line}), + .select, .split, .keep, .remove => { + try w.writeAll("Edit "); + try samWord(w, switch (op) { + .select => 'x', + .split => 'y', + .keep => 'g', + else => 'v', + }, line); + }, + .pipe => try w.print("Edit |{s}", .{line}), + .pipe_to => try w.print("Edit >{s}", .{line}), + .insert, .append, .keep_pipe => return null, + .command => try w.writeAll(line), + } + return if (op == .search or op == .search_back) "Look" else "Exec"; +} + +/// The head of the prompt's tag: ` s self▌ = Exec Edit x/self/ 4 +/// selections in 6 lines ⏎ select · C-r history · esc`. +pub fn head(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) !TagState.Head { + const s = &p.view().tag_state; + const pr = &s.prompt; + var text: std.ArrayList(u8) = .empty; + var spans: std.ArrayList(TagState.Span) = .empty; + try text.append(arena, ' '); + try styled(arena, &text, &spans, info.get(pr.op).cell, .key); + try text.append(arena, ' '); + const caret: u32 = @intCast(text.items.len + s.field.caret); + const line = s.field.text(); + try text.appendSlice(arena, line); + if (line.len > 0) { + var buf: [Field.max + 16]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + if (plainWord(&w, pr.op, line) catch null) |verb| { + try styled(arena, &text, &spans, try std.fmt.allocPrint(arena, " = {s}", .{verb}), .dim); + try text.print(arena, " {s}", .{w.buffered()}); + } + if (pr.bad) { + try text.appendSlice(arena, " "); + try styled(arena, &text, &spans, regexMessage(line), .err); + try text.print(arena, " · the {d} from before shown, dimmed", .{@as(usize, pane.body.nsel) + 1}); + } else try count(arena, &text, pane, pr); + } + try text.appendSlice(arena, " "); + try styled(arena, &text, &spans, info.get(pr.op).hint, .dim); + return .{ .text = text.items, .spans = spans.items, .cells = 1, .caret = caret }; +} + +fn styled(arena: std.mem.Allocator, text: *std.ArrayList(u8), spans: *std.ArrayList(TagState.Span), s: []const u8, style: TagState.Style) !void { + const lo: u32 = @intCast(text.items.len); + try text.appendSlice(arena, s); + try spans.append(arena, .{ .lo = lo, .hi = @intCast(text.items.len), .style = style }); +} + +/// The prompt's count after its field: what it found (`4 selections in 6 +/// lines`, `keeps 3 of 9`, `0`). +fn count(arena: std.mem.Allocator, text: *std.ArrayList(u8), pane: *const Pane, pr: *const Prompt) !void { + switch (pr.op) { + .select, .split => if (pr.found == 0) + try text.appendSlice(arena, " 0") + else + try text.print(arena, " {d} selection{s} in {d} line{s}", .{ pr.found, plural(pr.found), pr.scope, plural(pr.scope) }), + .keep, .remove => try text.print(arena, " keeps {d} of {d}", .{ pr.found, pane.nsel_snap }), + else => {}, + } +} + +fn plural(n: usize) []const u8 { + return if (n == 1) "" else "s"; +} + +/// The rows the prompt's band takes: its history unrolled (Ctrl-r), the +/// lines the field is in, eleven at most. +pub fn takes(p: *Pardes) u16 { + const s = &p.view().tag_state; + if (!s.prompt.history) return 0; + var n: u16 = 0; + const r = ring(p, s.prompt.op); + for (r.lines[0..r.n]) |l| { + if (std.mem.indexOf(u8, l.slice(), s.field.text()) != null) n += 1; + } + return @max(1, @min(Band.Cursor.shown, n)); +} + +/// The prompt's steps in its band: its history, newest first, the lines +/// holding the field, the one Up recalled on. +pub fn steps(p: *Pardes, arena: std.mem.Allocator, out: *[Band.max_steps]Band.Step) ![]Band.Step { + const s = &p.view().tag_state; + if (!s.prompt.history) return out[0..0]; + const r = ring(p, s.prompt.op); + var rows: std.ArrayList(Band.Row) = .empty; + const q = s.field.text(); + var back: u8 = 1; + while (back <= r.n and rows.items.len < Band.Cursor.shown) : (back += 1) { + const l = r.get(back).?; + if (std.mem.indexOf(u8, l, q) == null) continue; + try rows.append(arena, .{ .text = l, .on = back == s.prompt.recall, .index = back }); + } + if (rows.items.len == 0) try rows.append(arena, .{ .text = if (r.n == 0) "no history yet" else "no line holds it", .dim = true }); + out[0] = .{ .rows = rows.items }; + return out[0..1]; +} + +fn typeKeys(p: *Pardes, keys: []const u8) void { + for (keys) |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); +} + +fn tagOf(p: *Pardes) ![]const u8 { + return tagline.tagText(p, p.scratch.allocator(), p.panes[p.view().active].?); +} + +fn has(hay: []const u8, needle: []const u8) bool { + return std.mem.indexOf(u8, hay, needle) != null; +} + +test "s asks in the tag's head: its key cell, the field, the plain word and the count, the selections live in the body; no match is 0, a pattern that is no regex keeps the last result dimmed and says why, Esc puts them back" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 200, .rows = 30 }); + defer p.deinit(); + const pane = try p.setTestFile("self.a = 1;\nself.b = 2;\nother = 3;\n"); + const rest = try std.testing.allocator.dupe(u8, try tagOf(p)); + defer std.testing.allocator.free(rest); + typeKeys(p, "%s"); + try std.testing.expectEqual(TagState.Kind.prompt, p.view().tag_state.kind); + // No chip on the notice band: the prompt is the tag's. + try std.testing.expectEqual(Pane.Prompt.none, pane.prompt); + try std.testing.expect(std.mem.endsWith(u8, try tagOf(p), " s ⏎ select · C-r history · esc")); + typeKeys(p, "self"); + try std.testing.expect(has(try tagOf(p), " s self = Exec Edit x/self/ 2 selections in 3 lines ⏎ select")); + try std.testing.expectEqual(@as(u16, 1), pane.body.nsel); + try std.testing.expect(selecting(p, pane).?.dim == false); + // No match: 0, and the selection it began with. + typeKeys(p, "x"); + try std.testing.expect(has(try tagOf(p), "= Exec Edit x/selfx/ 0 ")); + try std.testing.expectEqual(@as(u16, 0), pane.body.nsel); + p.update(.{ .key = .{ .cp = Key.backspace } }); + try std.testing.expectEqual(@as(u16, 1), pane.body.nsel); + // No regex: the two from before, dimmed, and why. + typeKeys(p, "("); + try std.testing.expect(has(try tagOf(p), " bad regular expression · the 2 from before shown, dimmed ")); + try std.testing.expectEqual(@as(u16, 1), pane.body.nsel); + try std.testing.expect(selecting(p, pane).?.dim); + // Esc: rest, the tag and the selection as they were. + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expectEqual(TagState.Kind.rest, p.view().tag_state.kind); + try std.testing.expectEqualStrings(rest, try tagOf(p)); + try std.testing.expectEqual(@as(u16, 0), pane.body.nsel); + const r = pane.body.primaryRange(pane.file.?.content, 0); + try std.testing.expectEqual(pane.file.?.content.len, @max(r.anchor, r.head)); + try std.testing.expect(selecting(p, pane) == null); +} + +test "Enter keeps what s found, the pattern in / and in the history Up brings back; K keeps, counted; a pipe from the body asks in the tag and runs off the loop" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 200, .rows = 30 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = try p.setTestFile("self.a = 1;\nself.b = 2;\nother = 3;\n"); + typeKeys(p, "%sself.."); + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expectEqual(TagState.Kind.rest, p.view().tag_state.kind); + try std.testing.expectEqual(@as(u16, 1), pane.body.nsel); + try std.testing.expectEqualStrings("self..", p.registers.value('/', 0).?); + try std.testing.expectEqualStrings("self..", p.prompt_history.search.get(1).?); + // K over the two: Up brings `self..` back, `b` keeps one of them. + typeKeys(p, "K"); + p.update(.{ .key = .{ .cp = Key.up } }); + try std.testing.expectEqualStrings("self..", p.view().tag_state.field.text()); + try std.testing.expect(has(try tagOf(p), " K self.. = Exec Edit g/self../ keeps 2 of 2")); + p.update(.{ .key = .{ .cp = Key.down } }); + typeKeys(p, "b"); + try std.testing.expect(has(try tagOf(p), " K b = Exec Edit g/b/ keeps 1 of 2 ⏎ keep")); + // Ctrl-r: the history under the tag, a row a line. + p.update(.{ .key = .{ .cp = 'r', .ctrl = true } }); + try std.testing.expectEqual(@as(u16, 1), Band.takes(p, p.view().active)); + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expectEqual(@as(u16, 0), pane.body.nsel); + try std.testing.expectEqualStrings("b", p.prompt_history.search.get(1).?); + try std.testing.expectEqualStrings("self..", p.prompt_history.search.get(2).?); + // | from the body: in the tag, the plain word Edit's, Enter pipes. + typeKeys(p, "|"); + try std.testing.expectEqual(Pane.Prompt.none, pane.prompt); + p.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); + try std.testing.expect(has(try tagOf(p), " | tr a-z A-Z = Exec Edit |tr a-z A-Z ⏎ replace")); + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expectEqualStrings("tr a-z A-Z", p.registers.value('|', 0).?); + var asked: ?u32 = null; + while (p.nextEffect()) |effect| if (effect == .pipe) { + asked = effect.pipe.id; + }; + const request = p.pipe.pipeRequest(asked orelse return error.MissingPipeEffect).?; + try std.testing.expectEqualStrings("tr a-z A-Z", request.command); + try std.testing.expectEqualSlices(u8, "self.b", request.inputs[0]); + // Esc in a pipe's prompt runs nothing. + typeKeys(p, "|cat"); + p.update(.{ .key = .{ .cp = Key.escape } }); + while (p.nextEffect()) |effect| try std.testing.expect(effect != .pipe); +} diff --git a/core/TagState.zig b/core/TagState.zig index 56c715af..716704b7 100644 --- a/core/TagState.zig +++ b/core/TagState.zig @@ -24,11 +24,13 @@ const Root = bindings.Root; const Field = @import("Field.zig"); const Band = @import("Band.zig"); const Names = @import("Names.zig"); +const Prompt = @import("Prompt.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). -pub const Kind = enum(u8) { rest, help, describe }; +/// a sequence replayed in the tree (item 5); `prompt`, a text prompt +/// (Prompt.zig, SPEC §7). +pub const Kind = enum(u8) { rest, help, describe, prompt }; pub const replica = .{ .len = .{ .{ "scope", "scope_n" }, .{ "hits", "nhits" } } }; @@ -52,6 +54,9 @@ nhits: u16 = 0, ntotal: u16 = 0, /// The rows' cursor (Band.Cursor). rows: Band.Cursor = .{}, +/// A text prompt's own (Prompt.zig): which, its history's place, what its +/// field found. +prompt: Prompt = .{}, /// 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 @@ -155,6 +160,7 @@ pub fn toRest(p: *Pardes) void { pane.tag.normal.clear(); } const s = &v.tag_state; + if (s.kind == .prompt) Prompt.leave(p); s.kind = .rest; s.previewing = .empty; s.root = null; @@ -312,7 +318,7 @@ pub fn helpLeaf(p: *const Pardes, at: u16, buf: *[row_max]u8) Leaf { } /// How a span of the head is drawn (draw.zig paintPaneTag). -pub const Style = enum { key, dim, under, strike }; +pub const Style = enum { key, dim, under, strike, err }; 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. @@ -378,6 +384,7 @@ pub fn head(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) !?Head { return h; }, .describe => return null, + .prompt => return try Prompt.head(p, arena, pane), } const cur = current(p, v) orelse return null; try b.put(" "); diff --git a/core/body_layer.zig b/core/body_layer.zig index 9c4a4c73..4176514b 100644 --- a/core/body_layer.zig +++ b/core/body_layer.zig @@ -379,7 +379,10 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane if (b == pardes.sel_slot and @min(sl.r0, sl.r1) < pane.tag_rows) continue; paintPointerSelection(p, s, pane, r, sl, pane.tag_rows, sel_btn[b], buttonInks(th)[b]); } - const preview = normal.selRegexArmed(pane) != null; + // A selecting prompt's live result (Prompt.zig), dimmed while its + // field is no regex. + const selecting = pardes.Prompt.selecting(p, pane); + const preview = normal.selRegexArmed(pane) != null or selecting != null; const show_prim = (pane.body.mode == .normal and pane.body.vsel.active) or preview or (modal_hover and pane.body.vsel.active); const show_extra = pane.body.mode != .tty and pane.body.nsel > 0; @@ -397,7 +400,7 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane } else pane.body.sels[si]; const bnd = edit.cellBounds(sr); const hover_only = primary and modal_hover and pane.body.mode != .normal and !preview; - const bg = if (hover_only) + const bg = if (hover_only or (selecting != null and selecting.?.dim)) colors.mix(page_rgb, colors.mix(page_rgb, th.sel_bg)) else if (primary) th.sel_bg diff --git a/core/draw.zig b/core/draw.zig index bc606f02..3365f0a8 100644 --- a/core/draw.zig +++ b/core/draw.zig @@ -1002,6 +1002,7 @@ fn paintPaneTag(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, .dim => style.dim = true, .under => style.ul = .single, .strike => style.strikethrough = true, + .err => style.fg = .{ .rgb = chrome.diagnostic_error }, } } } diff --git a/core/edit.zig b/core/edit.zig index 8ed7752e..6c0ba02b 100644 --- a/core/edit.zig +++ b/core/edit.zig @@ -124,6 +124,11 @@ pub fn applyPaste(p: *Pardes, whole: []const u8) Error!void { var said: pardes.Kind.Buf(96) = .{}; p.setMessage(.at(v.active), said.print("paste cut at its limit, {d} KiB: the rest left out", .{limit / 1024})); } + // A text prompt in a tag takes it into its field (Prompt.zig). + if (v.tag_state.kind == .prompt) { + v.clip_pending = null; + return pardes.Prompt.paste(p, bytes); + } // A prompt answering for a header takes the paste, as it takes keys. const asking = if (p.panes[v.active]) |active| active.prompt != .none else false; if (!asking) if (tagline.focusedHeader(p)) |t| { @@ -146,7 +151,9 @@ pub fn applyPaste(p: *Pardes, whole: []const u8) Error!void { n += 1; }; if (n > 0) try insertKey(p.editor(), &pane.input, .{ .cp = line[0], .text = line[0..n] }); - if (normal.selRegexArmed(pane)) |a| if (panes.promptTarget(p, pane)) |t| normal.applySelRegex(p, pane, t, a.pat, a.mode); + if (normal.selRegexArmed(pane)) |a| if (panes.promptTarget(p, pane)) |t| { + _ = normal.applySelRegex(p, pane, t, a.pat, a.mode); + }; return; } if (pane.focus == .tag) return pasteInto(p, &pane.tag, bytes); diff --git a/core/keys.zig b/core/keys.zig index 6f43e166..6ffca8e1 100644 --- a/core/keys.zig +++ b/core/keys.zig @@ -20,6 +20,7 @@ const Pipe = @import("Pipe.zig"); const Registers = @import("Registers.zig"); const bindings = @import("bindings.zig"); const TagState = @import("TagState.zig"); +const Prompt = @import("Prompt.zig"); const Pardes = pardes.Pardes; const Pane = panes.Pane; const Text = panes.Text; @@ -360,8 +361,9 @@ pub fn handleKey(p: *Pardes, key: Key) void { .save => if (submit) exec.submitSave(p, p.view().active), .search => if (submit) look.submitSearch(p, p.view().active) - else if (normal.selRegexArmed(pane)) |_| if (target) |answered| - normal.applySelRegex(p, pane, answered, "", .select), + else if (normal.selRegexArmed(pane)) |_| if (target) |answered| { + _ = normal.applySelRegex(p, pane, answered, "", .select); + }, .none, .del_side, .repl_choice, .name => unreachable, } pane.closePrompt(); @@ -372,7 +374,9 @@ pub fn handleKey(p: *Pardes, key: Key) void { return; } edit.handleInsert(p.editor(), &pane.input, key); - if (normal.selRegexArmed(pane)) |a| if (panes.promptTarget(p, pane)) |answered| normal.applySelRegex(p, pane, answered, a.pat, a.mode); + 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) { @@ -549,9 +553,10 @@ fn leaderTake(p: *Pardes, c: u8) void { fn tagStateKey(p: *Pardes, key: Key) void { const v = p.view(); const s = &v.tag_state; + if (s.kind == .prompt) return Prompt.key(p, key); if (TagState.hostOf(p) == null or hit(key, config.escape)) return TagState.toRest(p); switch (s.kind) { - .rest => unreachable, + .rest, .prompt => unreachable, .describe => return TagState.toRest(p), .help => { const plain = !key.ctrl and !key.alt; diff --git a/core/lib_editor.zig b/core/lib_editor.zig index 3e4a1f15..e5c160ed 100644 --- a/core/lib_editor.zig +++ b/core/lib_editor.zig @@ -370,7 +370,7 @@ pub fn Editor(comptime cap: Capacity) type { } var snap: [max_selections]Selection = undefined; const got = t.ranges(t.own.?, 0, &snap); - normal.selectByRegex(live.context(a), t, snap[0..got.n], got.pri, t.vsel.active and t.vsel.explicit, pattern, how); + _ = normal.selectByRegex(live.context(a), t, snap[0..got.n], got.pri, t.vsel.active and t.vsel.explicit, pattern, how); return ed.keep(a, live, .done); } diff --git a/core/look.zig b/core/look.zig index cc3e750f..d7dd7690 100644 --- a/core/look.zig +++ b/core/look.zig @@ -390,7 +390,8 @@ pub fn submitSearch(p: *Pardes, id: usize) void { p.registers.put(p.gpa, '/', a.pat, 0, 1, true) catch |err| return p.reportError(.at(id), "search", err); p.registers.last_search = '/'; } - return if (panes.promptTarget(p, pane)) |t| normal.applySelRegex(p, pane, t, a.pat, a.mode); + if (panes.promptTarget(p, pane)) |t| _ = normal.applySelRegex(p, pane, t, a.pat, a.mode); + return; } const armed = pane.promptText() orelse return; const slash = std.mem.indexOfScalar(u8, armed, '/') orelse return; diff --git a/core/normal.zig b/core/normal.zig index 1f7ce1a7..c59a847c 100644 --- a/core/normal.zig +++ b/core/normal.zig @@ -22,6 +22,7 @@ const sel_slot = pardes.sel_slot; const Pardes = pardes.Pardes; const Macro = pardes.Macro; const Editor = @import("Editor.zig"); +const Prompt = @import("Prompt.zig"); fn isPrefix(key: Key, cp: u21) bool { return key.cp == cp and !key.ctrl and !key.alt; @@ -53,15 +54,19 @@ pub fn selRegexArmed(pane: *Pane) ?struct { pat: []const u8, mode: modal.Normal. /// Select (or split on, keep or remove by) `pat` inside the selections `t` /// had when s/S/K/Alt-K was pressed; the prompt's snapshot of them lives on -/// `pane`. -pub fn applySelRegex(p: *Pardes, pane: *Pane, t: *Text, pat: []const u8, mode: modal.Normal.RegexMode) void { - selectByRegex(p.editor(), t, pane.sel_snap[0..pane.nsel_snap], pane.sel_snap_pri, pane.sel_snap_expl, pat, mode); +/// `pane`. The ranges it found: none, the snapshot's back. +pub fn applySelRegex(p: *Pardes, pane: *Pane, t: *Text, pat: []const u8, mode: modal.Normal.RegexMode) usize { + return selectByRegex(p.editor(), t, pane.sel_snap[0..pane.nsel_snap], pane.sel_snap_pri, pane.sel_snap_expl, pat, mode); } /// Select (or split on, keep or remove by) `pat` inside `snap`, the -/// ranges there were (primary `pri`) when s/S/K/Alt-K was pressed. -pub fn selectByRegex(e: Editor, t: *Text, snap: []modal.Selection, pri: usize, expl: bool, pat: []const u8, mode: modal.Normal.RegexMode) void { - const text = edit.flatSurface(e, t) catch |err| return e.reportError(err); +/// ranges there were (primary `pri`) when s/S/K/Alt-K was pressed; the +/// ranges it found. +pub fn selectByRegex(e: Editor, t: *Text, snap: []modal.Selection, pri: usize, expl: bool, pat: []const u8, mode: modal.Normal.RegexMode) usize { + const text = edit.flatSurface(e, t) catch |err| { + e.reportError(err); + return 0; + }; var out: [Text.max_selections]modal.Selection = undefined; var m: usize = 0; if (regexp.Regex.compile(pat)) |compiled| { @@ -69,7 +74,10 @@ pub fn selectByRegex(e: Editor, t: *Text, snap: []modal.Selection, pri: usize, e var hay_all = text; if (for (pat) |c| { if (std.ascii.isUpper(c)) break false; - } else true) hay_all = std.ascii.allocLowerString(e.scratch, text) catch |err| return e.reportError(err); + } else true) hay_all = std.ascii.allocLowerString(e.scratch, text) catch |err| { + e.reportError(err); + return 0; + }; for (snap) |r| { const from = @min(r.anchor, r.head); const to = @min(@max(r.anchor, r.head), text.len); @@ -116,9 +124,11 @@ pub fn selectByRegex(e: Editor, t: *Text, snap: []modal.Selection, pri: usize, e r.anchor = @min(r.anchor, text.len); r.head = @min(r.head, text.len); } - return t.setRanges(e.tab, text, snap, &.{}, pri, expl); + t.setRanges(e.tab, text, snap, &.{}, pri, expl); + return 0; } t.setRanges(e.tab, text, out[0..m], &.{}, 0, true); // helix keeps primary 0 (its own TODO) + return m; } fn lastMatch(re: *SearchRegex, hay: []const u8, from: usize, to: usize) ?regexp.Regex.Match { @@ -600,6 +610,9 @@ fn actionPass(e: Editor, t: *Text, action: modal.Normal.Action) edit.Error!void } fn startSelRegex(p: *Pardes, pane: *Pane, t: *Text, mode: modal.Normal.RegexMode) edit.Error!void { + // A body's prompt is its tag's (Prompt.zig); a tag's or a header's asks + // on the notice band. + if (t.what == .body) return Prompt.open(p, pane, Prompt.ofMode(mode)); const text = try edit.flatSurface(p.editor(), t); const got = t.ranges(text, 0, &pane.sel_snap); pane.nsel_snap = @intCast(got.n); @@ -1360,11 +1373,18 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error! .column, .workspace => tagline.exitHeader(p), .body, .input => tagline.enterTag(p, pane), }, - .pipe_selection => return panes.startPrompt(p, pane, t, .{ .pipe = .replace }), - .pipe_selection_to => return panes.startPrompt(p, pane, t, .{ .pipe = .ignore }), - .insert_output => return panes.startPrompt(p, pane, t, .{ .pipe = .insert }), - .append_output => return panes.startPrompt(p, pane, t, .{ .pipe = .append }), - .keep_pipe => return panes.startPrompt(p, pane, t, .{ .pipe = .keep }), + inline .pipe_selection, .pipe_selection_to, .insert_output, .append_output, .keep_pipe => |role| { + const how: modal.Normal.PipeBehavior = switch (role) { + .pipe_selection => .replace, + .pipe_selection_to => .ignore, + .insert_output => .insert, + .append_output => .append, + else => .keep, + }; + // A body's in its tag (Prompt.zig), else on the notice band. + if (t.what == .body) return Prompt.open(p, pane, Prompt.ofBehavior(how)); + return panes.startPrompt(p, pane, t, .{ .pipe = how }); + }, // `/` in a text is its query pane's line 1 (Query.zig); a // terminal's still asks on the notice band. .search => if (pane.file != null and t.what == .body) @@ -1657,7 +1677,7 @@ test "s and S search a multi-line selection as addr does: ^ and $ per line, . wi }) |c| { pane.sel_snap[0] = .{ .anchor = 0, .head = text.len }; pane.nsel_snap = 1; - applySelRegex(p, pane, &pane.body, c.pat, c.mode); + _ = applySelRegex(p, pane, &pane.body, c.pat, c.mode); var out: [Text.max_selections]modal.Selection = undefined; const got = pane.body.ranges(text, 0, &out); try std.testing.expectEqual(c.want.len, got.n); diff --git a/core/panes.zig b/core/panes.zig index 115323c4..0590a80d 100644 --- a/core/panes.zig +++ b/core/panes.zig @@ -1953,7 +1953,7 @@ test "a prompt chip is a band with its caret, still on the grid, and only the ch for (pane.sel) |selection| try std.testing.expect(selection.state == .none); } -test "a prompt is typed on its own line in the notice band and leaves the tag row alone" { +test "a Save prompt is typed on its own line in the notice band and leaves the tag row alone" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); const pane = try p.setTestFile("one two\n"); @@ -1963,13 +1963,13 @@ test "a prompt is typed on its own line in the notice band and leaves the tag ro const tag_before = try std.testing.allocator.dupe(Cell, p.surface.tag_layers[0].cells); defer std.testing.allocator.free(tag_before); - // `s` keeps a prompt on the band (a text's `/` is its query pane's - // line 1 now, Query.zig). - p.update(.{ .key = .{ .cp = 's' } }); + // Save's path keeps a prompt on the band (a body's `s`, `|` and `/` + // ask in its tag, Prompt.zig). + startPrompt(p, pane, &pane.body, .save); p.update(.{ .key = .{ .cp = 't', .text = "tw" } }); p.update(.{ .key = .{ .cp = Key.left } }); - try std.testing.expect(pane.prompt == .search and pane.focus == .body); - try std.testing.expectEqualStrings(config.select_marker ++ "tw", pane.promptText().?); + try std.testing.expect(pane.prompt == .save and pane.focus == .body); + try std.testing.expectEqualStrings(config.save_marker ++ "/tw", pane.promptText().?); _ = frame.reset(.retain_capacity); _ = try p.render(frame.allocator()); // The tagline is exactly what it was: nothing of the prompt is in it. @@ -1986,7 +1986,7 @@ test "a prompt is typed on its own line in the notice band and leaves the tag ro const grid = p.surface.cursor orelse return error.MissingPromptCursor; try std.testing.expectEqual(p.bodyTop(pane, p.view().rects[0]), grid.y); - // Submitting searches for what was typed and gives the prompt its line back. - p.update(.{ .key = .{ .cp = Key.enter } }); + // Esc gives the prompt its line back. + p.update(.{ .key = .{ .cp = Key.escape } }); try std.testing.expect(pane.prompt == .none and pane.input.own == null); } diff --git a/core/root.zig b/core/root.zig index 36d940b2..09486906 100644 --- a/core/root.zig +++ b/core/root.zig @@ -92,6 +92,7 @@ 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 Prompt = @import("Prompt.zig"); pub const Addon = @import("Addon.zig"); pub const dump = @import("dump.zig"); pub const lsp = @import("lsp/lsp.zig"); @@ -415,6 +416,7 @@ test { _ = @import("TagState.zig"); _ = @import("Band.zig"); _ = @import("Field.zig"); + _ = @import("Prompt.zig"); _ = @import("Effect.zig"); _ = @import("tape.zig"); _ = @import("replica.zig"); diff --git a/test/behaviour/keys.zig b/test/behaviour/keys.zig index e1f550e3..e8731d2c 100644 --- a/test/behaviour/keys.zig +++ b/test/behaviour/keys.zig @@ -14,18 +14,20 @@ test "keys: a prompt's entry and cancellation leave the tag, the body and its cu const dot = s.at("/pane/{d}/dot", .{n}); try s.replace(tag, " keep"); for ([_]struct { keys: []const u8, shown: []const u8 }{ - .{ .keys = "s", .shown = " /zq" }, - .{ .keys = "|", .shown = " |zq" }, - .{ .keys = alt ++ "|", .shown = " |-zq" }, - .{ .keys = "!", .shown = " !zq" }, - .{ .keys = alt ++ "!", .shown = " !+zq" }, + .{ .keys = "s", .shown = " s zq" }, + .{ .keys = "|", .shown = " | zq" }, + .{ .keys = alt ++ "|", .shown = " A-| zq" }, + .{ .keys = "!", .shown = " ! zq" }, + .{ .keys = alt ++ "!", .shown = " A-! zq" }, }) |case| { try s.write(dot, "6 6"); try s.keys(case.keys); - // The answer is typed into the prompt's own line, never the tag. + // The answer is typed into the tag's head (walk UI), shown in place + // of the tag's own text, which it never touches. try s.keys("zq"); _ = try s.where(case.shown); - try std.testing.expectEqualStrings("/test.txt keep", try s.read(tag)); + const head = try s.read(tag); + try std.testing.expect(std.mem.startsWith(u8, head, "/test.txt") and std.mem.startsWith(u8, head["/test.txt".len..], case.shown)); try s.keys("\x1b"); try std.testing.expectError(error.NotOnScreen, s.where(case.shown)); try std.testing.expect(std.mem.endsWith(u8, try s.read(s.at("/pane/{d}/ctl", .{n})), " mode:normal ")); @@ -56,8 +58,8 @@ test "keys: a prompt opens whatever the tag already holds" { try s.keys(key); try s.keys("zq"); _ = try s.where("zq"); - try std.testing.expectEqualStrings(full, try s.read(tag)); try s.keys("\x1b"); + try std.testing.expectEqualStrings(full, try s.read(tag)); } } diff --git a/test/daemon.py b/test/daemon.py index f9cbc9e1..4bc2658f 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 = 36 + WIRE = 37 def __init__(self, path, timeout=10): self.path, self.timeout = path, timeout diff --git a/test/snapshots/msg.golden b/test/snapshots/msg.golden index 7f83cacf..6a79cd68 100644 --- a/test/snapshots/msg.golden +++ b/test/snapshots/msg.golden @@ -36,14 +36,18 @@ |7: |8: |9: -== snap prompt grid=70x17 cursor=69,3 -|3: 1 EXTERNAL Select /EXT -== snap prompt-wins grid=70x17 cursor=69,4 -|3: 1 AGAIN --:--:-- reloaded /tmp/pardes-snap/msg/cwd/a.txt -|4: ~ Select /EXT +== snap prompt grid=70x17 cursor=38,2 +|2: ^ /tmp/pardes-snap/msg/cwd/a.txt s EXT = Exec Edit x/EXT/ 0 ⏎ sel +|3: ect · C-r history · esc +|4: 1 EXTERNAL +|5: ~ +== snap prompt-wins grid=70x17 cursor=38,2 +|4: 1 AGAIN --:--:-- reloaded /tmp/pardes-snap/msg/cwd/a.txt == snap esc grid=70x17 cursor=7,4 +|2: /tmp/pardes-snap/msg/cwd/a.txt Save Term Collapse Follow Del |3: 1 AGAIN |4: ~ +|5: == snap msgbuiltin grid=70x17 cursor=29,5 |2: */tmp/pardes-snap/msg/cwd/a.txt Save Term Collapse Follow Del |3: 1 AGAIN hand-written report diff --git a/test/snapshots/pipe.golden b/test/snapshots/pipe.golden index 618a3019..641418f9 100644 --- a/test/snapshots/pipe.golden +++ b/test/snapshots/pipe.golden @@ -1,8 +1,8 @@ -== snap prompt grid=180x13 cursor=179,3 +== snap prompt grid=180x13 cursor=49,2 | Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config History Debug Exit | New Term Find Grep Joincol Delcol -| /tmp/pardes-snap/pipe/cwd/pipe.txt Save Term Collapse Follow Del -| 1 alpha beta |tr a-z A-Z +|^ /tmp/pardes-snap/pipe/cwd/pipe.txt | tr a-z A-Z = Exec Edit |tr a-z A-Z ⏎ replace · C-r history · esc +| 1 alpha beta | 2 gamma delta == snap filtered grid=180x13 cursor=17,3 |2: */tmp/pardes-snap/pipe/cwd/pipe.txt Save Term Collapse Follow Del diff --git a/test/snapshots/selregex.golden b/test/snapshots/selregex.golden index 4e456d99..cc460f03 100644 --- a/test/snapshots/selregex.golden +++ b/test/snapshots/selregex.golden @@ -1,18 +1,18 @@ -== snap prompt-armed grid=160x25 cursor=159,3 +== snap prompt-armed grid=160x25 cursor=40,2 | Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config History Debug Exit | New Term Find Grep Joincol Delcol -| /tmp/pardes-snap/selregex/cwd/m.zig Save Term Collapse Follow TreeContext Def Refs Del -| 1 const one = 1; Select / +|^ /tmp/pardes-snap/selregex/cwd/m.zig s ⏎ select · C-r history · esc +| 1 const one = 1; | 2 const two = 2; | 3 const three = 3; | ~ -== snap preview grid=160x25 cursor=159,3 -|3: 1 const one = 1; Select /const +== snap preview grid=160x25 cursor=45,2 +|2: ^ /tmp/pardes-snap/selregex/cwd/m.zig s const = Exec Edit x/const/ 3 selections in 3 lines ⏎ select · C-r history · esc == style preview grid=160x25 |0: 0-1 d,#1d2824, 2-159 #b2c3b8,#1d2824, |1: 0-1 d,#887455, 2-159 #becfc4,#314738, -|2: 0-1 d,#add38a, 2-31 #becfc4,#314738, 32-37 #dfbce5,#314738, 38-159 #becfc4,#314738, -|3: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f5f7ee,#3c614a, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-143 #e5eee5,#0d1410, 144-145 #e5eee5,#1d2824, 146-159 #b2c3b8,#1d2824, +|2: 0-1 #000000,#add38a, 2-31 #becfc4,#314738, 32-37 #dfbce5,#314738, 38-38 #add38a,#314738,b 39-39 #add38a,#314738, 40-44 #becfc4,#314738, 45-52 #becfc4,#314738,f 53-95 #becfc4,#314738, 96-123 #becfc4,#314738,f 124-159 #becfc4,#314738, +|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-10 #f5f7ee,#3c614a, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-159 #e5eee5,#0d1410, |4: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f5f7ee,#243a2d, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-159 #e5eee5,#0d1410, |5: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f5f7ee,#243a2d, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-20 #e5eee5,#0d1410, 21-21 #f8c082,#0d1410, 22-159 #e5eee5,#0d1410, |6: 0-0 d,#608269, 1-4 d,#0d1410, 5-159 #59675c,#0d1410, @@ -35,18 +35,21 @@ |23: 0-0 d,#608269, 1-159 d,#0d1410, |24: 0-0 d,#608269, 1-159 d,#0d1410, == snap three-selected grid=160x25 cursor=11,3 -|3: 1 const one = 1; +|2: /tmp/pardes-snap/selregex/cwd/m.zig Save Term Collapse Follow TreeContext Def Refs Del == style three-selected grid=160x25 +|2: 0-1 d,#add38a, 2-31 #becfc4,#314738, 32-37 #dfbce5,#314738, 38-159 #becfc4,#314738, |3: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-11 #f5f7ee,#3c614a, 12-12 #f5f7ee,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-159 #e5eee5,#0d1410, -== snap narrowed grid=160x25 cursor=159,3 -|3: 1 const one = 1; Select /t +== snap narrowed grid=160x25 cursor=41,2 +|2: ^ /tmp/pardes-snap/selregex/cwd/m.zig s t = Exec Edit x/t/ 3 selections in 3 lines ⏎ select · C-r history · esc == style narrowed grid=160x25 -|3: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-147 #e5eee5,#0d1410, 148-149 #e5eee5,#1d2824, 150-159 #b2c3b8,#1d2824, +|2: 0-1 #000000,#add38a, 2-31 #becfc4,#314738, 32-37 #dfbce5,#314738, 38-38 #add38a,#314738,b 39-39 #add38a,#314738, 40-40 #becfc4,#314738, 41-48 #becfc4,#314738,f 49-87 #becfc4,#314738, 88-115 #becfc4,#314738,f 116-159 #becfc4,#314738, +|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-10 #e5eee5,#0d1410, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-159 #e5eee5,#0d1410, |4: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-159 #e5eee5,#0d1410, |5: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-20 #e5eee5,#0d1410, 21-21 #f8c082,#0d1410, 22-159 #e5eee5,#0d1410, == snap esc-restores grid=160x25 cursor=11,3 -|3: 1 const one = 1; +|2: /tmp/pardes-snap/selregex/cwd/m.zig Save Term Collapse Follow TreeContext Def Refs Del == style esc-restores grid=160x25 +|2: 0-1 d,#add38a, 2-31 #becfc4,#314738, 32-37 #dfbce5,#314738, 38-159 #becfc4,#314738, |3: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-11 #f5f7ee,#3c614a, 12-12 #f5f7ee,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-159 #e5eee5,#0d1410, |4: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f5f7ee,#243a2d, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-159 #e5eee5,#0d1410, |5: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f5f7ee,#243a2d, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-20 #e5eee5,#0d1410, 21-21 #f8c082,#0d1410, 22-159 #e5eee5,#0d1410, -- cgit v1.3 From b28053aede910b8714db4f27ef66e59dd96945c0 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 24 Nov 2026 21:10:15 -0300 Subject: Prompt: `/` and `?` search a file's body as they are typed (walk UI, pick-ui SPEC.md §7.3, item 2 of line E): its places found from where it began (Places.search, the view's on the key, a frame's budget a tick after), tinted, the current one stronger and selected as soon as it is found (`?`: the last before the caret, once the text between is searched), the gutter marked in the blank after each line number (`▸` the current place's line, `▪` the others'), counted `3/7 · 5 lines` (`3/⋯` while they are found; the lines counted once, at the step they are all found, a pass to the last place), ` · wrapped` past the end from where it began, `0` for no match; a pattern that is no regex keeps the last places, dimmed (Places.paint), the reason in the count; Enter lands, the pattern in `/`, and folds the pane's one search word into its trail (`/dirty/ 3/7`, Trail.setWord: the newest back step, in place of the one it had); n and N write it again in place and echo `/dirty/ 4/7 · line 112` on the message row, ` ↻` after a step round an end, `–/7` with the selection off its places, every step (Prompt.settle beside the places'); the first Esc in normal mode clears a search's tints (SPEC §10.4's first step: C's Esc order when it lands) and the word stays, dimmed (draw.zig, Trail.spanOf); Look on the word lights its places again and selects the one it was on, Exec searches again from the caret (Trail.lookStep, execStep); `*` makes the selection's pattern the search word, no prompt and no query pane; Alt-Enter keeps the places as rows: today's query pane (Query.open .text), the body as it was; `?` is helix's backward search, a new role (modal.zig, config.zig); THE FAULTS THE TESTS MET, both B's and latent until a word step was made: Trail.wordOf returned the text of a COPY of the step (a slice of its stack frame: the word drawn as garbage), now the step's own bytes; Trail.lastCur held `cur` under `n`, though keep() leaves a held pane's at `n` (a search word alone: the dump's load moved it and the digests differed), now `n`; TEST FIRST: Prompt.zig "/ searches the body as it is typed ..." and "? searches back from the caret ..."; Places' `*` test reads the echo, Query's and Stream's `/` tests keep their query pane by Alt-Enter, Query's `*` test reads the word; test/perf.zig --search measures a key in `/` and `s` on a 1 MB file; goldens fsearch, lookrange (the prompt in the tag, the word in the trail); core-test 1016/1182 (166 skipped), shell-test 1229/1232, pane-test 182/184, behaviour-test 274/277 (the failures A's, as on item 1), process-test A's six and none of mine, term-test 17/17, kitty-test 45/45 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- core/Core.zig | 2 + core/Places.zig | 15 +- core/Prompt.zig | 427 +++++++++++++++++++++++++++++++++++++++- core/Query.zig | 24 ++- core/Stream.zig | 2 + core/Trail.zig | 56 +++++- core/body_layer.zig | 1 + core/config.zig | 1 + core/draw.zig | 2 + core/modal.zig | 2 + core/normal.zig | 33 ++-- test/perf.zig | 32 +++ test/snapshots/fsearch.golden | 137 +++++++------ test/snapshots/lookrange.golden | 33 ++-- 14 files changed, 643 insertions(+), 124 deletions(-) diff --git a/core/Core.zig b/core/Core.zig index 987c4f85..95f3a3a8 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -1825,6 +1825,8 @@ fn updateInner(p: *Pardes, ev: Event) void { // Each pane's places find a frame's more on a tick, and on any other // step the ones an edit or a scroll left unfound in the view. for (p.panes) |slot| if (slot) |pane| pane.places.settle(p, pane, ev == .tick); + // Their search words and a search prompt with them (Prompt.zig). + pardes.Prompt.settle(p); // Each live query pane's rows, made from what changed this step. pardes.panes.Query.produceAll(p, ev == .tick, ev == .key); _ = p.scratch.reset(.{ .retain_with_limit = memory.limits.scratch_kept }); diff --git a/core/Places.zig b/core/Places.zig index 6c3ac9ab..4c04555b 100644 --- a/core/Places.zig +++ b/core/Places.zig @@ -664,8 +664,13 @@ pub fn paint(set: *Places, p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, if (!set.shows(pane)) return; const f = &pane.file.?; const th = p.theme(); - const strong = p.chromeTheme().search_bg; - const quiet = colors.mix(th.bg orelse th.tag_bg, strong); + var strong = p.chromeTheme().search_bg; + var quiet = colors.mix(th.bg orelse th.tag_bg, strong); + // A search prompt's pattern that is no regex: its last places, dimmed. + if (pardes.Prompt.dims(p, pane)) { + strong = quiet; + quiet = colors.mix(th.bg orelse th.tag_bg, quiet); + } const hits = set.hits.items; if (hits.len == 0) return; const nlines = File.nlines(p.gpa, f); @@ -792,11 +797,11 @@ test "places: * finds them all, n and N step them round the end silently, an edi try std.testing.expectEqual(@as(?usize, 1), set.current); typeKeys(p, "n"); try std.testing.expectEqual(@as(?usize, 2), set.current); - const logged = p.messages.len; typeKeys(p, "n"); try std.testing.expectEqual(@as(?usize, 0), set.current); - // round the end without a word anywhere - try std.testing.expectEqual(logged, p.messages.len); + // round the end: the search word says so, and the message row echoes + // it (Prompt.zig, pick-ui SPEC §7.3) + try std.testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "1/3 ↻ · line 1") != null); typeKeys(p, "N"); try std.testing.expectEqual(@as(?usize, 2), set.current); diff --git a/core/Prompt.zig b/core/Prompt.zig index e5fac06c..53f6cd5c 100644 --- a/core/Prompt.zig +++ b/core/Prompt.zig @@ -1,5 +1,6 @@ -//! A text prompt in a pane's tag (walk UI, pick-ui SPEC.md §7): `s S K A-K` -//! select by a pattern, `| A-| ! A-! $` pipe through a command, typed in +//! A text prompt in a pane's tag (walk UI, pick-ui SPEC.md §7): `/ ?` +//! search the body, `s S K A-K` select by a pattern, `| A-| ! A-! $` pipe +//! through a command, typed in //! the head's field after the prompt's key cell, the plain word it stands //! for and its count beside it (`s self = Exec Edit x/self/ 4 selections in //! 6 lines`), its effect drawn live in the body on every key; Enter applies @@ -26,6 +27,11 @@ const Field = @import("Field.zig"); const Band = @import("Band.zig"); const TagState = @import("TagState.zig"); const Kind = @import("Kind.zig"); +const Places = @import("Places.zig"); +const Trail = @import("Trail.zig"); +const colors = @import("colors.zig"); +const Surface = @import("surface.zig").Surface; +const File = panes.File; const Pardes = pardes.Pardes; const Pane = panes.Pane; const Text = panes.Text; @@ -47,6 +53,13 @@ bad: bool = false, /// from back), and the lines those it started from cover. found: u16 = 0, scope: u32 = 0, +/// `?` waits for its place: the last before where it began, once the text +/// between them is searched. +seeking: bool = false, +/// The lines a search's places are on, counted once they are all found, at +/// the places' `hits_gen` `counted`. +lines: u32 = 0, +counted: u32 = std.math.maxInt(u32), /// The session's prompt histories: the lines Enter took, newest last. pub const History = struct { @@ -93,8 +106,8 @@ const Info = struct { }; const info = std.EnumArray(Op, Info).init(.{ - .search = .{ .cell = "/", .hint = "⏎ land · C-r history · esc" }, - .search_back = .{ .cell = "?", .hint = "⏎ land · C-r history · esc" }, + .search = .{ .cell = "/", .hint = "⏎ land · M-⏎ as a list · C-r history · esc" }, + .search_back = .{ .cell = "?", .hint = "⏎ land · M-⏎ as a list · C-r history · esc" }, .select = .{ .cell = "s", .hint = "⏎ select · C-r history · esc" }, .split = .{ .cell = "S", .hint = "⏎ select · C-r history · esc" }, .keep = .{ .cell = "K", .hint = "⏎ keep · C-r history · esc" }, @@ -145,6 +158,10 @@ pub fn ofBehavior(how: modal.Normal.PipeBehavior) Op { }; } +fn searches(op: Op) bool { + return op == .search or op == .search_back; +} + fn behavior(op: Op) ?modal.Normal.PipeBehavior { return switch (op) { .pipe => .replace, @@ -158,7 +175,8 @@ fn behavior(op: Op) ?modal.Normal.PipeBehavior { /// Prompt `op` in the tag of `pane`, the pane with the keyboard, for its /// body: its field empty, the body's selections as they are (`s S K A-K` -/// select inside them, Esc puts them back). +/// select inside them, `/ ?` search from the primary one; Esc puts them +/// back). `/ ?` search a file's body only. pub fn open(p: *Pardes, pane: *Pane, op: Op) void { // Nobody is at the keyboard to answer a command a script wrote to a // ctl file: the write fails instead (core/ninep/ctl.zig). @@ -186,6 +204,7 @@ pub fn open(p: *Pardes, pane: *Pane, op: Op) void { scope += @intCast(std.mem.count(u8, text[lo..hi -| @intFromBool(hi > lo and text[hi - 1] == '\n')], "\n") + 1); } } + if (searches(op)) pane.places.remember(p, pane); pane.focus = .body; tagline.exitHeader(p); t.mode = .normal; @@ -210,6 +229,7 @@ pub fn key(p: *Pardes, k: Key) void { const ctrl = k.ctrl and !k.alt; if (hit(k, config.escape)) return cancel(p, pane); if (plain and k.cp == Key.enter) return commit(p, id, pane); + if (k.alt and !k.ctrl and k.cp == Key.enter) return asList(p, id, pane); // Backspace on an empty field: the prompt goes, as Esc. if (plain and k.cp == Key.backspace and s.field.len == 0) return cancel(p, pane); // Up and Down bring its history's lines into the field, the newest first. @@ -236,11 +256,54 @@ pub fn key(p: *Pardes, k: Key) void { /// prompt says why. fn live(p: *Pardes, pane: *Pane) void { const s = &p.view().tag_state; - const m = mode(s.prompt.op) orelse return; const pat = s.field.text(); + if (mode(s.prompt.op) == null and !searches(s.prompt.op)) return; s.prompt.bad = pat.len > 0 and if (regexp.Regex.compile(pat)) |_| false else |_| true; if (s.prompt.bad) return; - s.prompt.found = @intCast(normal.applySelRegex(p, pane, &pane.body, pat, m)); + if (mode(s.prompt.op)) |m| { + s.prompt.found = @intCast(normal.applySelRegex(p, pane, &pane.body, pat, m)); + return; + } + // A search: its places found from where it began, the view's first, + // the rest a frame's budget a tick (Places.zig); `/` selects the first + // at or after the caret as soon as it is found, `?` the last before it. + const set = &pane.places; + s.prompt.counted = std.math.maxInt(u32); + if (pat.len == 0) { + if (set.from == 0) set.clear(p.gpa); + set.restore(p.settings.tab, pane); + return; + } + const back = s.prompt.op == .search_back; + set.search(p, pane, .typed, 0, pat, false, if (back) null else set.origin(pane), !back); + s.prompt.seeking = back; + if (back) seekBack(p, pane); +} + +/// `?`'s place: the last before where it began once the text between is +/// searched, past the top the last of all once every place is found; +/// none, the body as it was. +fn seekBack(p: *Pardes, pane: *Pane) void { + const s = &p.view().tag_state; + const set = &pane.places; + if (!set.started) return; + const origin = set.origin(pane); + const hits = set.hits.items; + const i = Places.firstFrom(hits, origin); + const whole = set.head_to >= set.lo; + const to: ?usize = if (i > 0 and origin <= set.hi and (whole or hits[i - 1].start >= set.lo)) + i - 1 + else if (set.complete() and hits.len > 0) + hits.len - 1 + else + null; + if (to) |at| { + s.prompt.seeking = false; + return set.goTo(p.settings.tab, pane, at, false); + } + if (!set.complete()) return; + s.prompt.seeking = false; + set.restore(p.settings.tab, pane); } /// Enter: what the field says, applied, and the line kept in its history @@ -258,6 +321,7 @@ fn commit(p: *Pardes, id: usize, pane: *Pane) void { TagState.toRest(p); if (typed.len == 0) return undo(p, pane, op); ring(p, op).add(typed); + if (searches(op)) return land(p, id, pane, op, typed, bad); if (mode(op) != null) { // No regex: the selections it began with, and why. if (bad) { @@ -275,6 +339,44 @@ fn commit(p: *Pardes, id: usize, pane: *Pane) void { } } +/// Enter in `/` or `?`: the place found current, its places tinted from +/// now on for n and N, the pattern in `/`, and the pane's search word +/// `/re/ 3/7` in its trail (SPEC §7.3). +fn land(p: *Pardes, id: usize, pane: *Pane, op: Op, pat: []const u8, bad: bool) void { + const set = &pane.places; + if (bad) { + undo(p, pane, op); + return p.setMessage(.at(id), regexMessage(pat)); + } + set.fill(p, pane, std.math.maxInt(usize), regexp.Regex.budget); + if (op == .search_back) seekBack(p, pane); + if (set.hits.items.len == 0) { + undo(p, pane, op); + var said: [Field.max + 16]u8 = undefined; + return p.setMessage(.at(id), std.fmt.bufPrint(&said, "/{s}/: no match", .{pat}) catch "no match"); + } + p.registers.put(p.gpa, '/', pat, 0, 1, true) catch |err| return p.reportError(.at(id), "search", err); + p.registers.last_search = '/'; + set.provenance = .search; + set.forget(p.gpa); + word(pane, if (op == .search_back) '?' else '/', pat); +} + +/// Alt-Enter in `/` or `?`: the places kept as a list, a row each, in the +/// pane's query pane (Query.zig), the body as it was before the prompt. +fn asList(p: *Pardes, id: usize, pane: *Pane) void { + const s = &p.view().tag_state; + const op = s.prompt.op; + if (!searches(op)) return; + var kept: [Field.max]u8 = undefined; + const typed = kept[0..s.field.len]; + @memcpy(typed, s.field.text()); + s.kind = .rest; + TagState.toRest(p); + undo(p, pane, op); + panes.Query.open(p, id, .text, typed, true); +} + /// Esc: the prompt goes and the body is as it was before it. fn cancel(p: *Pardes, pane: *Pane) void { const op = p.view().tag_state.prompt.op; @@ -287,6 +389,11 @@ fn cancel(p: *Pardes, pane: *Pane) void { fn undo(p: *Pardes, pane: *Pane, op: Op) void { if (mode(op)) |m| _ = normal.applySelRegex(p, pane, &pane.body, "", m); pane.nsel_snap = 0; + if (!searches(op)) return; + const set = &pane.places; + if (set.from == 0 and set.provenance == .typed) set.clear(p.gpa); + set.restore(p.settings.tab, pane); + set.forget(p.gpa); } /// The prompt left by something else than its keys (TagState.toRest: a @@ -317,6 +424,201 @@ pub fn selecting(p: *const Pardes, pane: *const Pane) ?struct { dim: bool } { return .{ .dim = s.prompt.bad }; } +/// Whether `pane`'s places are a search prompt's last good ones, its field +/// no regex now: tinted dimmed (Places.paint). +pub fn dims(p: *const Pardes, pane: *const Pane) bool { + const s = &p.view().tag_state; + return s.kind == .prompt and searches(s.prompt.op) and s.host == pane.serial and s.prompt.bad; +} + +// ---- the search word (SPEC §7.3) ---- + +/// Pane `pane`'s search word, `/re/ 3/7`: one a pane, its `index` the +/// length of its `/re/` with bit 16 set after n or N went round an end. +fn wordOf(pane: *Pane) ?*Trail.Word { + for (pane.trail.steps[0..pane.trail.n]) |*step| if (step.* == .search) return &step.search; + return null; +} + +fn patternOf(w: *const Trail.Word) []const u8 { + const end: u16 = @truncate(w.index); + return w.text.slice()[1 .. end - 1]; +} + +/// Whether the places the pane's body shows are its search word's. +fn lights(pane: *const Pane, w: *const Trail.Word) bool { + const set = &pane.places; + return set.shows(pane) and set.provenance == .search and !set.literal and std.mem.eql(u8, set.pattern, patternOf(w)); +} + +/// `pat`, delimited by `delim`, as pane `pane`'s one search word, in place +/// of the one it had, written for where its places stand. +fn word(pane: *Pane, delim: u8, pat: []const u8) void { + // Its pattern and its place in the trail's room, else none. + if (pat.len + 2 + 32 > Trail.max_text) return; + var w: Trail.Word = .{}; + _ = w.text.print("{c}{s}{c}", .{ delim, pat, delim }); + w.index = w.text.len; + pane.trail.setWord(.{ .search = w }); + refresh(pane, false); +} + +/// The search word's place among its places written after its pattern: +/// `3/7`, `–/7` with the selection off them, `⋯` for the count while they +/// are found, ` ↻` after n or N went round an end (`wrapped`; null keeps +/// what it said). +fn refresh(pane: *Pane, wrapped: ?bool) void { + const w = wordOf(pane) orelse return; + if (!lights(pane, w)) return; + const set = &pane.places; + const f = &pane.file.?; + const end: u16 = @truncate(w.index); + const round = wrapped orelse (w.index >> 16 != 0); + const hits = set.hits.items; + const sel = pane.body.primaryRange(f.content, 0); + const on: ?usize = if (set.current) |c| (if (c < hits.len and hits[c].start == @min(sel.anchor, sel.head) and hits[c].end == @max(sel.anchor, sel.head)) c else null) else null; + var buf: [48]u8 = undefined; + var out: std.Io.Writer = .fixed(&buf); + out.writeByte(' ') catch return; + if (on) |c| out.print("{d}", .{c + 1}) catch return else out.writeAll("–") catch return; + if (set.complete()) out.print("/{d}", .{hits.len}) catch return else out.writeAll("/⋯") catch return; + if (round) out.writeAll(" ↻") catch return; + const now = w.text.slice(); + if (std.mem.eql(u8, now[end..], out.buffered()) and (w.index >> 16 != 0) == round) return; + var text: [Trail.max_text]u8 = undefined; + @memcpy(text[0..end], now[0..end]); + @memcpy(text[end..][0..out.buffered().len], out.buffered()); + w.text.set(text[0 .. end + out.buffered().len]); + w.index = end | @as(u32, @intFromBool(round)) << 16; +} + +/// After each step (Core.zig, beside the places'): every search word says +/// where its places stand; the live view's search prompt finds `?`'s place +/// and counts the lines its places are on once they are all found. +pub fn settle(p: *Pardes) void { + for (p.panes) |slot| if (slot) |pane| refresh(pane, null); + const s = &p.view().tag_state; + if (s.kind != .prompt or !searches(s.prompt.op)) return; + const pane = p.panes[TagState.hostOf(p) orelse return].?; + if (s.prompt.seeking) seekBack(p, pane); + const set = &pane.places; + if (!set.shows(pane) or !set.complete() or s.prompt.counted == set.hits_gen) return; + // A line holds the next place unless a newline lies between them: a + // pass over the text to the last place, once. + const text = pane.file.?.content; + var lines: u32 = 0; + var prev: ?usize = null; + for (set.hits.items) |h| { + if (prev == null or std.mem.indexOfScalarPos(u8, text[0..h.start], prev.?, '\n') != null) lines += 1; + prev = h.start; + } + s.prompt.lines = lines; + s.prompt.counted = set.hits_gen; +} + +/// n or N stepped pane `id`'s places from place `before`: its search word +/// says where they stand, ` ↻` when the step went round an end, and the +/// message row echoes it with the line: `/dirty/ 4/7 · line 112`. +pub fn stepped(p: *Pardes, id: usize, forward: bool, before: ?usize) void { + const pane = p.panes[id] orelse return; + const w = wordOf(pane) orelse return; + const set = &pane.places; + if (!lights(pane, w)) return; + const after = set.current orelse return; + refresh(pane, if (before) |b| (if (forward) after <= b else after >= b) else false); + const index = File.lineIndex(p.gpa, &pane.file.?) catch return; + var said: [Trail.max_text + 32]u8 = undefined; + p.setMessage(.at(id), std.fmt.bufPrint(&said, "{s} · line {d}", .{ w.text.slice(), Places.lineOf(index, set.hits.items[after].start) + 1 }) catch return); +} + +/// `*`: pattern `pat`, the selection's (in `/` already), lights its places +/// in `pane`'s body and is its search word, no prompt asked (SPEC §7.3). +pub fn star(p: *Pardes, pane: *Pane, pat: []const u8) void { + pane.places.search(p, pane, .search, 0, pat, false, null, false); + word(pane, '/', pat); +} + +/// Look on pane `id`'s search word (SPEC §6.3): its places lit again and +/// the one it was on selected. +pub fn lookWord(p: *Pardes, id: usize) void { + const pane = p.panes[id] orelse return; + const w = wordOf(pane) orelse return; + const set = &pane.places; + const pat = patternOf(w); + p.registers.put(p.gpa, '/', pat, 0, 1, true) catch |err| return p.reportError(.at(id), "search", err); + p.registers.last_search = '/'; + set.search(p, pane, .search, 0, pat, false, null, false); + set.fill(p, pane, std.math.maxInt(usize), regexp.Regex.budget); + p.view().active = id; + const end: u16 = @truncate(w.index); + const rest = w.text.slice()[end..]; + const n = std.fmt.parseInt(usize, std.mem.trim(u8, rest[0 .. std.mem.indexOfScalar(u8, rest, '/') orelse rest.len], " "), 10) catch return; + if (n > 0 and n <= set.hits.items.len) set.goTo(p.settings.tab, pane, n - 1, false); +} + +/// Exec on it: searched again from the caret, as its prompt and Enter +/// would, the next place when they are lit already (n). +pub fn execWord(p: *Pardes, id: usize) void { + const pane = p.panes[id] orelse return; + const w = wordOf(pane) orelse return; + const set = &pane.places; + const pat = patternOf(w); + p.registers.put(p.gpa, '/', pat, 0, 1, true) catch |err| return p.reportError(.at(id), "search", err); + p.registers.last_search = '/'; + p.view().active = id; + if (lights(pane, w)) { + const before = set.current; + set.step(p, pane, true, 1, false); + return stepped(p, id, true, before); + } + set.search(p, pane, .search, 0, pat, false, set.origin(pane), true); +} + +/// The span of pane `pane`'s tag its search word takes while its places no +/// longer light it (the first Esc cleared them): drawn dimmed (draw.zig). +pub fn unlit(pane: *Pane) ?[2]usize { + const t = &pane.trail; + for (t.steps[0..t.cur], 0..) |*step, i| if (step.* == .search) { + if (lights(pane, &step.search) or t.cur - i > Trail.shown_steps) return null; + return t.spanOf(i); + }; + return null; +} + +/// The gutter's marks while a prompt is typed (SPEC §7.1): `▸` on the +/// current place's line and `▪` on every other line holding a place (`/ +/// ?`). In the blank after a row's line number, on a line's first row. +pub fn paintGutter(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, body_h: u16) void { + const ts = &p.view().tag_state; + if (ts.kind != .prompt or ts.host != pane.serial or !searches(ts.prompt.op)) return; + const f = &(pane.file orelse return); + const set = &pane.places; + if (!set.shows(pane)) return; + const hits = set.hits.items; + if (hits.len == 0) return; + const tab = p.settings.tab; + const x = r.x + config.GUTTER + (File.gutterWidth(pane) -| File.laneCells(pane) -| pane.layers.heat -| 1); + const y = p.bodyTop(pane, r); + const ink = p.chromeTheme().box; + const nlines = File.nlines(p.gpa, f); + var last: i32 = -1; + var vr: u16 = 0; + while (vr < body_h) : (vr += 1) { + const line = pane.wrapAt(tab, vr).line; + if (line == last or line < 0) continue; + if (line >= nlines) break; + last = line; + const ls = File.lineStart(p.gpa, f, @intCast(line)); + const next = File.lineStart(p.gpa, f, @intCast(line + 1)); + const i = Places.firstFrom(hits, ls); + if (i == hits.len or hits[i].start >= @max(next, ls + 1)) continue; + const current = if (set.current) |c| hits[c].start >= ls and hits[c].start < @max(next, ls + 1) else false; + var style = s.at(x, y + vr).style; + style.fg = .{ .rgb = ink }; + s.set(x, y + vr, if (current) "▸" else "▪", style); + } +} + fn regexMessage(pat: []const u8) []const u8 { return if (regexp.Regex.compile(pat)) |_| "" else |err| regexp.Regex.message(err); } @@ -390,9 +692,24 @@ fn styled(arena: std.mem.Allocator, text: *std.ArrayList(u8), spans: *std.ArrayL } /// The prompt's count after its field: what it found (`4 selections in 6 -/// lines`, `keeps 3 of 9`, `0`). -fn count(arena: std.mem.Allocator, text: *std.ArrayList(u8), pane: *const Pane, pr: *const Prompt) !void { +/// lines`, `keeps 3 of 9`, `3/7 · 5 lines`, `3/⋯` while its places are +/// found, `0`). +fn count(arena: std.mem.Allocator, text: *std.ArrayList(u8), pane: *Pane, pr: *const Prompt) !void { switch (pr.op) { + .search, .search_back => { + const set = &pane.places; + if (!set.shows(pane)) return; + const hits = set.hits.items; + if (set.complete() and hits.len == 0) return text.appendSlice(arena, " 0"); + try text.appendSlice(arena, " "); + if (set.current) |c| try text.print(arena, "{d}", .{c + 1}) else try text.appendSlice(arena, "–"); + if (!set.complete()) return text.appendSlice(arena, "/⋯"); + try text.print(arena, "/{d} · {d} line{s}", .{ hits.len, pr.lines, plural(pr.lines) }); + // Round the end from where it began. + const c = set.current orelse return; + const origin = set.origin(pane); + if (if (pr.op == .search) hits[c].start < origin else hits[c].start > origin) try text.appendSlice(arena, " · wrapped"); + }, .select, .split => if (pr.found == 0) try text.appendSlice(arena, " 0") else @@ -531,3 +848,95 @@ test "Enter keeps what s found, the pattern in / and in the history Up brings ba p.update(.{ .key = .{ .cp = Key.escape } }); while (p.nextEffect()) |effect| try std.testing.expect(effect != .pipe); } + +const dirty = "dirty one\nclean\ndirty two dirty\nclean\ndirty three\ndirty four dirty\nclean\ndirty five\n"; + +/// The glyph in the blank after the line number of body row `row`. +fn gutterAt(p: *Pardes, arena: std.mem.Allocator, row: u16) ![]const u8 { + p.sync(); + const s = try p.render(arena); + const pane = p.panes[0].?; + const r = p.view().rects[0]; + const x = r.x + config.GUTTER + (File.gutterWidth(pane) -| File.laneCells(pane) -| pane.layers.heat -| 1); + return s.at(x, p.bodyTop(pane, r) + row).grapheme(); +} + +test "/ searches the body as it is typed: the current place selected, the gutter marked, counted 3/7 · 5 lines; Enter folds /dirty/ 3/7 into the trail; n says where it went, round the end too; the first Esc clears the tints and dims the word, Look on it lights them again" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 200, .rows = 30 }); + defer p.deinit(); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + const pane = try p.setTestFile(dirty); + pane.body.cur_row = 2; + pane.body.cur_col = 6; + typeKeys(p, "/dirty"); + try std.testing.expect(has(try tagOf(p), " / dirty = Look /dirty/ 3/7 · 5 lines ⏎ land · M-⏎ as a list")); + try std.testing.expectEqual(@as(?usize, 2), pane.places.current); + try std.testing.expectEqualStrings("▪", try gutterAt(p, frame.allocator(), 0)); + try std.testing.expectEqualStrings(" ", try gutterAt(p, frame.allocator(), 1)); + try std.testing.expectEqualStrings("▸", try gutterAt(p, frame.allocator(), 2)); + try std.testing.expectEqualStrings("▪", try gutterAt(p, frame.allocator(), 7)); + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expectEqual(TagState.Kind.rest, p.view().tag_state.kind); + try std.testing.expect(std.mem.startsWith(u8, try tagOf(p), "/dirty/ 3/7 › /test.txt ")); + try std.testing.expectEqualStrings("dirty", p.registers.value('/', 0).?); + try std.testing.expectEqualStrings(" ", try gutterAt(p, frame.allocator(), 0)); + // n: the word in place, and the line said. + typeKeys(p, "n"); + try std.testing.expect(std.mem.startsWith(u8, try tagOf(p), "/dirty/ 4/7 › ")); + try std.testing.expect(has(pane.msg[0..pane.msg_len], "/dirty/ 4/7 · line 5")); + typeKeys(p, "nnnn"); + try std.testing.expect(std.mem.startsWith(u8, try tagOf(p), "/dirty/ 1/7 ↻ › ")); + // Esc: the tints go, the word stays, dimmed; Look on it lights them + // again, the place it was on selected. + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expect(!pane.places.started); + try std.testing.expect(std.mem.startsWith(u8, try tagOf(p), "/dirty/ 1/7 ↻ › ")); + try std.testing.expect(unlit(pane) != null); + typeKeys(p, "j"); + Trail.lookStep(p, 0, 0); + try std.testing.expect(pane.places.started and unlit(pane) == null); + try std.testing.expectEqual(@as(?usize, 0), pane.places.current); + const sel = pane.body.primaryRange(pane.file.?.content, 0); + try std.testing.expectEqual(@as(usize, 0), @min(sel.anchor, sel.head)); + // Off a place: –/7. + typeKeys(p, "j"); + try std.testing.expect(std.mem.startsWith(u8, try tagOf(p), "/dirty/ –/7")); + // One search word a pane: a new search takes its place. + typeKeys(p, "gg/clean"); + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expect(std.mem.startsWith(u8, try tagOf(p), "/clean/ 1/3 › /test.txt ")); + try std.testing.expectEqual(@as(u8, 1), pane.trail.n); +} + +test "? searches back from the caret; no match is 0; a pattern that is no regex keeps the last places dimmed; Esc puts the body back; * makes the search word with no prompt; Alt-Enter keeps the places as the query pane's rows" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 200, .rows = 30 }); + defer p.deinit(); + const pane = try p.setTestFile(dirty); + pane.body.cur_row = 2; + pane.body.cur_col = 6; + const was = pane.body.primaryRange(pane.file.?.content, 0); + typeKeys(p, "?dirty"); + try std.testing.expect(has(try tagOf(p), " ? dirty = Look ?dirty? 2/7 · 5 lines ⏎ land")); + typeKeys(p, "x"); + try std.testing.expect(has(try tagOf(p), "= Look ?dirtyx? 0 ⏎ land")); + try std.testing.expectEqualDeep(was, pane.body.primaryRange(pane.file.?.content, 0)); + p.update(.{ .key = .{ .cp = Key.backspace } }); + typeKeys(p, "("); + try std.testing.expect(has(try tagOf(p), " bad regular expression · ")); + try std.testing.expect(dims(p, pane) and pane.places.started); + try std.testing.expectEqualStrings("dirty", pane.places.pattern); + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expect(!pane.places.started); + try std.testing.expectEqualDeep(was, pane.body.primaryRange(pane.file.?.content, 0)); + try std.testing.expectEqual(@as(u8, 0), pane.trail.n); + // `*` on `dirty` at the top: its places, its word, no prompt. + typeKeys(p, "gge*"); + try std.testing.expectEqual(TagState.Kind.rest, p.view().tag_state.kind); + try std.testing.expect(std.mem.startsWith(u8, try tagOf(p), "/\\bdirty\\b/ 1/7 › ")); + // Alt-Enter: the query pane, its line `/dirty`. + typeKeys(p, "/dirty"); + p.update(.{ .key = .{ .cp = Key.enter, .alt = true } }); + try std.testing.expectEqual(TagState.Kind.rest, p.view().tag_state.kind); + try std.testing.expect(p.panes[p.view().active].?.query != null); +} diff --git a/core/Query.zig b/core/Query.zig index feebb6cd..3ac87dfb 100644 --- a/core/Query.zig +++ b/core/Query.zig @@ -2134,6 +2134,12 @@ pub fn paint(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, body_h: u16) // ---- tests ---- +/// `/` and `typed` in the tag's prompt, kept as the query pane (Alt-Enter). +fn slash(p: *Pardes, typed: []const u8) void { + typeKeys(p, typed); + p.update(.{ .key = .{ .cp = Key.enter, .alt = true } }); +} + fn typeKeys(p: *Pardes, text: []const u8) void { for (text) |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); } @@ -2169,7 +2175,7 @@ test "a / query: keystroke by keystroke, the owner shows the set, rows from its // cursor on line 3 (row 2) pane.body.cur_row = 2; pane.body.cur_col = 0; - typeKeys(p, "/"); + slash(p, "/"); const qid = queryPane(p).?; const qp = p.panes[qid].?; try std.testing.expectEqual(@as(?usize, 0), layout.ownerOf(p, qid)); @@ -2226,7 +2232,7 @@ test "a dump holding a query pane, live or frozen, restores it as it was" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 }); defer p.deinit(); _ = try p.setTestFile("alpha one\nbeta\nalphabet\n"); - typeKeys(p, "/alpha"); + slash(p, "/alpha"); for (0..2) |_| { const qid = queryPane(p).?; try pardes.dump.dumpState(p); @@ -2245,7 +2251,7 @@ test "a / query: Enter lands and freezes, the register filled, n and N step sile const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 }); defer p.deinit(); const pane = try p.setTestFile("alpha one\nbeta\nalphabet\ngamma alpha\nalpha two\ndelta\n"); - typeKeys(p, "/alpha"); + slash(p, "/alpha"); const qid = queryPane(p).?; const qp = p.panes[qid].?; const q = qp.query.?; @@ -2274,7 +2280,7 @@ test "a / query: Enter lands and freezes, the register filled, n and N step sile typeKeys(p, "N"); try std.testing.expectEqual(@as(?usize, 3), pane.places.current); // a later `/` reuses the pane: line 1 fresh, the rows the new query's - typeKeys(p, "/"); + slash(p, "/"); try std.testing.expectEqual(qid, queryPane(p).?); try std.testing.expectEqual(qid, p.view().active); try std.testing.expect(!q.frozen); @@ -2419,11 +2425,12 @@ test "* seeds line 1 and keeps the keyboard; SPC b b picks a pane, SPC s s a dec const pane = try p.setTestFile("const alpha = 1;\nfn beta() void {\n _ = alpha;\n}\nfn gamma() void {}\n"); p.gpa.free(pane.file.?.path); pane.file.?.path = try p.gpa.dupe(u8, "/tmp/x.zig"); - // `*` on `const`: line 1 `/\bconst\b`, the keyboard still in the text + // `*` on `const`: its places and the pane's search word, no query + // pane, the keyboard still in the text (Prompt.zig) typeKeys(p, "e*"); - const qid = queryPane(p).?; + try std.testing.expect(queryPane(p) == null); try std.testing.expectEqual(@as(usize, 0), p.view().active); - try std.testing.expect(std.mem.startsWith(u8, lineOne(p.panes[qid].?.file.?.content), "/")); + try std.testing.expect(pane.trail.n == 1 and pane.trail.steps[0] == .search); try std.testing.expect(pane.places.started); typeKeys(p, "n"); try std.testing.expectEqual(@as(?usize, 0), pane.places.current); @@ -2433,7 +2440,6 @@ test "* seeds line 1 and keeps the keyboard; SPC b b picks a pane, SPC s s a dec p.view().active = 0; leader(p, "bb"); const bid = queryPane(p).?; - try std.testing.expectEqual(bid, qid); try std.testing.expectEqual(Source.panes, p.panes[bid].?.query.?.source); try std.testing.expect(p.panes[bid].?.query.?.total >= 1); // SPC s s: the declarations, fuzzy; Enter lands on the line @@ -2512,7 +2518,7 @@ test "B1 on a query pane's rows places the caret and selects, nothing else, the const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 }); defer p.deinit(); const pane = try p.setTestFile("alpha one\nbeta\nalphabet\ngamma alpha\nalpha two\ndelta\n"); - typeKeys(p, "/alpha"); + slash(p, "/alpha"); const qid = queryPane(p).?; const qp = p.panes[qid].?; const q = qp.query.?; diff --git a/core/Stream.zig b/core/Stream.zig index 2f700cb4..a933c014 100644 --- a/core/Stream.zig +++ b/core/Stream.zig @@ -1343,7 +1343,9 @@ test "Stream: a big text's declarations are parsed on a worker, never the loop, p.stream.cancelParse(); shell.q.deinit(); } + // `/` asks in the tag; Alt-Enter keeps it as the query pane (Prompt.zig). for ("/needle") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); + p.update(.{ .key = .{ .cp = pardes.Key.enter, .alt = true } }); const qid = for (p.panes, 0..) |slot, i| { if (slot) |qp| if (qp.query != null) break i; } else return error.NoQueryPane; diff --git a/core/Trail.zig b/core/Trail.zig index 7166d810..0ea893e2 100644 --- a/core/Trail.zig +++ b/core/Trail.zig @@ -38,8 +38,10 @@ cur: u8 = 0, /// Kept, or edited since it was shown: it no longer walks (§6.5). held: bool = false, +/// `cur` is at most `n`: a held pane's (keep, a search's or a recipe's +/// word alone) has no current place, past its steps. pub fn lastCur(t: *const Trail) usize { - return t.n -| 1; + return t.n; } /// One step of a walk, as its word says it (§2 "trail word"). @@ -194,6 +196,31 @@ fn show(p: *Pardes, id: usize, path: []const u8, at: Spot) !usize { return free; } +/// `s`, a search's or a recipe's word, the pane's one of its kind (§7.3, +/// §7.5): the one it had goes, and it is the newest back step. +pub fn setWord(t: *Trail, s: Step) void { + var w: u8 = 0; + for (t.steps[0..t.n], 0..) |old, i| { + if (std.meta.activeTag(old) == std.meta.activeTag(s)) { + if (i < t.cur) t.cur -= 1; + continue; + } + t.steps[w] = old; + w += 1; + } + t.n = w; + 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; + } + 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; +} + /// 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 @@ -246,12 +273,13 @@ 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 "·"; - return switch (s) { + const s = &t.steps[i]; + if (s.* != .owner and i < t.cur and t.cur - i > shown_steps) return "·"; + // The step itself, not a copy: a word's text is the step's own bytes. + return switch (s.*) { .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(), + .list, .search, .recipe => |*w| w.text.slice(), }; } @@ -285,6 +313,14 @@ pub fn bytes(t: *const Trail, part: Part) usize { return n; } +/// Where back step `i`'s word is in what `write` writes for the back steps. +pub fn spanOf(t: *const Trail, i: usize) [2]usize { + var buf: [max_text + 16]u8 = undefined; + var x: usize = 0; + for (0..i) |j| x += wordOf(t, j, &buf).len + sep.len; + return .{ x, x + wordOf(t, i, &buf).len }; +} + /// 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 { @@ -302,8 +338,8 @@ pub fn stepAt(t: *const Trail, part: Part, off: usize) ?u8 { } /// Look on step `i` of pane `id`'s trail (§6.3): a place is gone back or -/// forward to, the owner focused; a list, a search or a recipe is the -/// pickers' and the prompts' to take (not yet: said). +/// forward to, the owner focused, a search lit again (Prompt.zig); a list +/// or a recipe is the pickers' and 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]) { @@ -311,7 +347,8 @@ pub fn lookStep(p: *Pardes, id: usize, i: u8) void { .owner => |serial| if (p.paneBySerial(serial)) |owner| { p.view().active = owner; } else p.reportFailure(id, "walk: its owner is closed"), - .list, .search, .recipe => p.setMessage(.at(id), "walk: a list, a search or a recipe is not walked yet"), + .search => pardes.Prompt.lookWord(p, id), + .list, .recipe => p.setMessage(.at(id), "walk: a list or a recipe is not walked yet"), } } @@ -321,7 +358,8 @@ 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, .search, .recipe => p.setMessage(.at(id), "walk: a list, a search or a recipe is not run again yet"), + .search => pardes.Prompt.execWord(p, id), + .list, .recipe => p.setMessage(.at(id), "walk: a list or a recipe is not run again yet"), } } diff --git a/core/body_layer.zig b/core/body_layer.zig index 4176514b..de822674 100644 --- a/core/body_layer.zig +++ b/core/body_layer.zig @@ -347,6 +347,7 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane panes.Tables.paint(p, s, pane, r, tx, tw, body_h); drawWrapMarkers(p, s, pane, r, tx, tw, body_h, pane_bg); pane.places.paint(p, s, pane, r, body_h); + pardes.Prompt.paintGutter(p, s, pane, r, body_h); panes.Query.paint(p, s, pane, r, body_h); } else if (pane.isTerminal()) { ansi.recolor(p, s, pane, r, tx, tw, body_h, body); diff --git a/core/config.zig b/core/config.zig index 6adebe1b..a3d0fb84 100644 --- a/core/config.zig +++ b/core/config.zig @@ -266,6 +266,7 @@ pub const tag_tty = "$"; pub const command_line: []const Chord = &.{.{ .cp = ':' }}; pub const search: []const Chord = &.{.{ .cp = '/' }}; +pub const search_back: []const Chord = &.{.{ .cp = '?' }}; pub const search_next: []const Chord = &.{.{ .cp = 'n' }}; pub const search_prev: []const Chord = &.{.{ .cp = 'N' }}; /// Typing on a query pane's line 1 (Query.zig): the next and the previous diff --git a/core/draw.zig b/core/draw.zig index 3365f0a8..0b6cebcf 100644 --- a/core/draw.zig +++ b/core/draw.zig @@ -979,6 +979,8 @@ fn paintPaneTag(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, // 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); + // A search word its places no longer light, dimmed (Prompt.zig). + if (pardes.Prompt.unlit(pane)) |span| inkTag(p, s, shown, lines[0..rows], top, tx, tag_y, tw, span[0], @min(span[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| { diff --git a/core/modal.zig b/core/modal.zig index fda948a2..41ec6739 100644 --- a/core/modal.zig +++ b/core/modal.zig @@ -160,6 +160,7 @@ pub const Normal = struct { macro_replay, repeat_insert, search, + search_back, search_next, search_prev, search_selection, @@ -305,6 +306,7 @@ pub const Normal = struct { .macro_replay, .repeat_insert, .search, + .search_back, .search_next, .search_prev, .search_selection, diff --git a/core/normal.zig b/core/normal.zig index c59a847c..307f1296 100644 --- a/core/normal.zig +++ b/core/normal.zig @@ -1088,7 +1088,7 @@ fn shrinkSelToLineBounds(tab: u16, t: *Text, text: []const u8, range: modal.Sele pub fn textRole(role: modal.Normal.Role, tree: bool) bool { return switch (role) { .all_children, .all_siblings, .expand_node, .goto_class, .goto_comment, .goto_entry, .goto_function, .goto_parameter, .goto_test, .goto_xml_element, .next_sibling, .parent_node_end, .parent_node_start, .prev_sibling, .shrink_node => tree, - .append_output, .command_line, .format, .goto_callstack, .goto_change, .goto_declaration, .goto_definition, .goto_diagnostic, .goto_diagnostic_end, .goto_implementation, .goto_references, .goto_type_definition, .goto_view_bottom, .goto_view_top, .goto_word, .half_page_down, .half_page_up, .insert_output, .keep_pipe, .keep_regex, .leader, .macro_record, .macro_replay, .page_down, .page_up, .pipe_selection, .pipe_selection_to, .remove_regex, .repeat_insert, .search, .search_next, .search_prev, .select_regex, .split_regex, .view_bottom, .view_center, .view_middle, .view_scroll_down, .view_scroll_up, .view_top => false, + .append_output, .command_line, .format, .goto_callstack, .goto_change, .goto_declaration, .goto_definition, .goto_diagnostic, .goto_diagnostic_end, .goto_implementation, .goto_references, .goto_type_definition, .goto_view_bottom, .goto_view_top, .goto_word, .half_page_down, .half_page_up, .insert_output, .keep_pipe, .keep_regex, .leader, .macro_record, .macro_replay, .page_down, .page_up, .pipe_selection, .pipe_selection_to, .remove_regex, .repeat_insert, .search, .search_back, .search_next, .search_prev, .select_regex, .split_regex, .view_bottom, .view_center, .view_middle, .view_scroll_down, .view_scroll_up, .view_top => false, else => true, }; } @@ -1107,6 +1107,12 @@ pub fn textAction(e: Editor, t: *Text, a: modal.Normal.Action) edit.Error!void { if (comptime Editor.lib) return; // typed again by a macro, Esc is only helix's if (e.p.macro.replaying > 0) return; + // The first Esc clears a search's tints (pick-ui SPEC §7.3, + // §10.4's first step); its word stays in the trail, dimmed. + if (t.what == .body) if (t.pane()) |pane| if (pane.places.started and pane.places.provenance == .search) { + pane.places.clear(e.p.gpa); + return; + }; tagline.exitHeader(e.p); // out of a header too, as Shift-Esc return exec.runBuiltin(e.p, .Last, e.p.view().active, "", null); }, @@ -1253,14 +1259,13 @@ pub fn textAction(e: Editor, t: *Text, a: modal.Normal.Action) edit.Error!void { .decrement => return edit.normalAdjustNumber(e, t, -@as(i64, @intCast(a.count))), .search_selection, .search_selection_word => { try searchSelection(e, t, text, a.role == .search_selection_word); - // The pattern is line 1 of this text's query pane, made or - // reused, the keyboard staying here: n and N step its places. + // The pattern lights its places and is the pane's search word, + // no prompt asked (Prompt.zig): n and N step them. const pane = t.pane() orelse return; if (t.what == .body and pane.file != null and pane.query == null) { const name = if (e.register.* != 0) e.register.* else '/'; const pat = e.registers.value(name, 0) orelse return; - panes.Query.open(e.p, e.p.view().active, .text, pat, false); - pane.places.provenance = .search; + Prompt.star(e.p, pane, pat); } }, // prefix keys: what they begin is the command @@ -1385,10 +1390,11 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error! if (t.what == .body) return Prompt.open(p, pane, Prompt.ofBehavior(how)); return panes.startPrompt(p, pane, t, .{ .pipe = how }); }, - // `/` in a text is its query pane's line 1 (Query.zig); a - // terminal's still asks on the notice band. - .search => if (pane.file != null and t.what == .body) - panes.Query.open(p, v.active, .text, "", true) + // `/` and `?` in a file's text search it in its tag (Prompt.zig), + // Alt-Enter keeping the places as its query pane's rows (Query.zig); + // a terminal's still asks on the notice band. + .search, .search_back => if (pane.file != null and t.what == .body) + return Prompt.open(p, pane, if (a.role == .search) .search else .search_back) else return panes.startPrompt(p, pane, &pane.body, .{ .search = config.search_marker }), // In a file's text, n and N step its places while they answer for @@ -1397,9 +1403,12 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error! // places the rows hold, never the disk (a motion). .search_next, .search_prev => if (t.what == .body and pane.addon != null) 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 + else if (t.what == .body and pane.file != null and pane.places.answersN(p, pane)) { + // The pane's search word says where it went (Prompt.zig). + const was = pane.places.current; + pane.places.step(p, pane, a.role == .search_next, a.count, t.select); + return Prompt.stepped(p, v.active, a.role == .search_next, was); + } else return searchStep(p.editor(), t, text, a.role == .search_next, a.count), .goto_word => return startJump(p, pane, t), .macro_record => { diff --git a/test/perf.zig b/test/perf.zig index f36d64ac..4ba061e1 100644 --- a/test/perf.zig +++ b/test/perf.zig @@ -1822,6 +1822,38 @@ fn measureSearch(io: std.Io) !void { } slow.report("fill", pattern, set.hits.items.len); } + + // A key typed into a text prompt in the tag (core/Prompt.zig) on a 1 MB + // file, with its frame: `/` from the middle (its places from the view on, + // a frame's budget a tick after), `s` over the whole text (`%`). + const mb: Fixture = .{ .name = "onemeg", .lines = 17_000, .cols = 60 }; + const mb_path = try std.fmt.allocPrint(gpa, "{s}/{s}.zig", .{ dir, mb.name }); + defer gpa.free(mb_path); + const mb_text = try generate(mb); + try writeFile(mb_path, mb_text); + std.debug.print("prompt keys over {d} bytes\n", .{mb_text.len}); + gpa.free(mb_text); + for ([_][]const u8{ "/", "%s" }) |opener| for ([_][]const u8{ "helper", "qqq" }) |typed| { + const core = try boot(); + defer core.deinit(); + pardes.look.lookAt(core, 0, mb_path); + pump(core); + const id = filePane(core) orelse return error.OpenDidNotOpenFile; + const pane = core.panes[id].?; + seek(pane, mb, 0); + pane.file.?.scroll = mb.lines / 2; + pane.body.cur_row = @intCast(mb.lines / 2); + _ = try frame(core); + for (opener) |c| core.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); + _ = try frame(core); + for (typed, 0..) |c, n| { + const was = counter.read(); + const t0 = nowNs(); + core.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); + _ = try frame(core); + std.debug.print("prompt {s} \"{s}\": {d} instructions, {d} us (key and frame)\n", .{ opener, typed[0 .. n + 1], counter.read() -| was, (nowNs() -| t0) / 1000 }); + } + }; } /// The longest of a scan's calls. diff --git a/test/snapshots/fsearch.golden b/test/snapshots/fsearch.golden index 71a9900a..6997dbcb 100644 --- a/test/snapshots/fsearch.golden +++ b/test/snapshots/fsearch.golden @@ -19,69 +19,82 @@ | /tmp/pardes-snap/fsearch/cwd Term+bash Save Mode Filter Collapse Del | ls | g.txt -== snap slash grid=180x31 cursor=3,10 -|9: ^ +Search 0 Del -|10: / -|11: -|12: -|13: -|14: -|15: -|16: -== snap typing grid=180x31 cursor=7,10 -|9: ^ +Search 1/3 Del -|10: /MARK -|11: g.txt:2:1 MARK a -|12: g.txt:6:1 MARK b -|13: g.txt:10:1 MARK c +== snap slash grid=180x31 cursor=39,6 +|6: ^ /tmp/pardes-snap/fsearch/cwd/g.txt / ⏎ land · M-⏎ as a list · C-r history · esc +== snap typing grid=180x31 cursor=43,6 +|6: ^ /tmp/pardes-snap/fsearch/cwd/g.txt / MARK = Look /MARK/ 1/3 · 3 lines ⏎ land · M-⏎ +|7: as a list · C-r history · esc +|8: 1 l1 +|9: 2▸MARK a +|10: 3 l3 +|11: 4 l4 +|12: 5 l5 +|13: 6▪MARK b +|14: 7 l7 +|15: 8 l8 +|16: 9 l9 == style typing grid=180x31 |0: 0-1 d,#1d2824, 2-179 #b2c3b8,#1d2824, |1: 0-1 d,#887455, 2-89 #becfc4,#314738, 90-91 #becfc4,#887455, 92-179 #b2c3b8,#1d2824, -|2: 0-1 d,#496656, 2-30 #b2c3b8,#1d2824, 31-40 #d3b0d9,#1d2824, 41-89 #b2c3b8,#1d2824, 90-91 #b2c3b8,#496656, 92-120 #b2c3b8,#1d2824, 121-130 #d3b0d9,#1d2824, 131-179 #b2c3b8,#1d2824, -|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|4: 0-0 d,#608269, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|5: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, -|6: 0-1 d,#496656, 2-30 #b2c3b8,#1d2824, 31-36 #d3b0d9,#1d2824, 37-89 #b2c3b8,#1d2824, 90-90 #b2c3b8,#608269, 91-179 #b2c3b8,#0d1410, -|7: 0-0 d,#5e4923, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|8: 0-0 d,#5e4923, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f5f7ee,#3c614a, 11-11 #f5f7ee,#0d1410, 12-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|9: 0-1 #000000,#add38a, 2-89 #becfc4,#314738, 90-90 #becfc4,#608269, 91-179 #becfc4,#0d1410, -|10: 0-0 d,#608269, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|11: 0-0 d,#608269, 1-1 d,#0d1410, 2-15 #59675c,#243a2d, 16-19 #f7e4a5,#5e4923, 20-20 #f7e4a5,#243a2d, 21-89 #e5eee5,#243a2d, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|12: 0-0 d,#608269, 1-1 d,#0d1410, 2-15 #59675c,#0d1410, 16-19 #f7e4a5,#352e19, 20-20 #f7e4a5,#0d1410, 21-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|13: 0-0 d,#608269, 1-1 d,#0d1410, 2-15 #59675c,#0d1410, 16-19 #f7e4a5,#352e19, 20-20 #f7e4a5,#0d1410, 21-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|14: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, -|15: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, -|16: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, -|17: 0-1 d,#496656, 2-30 #b2c3b8,#1d2824, 31-40 #d3b0d9,#1d2824, 41-89 #b2c3b8,#1d2824, 90-90 #b2c3b8,#608269, 91-179 #b2c3b8,#0d1410, -|18: 0-0 d,#608269, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|19: 0-0 d,#608269, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|20: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, -|21: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, -|22: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, -|23: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, -|24: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, -|25: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, -|26: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, -|27: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, -|28: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, -|29: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, -|30: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, -== snap ctrln grid=180x31 cursor=7,10 -|7: 5 l5 -|8: 6 MARK b -|9: ^ +Search 2/3 Del +|2: 0-1 d,#496656,f 2-30 #b2c3b8,#1d2824,f 31-40 #d3b0d9,#1d2824,f 41-89 #b2c3b8,#1d2824,f 90-91 #b2c3b8,#496656,f 92-120 #b2c3b8,#1d2824,f 121-130 #d3b0d9,#1d2824,f 131-179 #b2c3b8,#1d2824,f +|3: 0-0 d,#608269,f 1-1 d,#0d1410,f 2-89 #e5eee5,#0d1410,f 90-90 #e5eee5,#608269,f 91-179 #e5eee5,#0d1410,f +|4: 0-0 d,#608269,f 1-1 d,#0d1410,f 2-89 #e5eee5,#0d1410,f 90-90 #e5eee5,#608269,f 91-179 #e5eee5,#0d1410,f +|5: 0-0 d,#608269,f 1-89 d,#0d1410,f 90-90 d,#608269,f 91-179 d,#0d1410,f +|6: 0-1 #000000,#add38a, 2-30 #becfc4,#314738, 31-36 #dfbce5,#314738, 37-37 #add38a,#314738,b 38-38 #add38a,#314738, 39-42 #becfc4,#314738, 43-50 #becfc4,#314738,f 51-76 #becfc4,#314738, 77-89 #becfc4,#314738,f 90-90 #becfc4,#608269,f 91-179 #becfc4,#0d1410,f +|7: 0-1 d,#314738, 2-30 #becfc4,#314738,f 31-89 #becfc4,#314738, 90-90 #becfc4,#608269,f 91-179 #becfc4,#0d1410,f +|8: 0-0 d,#e5eee5, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269,f 91-179 #e5eee5,#0d1410,f +|9: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-5 #616f64,#0d1410,b 6-6 #add38a,#0d1410,b 7-10 #f5f7ee,#3c614a, 11-11 #f5f7ee,#0d1410, 12-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269,f 91-179 #e5eee5,#0d1410,f +|10: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269,f 91-179 #e5eee5,#0d1410,f +|11: 0-0 d,#5e4923, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269,f 91-179 #e5eee5,#0d1410,f +|12: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269,f 91-179 #e5eee5,#0d1410,f +|13: 0-0 d,#608269, 1-4 d,#0d1410, 5-5 #59675c,#0d1410, 6-6 #add38a,#0d1410, 7-10 #e5eee5,#352e19, 11-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269,f 91-179 #e5eee5,#0d1410,f +|14: 0-0 d,#5e4923, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269,f 91-179 #e5eee5,#0d1410,f +|15: 0-0 d,#152019, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269,f 91-179 #e5eee5,#0d1410,f +|16: 0-0 d,#152019, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269,f 91-179 #e5eee5,#0d1410,f +|17: 0-1 d,#496656,f 2-30 #b2c3b8,#1d2824,f 31-40 #d3b0d9,#1d2824,f 41-89 #b2c3b8,#1d2824,f 90-90 #b2c3b8,#608269,f 91-179 #b2c3b8,#0d1410,f +|18: 0-0 d,#608269,f 1-1 d,#0d1410,f 2-89 #e5eee5,#0d1410,f 90-90 #e5eee5,#608269,f 91-179 #e5eee5,#0d1410,f +|19: 0-0 d,#608269,f 1-1 d,#0d1410,f 2-89 #e5eee5,#0d1410,f 90-90 #e5eee5,#608269,f 91-179 #e5eee5,#0d1410,f +|20: 0-0 d,#608269,f 1-89 d,#0d1410,f 90-90 d,#608269,f 91-179 d,#0d1410,f +|21: 0-0 d,#608269,f 1-89 d,#0d1410,f 90-90 d,#608269,f 91-179 d,#0d1410,f +|22: 0-0 d,#608269,f 1-89 d,#0d1410,f 90-90 d,#608269,f 91-179 d,#0d1410,f +|23: 0-0 d,#608269,f 1-89 d,#0d1410,f 90-90 d,#608269,f 91-179 d,#0d1410,f +|24: 0-0 d,#608269,f 1-89 d,#0d1410,f 90-90 d,#608269,f 91-179 d,#0d1410,f +|25: 0-0 d,#608269,f 1-89 d,#0d1410,f 90-90 d,#608269,f 91-179 d,#0d1410,f +|26: 0-0 d,#608269,f 1-89 d,#0d1410,f 90-90 d,#608269,f 91-179 d,#0d1410,f +|27: 0-0 d,#608269,f 1-89 d,#0d1410,f 90-90 d,#608269,f 91-179 d,#0d1410,f +|28: 0-0 d,#608269,f 1-89 d,#0d1410,f 90-90 d,#608269,f 91-179 d,#0d1410,f +|29: 0-0 d,#608269,f 1-89 d,#0d1410,f 90-90 d,#608269,f 91-179 d,#0d1410,f +|30: 0-0 d,#608269,f 1-89 d,#0d1410,f 90-90 d,#608269,f 91-179 d,#0d1410,f +== snap ctrln grid=180x31 cursor=43,6 == snap landed grid=180x31 cursor=10,8 -|9: +Search 2/3 Save Undock Del -== snap n grid=180x31 cursor=10,8 -|7: 9 l9 -|8: 10 MARK c -== snap N grid=180x31 cursor=10,7 -|7: 6 MARK b -|8: 7 l7 -== snap cancel grid=180x31 cursor=10,7 -== snap nomatch grid=180x31 cursor=7,10 -|9: ^ +Search 0 Del -|10: /zzqq -|11: -|12: -|13: +|6: /MARK/ 1/3 › /tmp/pardes-snap/fsearch/cwd/g.txt Save Term Collapse Follow Del +|7: 1 l1 +|8: 2 MARK a +|9: 3 l3 +|10: 4 l4 +|11: 5 l5 +|12: 6 MARK b +|13: 7 l7 +|14: 8 l8 +|15: 9 l9 +|16: 10 MARK c +== snap n grid=180x31 cursor=10,12 +|6: /MARK/ 2/3 › /tmp/pardes-snap/fsearch/cwd/g.txt Save Term Collapse Follow Del +|7: 1 l1 /MARK/ 2/3 · line 6 +== snap N grid=180x31 cursor=10,8 +|6: /MARK/ 1/3 › /tmp/pardes-snap/fsearch/cwd/g.txt Save Term Collapse Follow Del +|7: 1 l1 /MARK/ 1/3 · line 2 +== snap cancel grid=180x31 cursor=10,8 +|7: 1 l1 +== snap nomatch grid=180x31 cursor=56,6 +|6: ^ /MARK/ 1/3 › /tmp/pardes-snap/fsearch/cwd/g.txt / zzqq = Look /zzqq/ 0 ⏎ land · M-⏎ +|7: as a list · C-r history · esc +|8: 1 l1 +|9: 2 MARK a +|10: 3 l3 +|11: 4 l4 +|12: 5 l5 +|13: 6 MARK b +|14: 7 l7 +|15: 8 l8 +|16: 9 l9 diff --git a/test/snapshots/lookrange.golden b/test/snapshots/lookrange.golden index c677fb8f..6c414ea9 100644 --- a/test/snapshots/lookrange.golden +++ b/test/snapshots/lookrange.golden @@ -69,32 +69,29 @@ |15: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-11 #e5eee5,#0d1410, 12-149 #f5f7ee,#3c614a, |16: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-10 #f5f7ee,#3c614a, 11-149 #f5f7ee,#0d1410, == snap hit1 grid=150x31 cursor=17,15 -|21: +Search 2/2 Save Undock Del -|22: /NEEDLE -|23: r.txt:7:4 gg NEEDLE gg -|24: r.txt:8:6 hhhh NEEDLE +|7: /NEEDLE/ 2/2 › /tmp/pardes-snap/lookrange/cwd/r.txt Save Term Collapse Follow Del == style hit1 grid=150x31 +|7: 0-1 d,#add38a, 2-47 #becfc4,#314738, 48-53 #dfbce5,#314738, 54-149 #becfc4,#314738, |14: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-9 #e5eee5,#0d1410, 10-15 #e5eee5,#352e19, 16-149 #e5eee5,#0d1410, |15: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-11 #e5eee5,#0d1410, 12-17 #f5f7ee,#3c614a, 18-149 #f5f7ee,#0d1410, -|16: 0-0 d,#5e4923, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, -|18: 0-0 d,#e5eee5, 1-149 d,#0d1410, -|21: 0-1 d,#496656, 2-149 #b2c3b8,#1d2824, -|22: 0-0 d,#608269, 1-1 d,#0d1410, 2-149 #e5eee5,#0d1410, -|23: 0-0 d,#608269, 1-1 d,#0d1410, 2-14 #59675c,#0d1410, 15-17 #e5eee5,#0d1410, 18-23 #f7e4a5,#352e19, 24-24 #f7e4a5,#0d1410, 25-149 #e5eee5,#0d1410, -|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-14 #59675c,#243a2d, 15-19 #e5eee5,#243a2d, 20-25 #f7e4a5,#5e4923, 26-149 #f7e4a5,#243a2d, +|16: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, +|23: 0-0 d,#5e4923, 1-149 d,#0d1410, +|25: 0-0 d,#e5eee5, 1-149 d,#0d1410, == snap hit2 grid=150x31 cursor=15,14 +|7: /NEEDLE/ 1/2 ↻ › /tmp/pardes-snap/lookrange/cwd/r.txt Save Term Collapse Follow Del +|8: 1 aaaa /NEEDLE/ 1/2 ↻ · line 7 == style hit2 grid=150x31 +|7: 0-1 d,#add38a, 2-49 #becfc4,#314738, 50-55 #dfbce5,#314738, 56-149 #becfc4,#314738, +|8: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-124 #e5eee5,#0d1410, 125-125 #e5eee5,#1d2824, 126-149 #b2c3b8,#1d2824, |14: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-9 #e5eee5,#0d1410, 10-15 #f5f7ee,#3c614a, 16-16 #f5f7ee,#0d1410, 17-149 #e5eee5,#0d1410, |15: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-11 #e5eee5,#0d1410, 12-17 #e5eee5,#352e19, 18-149 #e5eee5,#0d1410, -|16: 0-0 d,#e5eee5, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, -|18: 0-0 d,#5e4923, 1-149 d,#0d1410, -|23: 0-0 d,#608269, 1-1 d,#0d1410, 2-14 #59675c,#0d1410, 15-17 #e5eee5,#0d1410, 18-23 #f7e4a5,#5e4923, 24-24 #f7e4a5,#0d1410, 25-149 #e5eee5,#0d1410, -|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-14 #59675c,#243a2d, 15-19 #e5eee5,#243a2d, 20-25 #f7e4a5,#352e19, 26-149 #f7e4a5,#243a2d, +|23: 0-0 d,#e5eee5, 1-149 d,#0d1410, +|25: 0-0 d,#5e4923, 1-149 d,#0d1410, == snap back grid=150x31 cursor=17,15 +|7: /NEEDLE/ 2/2 ↻ › /tmp/pardes-snap/lookrange/cwd/r.txt Save Term Collapse Follow Del +|8: 1 aaaa /NEEDLE/ 2/2 ↻ · line 8 == style back grid=150x31 |14: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-9 #e5eee5,#0d1410, 10-15 #e5eee5,#352e19, 16-149 #e5eee5,#0d1410, |15: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-11 #e5eee5,#0d1410, 12-17 #f5f7ee,#3c614a, 18-149 #f5f7ee,#0d1410, -|16: 0-0 d,#5e4923, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, -|18: 0-0 d,#e5eee5, 1-149 d,#0d1410, -|23: 0-0 d,#608269, 1-1 d,#0d1410, 2-14 #59675c,#0d1410, 15-17 #e5eee5,#0d1410, 18-23 #f7e4a5,#352e19, 24-24 #f7e4a5,#0d1410, 25-149 #e5eee5,#0d1410, -|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-14 #59675c,#243a2d, 15-19 #e5eee5,#243a2d, 20-25 #f7e4a5,#5e4923, 26-149 #f7e4a5,#243a2d, +|23: 0-0 d,#5e4923, 1-149 d,#0d1410, +|25: 0-0 d,#e5eee5, 1-149 d,#0d1410, -- cgit v1.3 From 3da01ac676283c6d20ca6f2c0321b9dfe8cc59cd Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 24 Nov 2026 22:04:55 -0300 Subject: Prompt: sam prompts one after another make one recipe word, and `s S K A-K` show their scope and what K drops (walk UI, pick-ui SPEC.md §7.1's table, §7.5, item 3 of line E): a sam prompt (`s S K A-K | A-|`, sam's `x y g v | >`) right after another of the same pane's, no key between (Prompt.chain, ended by any key at rest but one that opens such a prompt: Prompt.keyAtRest from keys.handleKey, by a search, by `! A-! $`), extends the pane's one recipe word in its trail, the Edit line it is (`Edit x/self../ g/a/ |tr a-z A-Z`, Trail.setWord); a selecting one that found nothing adds no link; Look on the word puts back the selections its sam prompts made (Pane.recipe_sels, recipe_pri), Exec runs it as Edit (edit_cmd.run, sam's dot the primary selection: a recipe of selections alone prints its matches, as acme's Edit does); while `s S K A-K` is typed the lines the selections it began with cover are fenced `┃` in the gutter, and K's and A-K's selections that would go are dimmed and struck through (a visible line's ranges found by a binary search, never all of them a frame); wire 38; THE FAULTS THE 40,000-SEED FUZZ MET over a session holding a recipe, a search word and an open prompt (a dump or an image cut, flipped and grown loaded and used): View.focus_told's pane slot was never held to the panes (Core.zig reportFocus indexed p.panes past 64: a damaged image's), now a `.index` of its own; A's Field's caret was not held to its text (Field.insert copied past the buffer at caret 513), now a `.place`; Places.current past its places (Places.addTicks's tickOf, the prompt's count and the gutter) taken as none; a search word's `/re/` length past its text taken as its text's; a user loading a damaged Dump could have hit the first three; TEST FIRST: Prompt.zig "sam prompts one after another make one recipe word ..."; fuzz "a dump and an image cut" at 40,000 join and 1,779 image seeds (a temporary edit, put back): pass; the soak, 5 clients: diverged 0, unequal 0 at rtt 30/80/207, quiet checks 413/0 426/0 619/0, the corpus 22 scenes the same, exit 0; goldens pipe (the recipe word in the trail), selregex (the fence); core-test 1017/1183 (166 skipped), shell-test 1230/1233, pane-test 182/184, behaviour-test and its replay 274/277 (the failures A's, as on item 1), process-test A's six and none of mine (`exec` failed once under a load of 8 and passes alone), term-test 17/17, kitty-test 45/45 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- abi/wire.zig | 5 +- core/Core.zig | 8 +- core/Field.zig | 8 +- core/Places.zig | 3 +- core/Prompt.zig | 265 +++++++++++++++++++++++++++++++++++++++-- core/Trail.zig | 10 +- core/keys.zig | 1 + core/panes.zig | 5 + test/daemon.py | 2 +- test/snapshots/pipe.golden | 4 +- test/snapshots/selregex.golden | 47 +++++--- 11 files changed, 317 insertions(+), 41 deletions(-) diff --git a/abi/wire.zig b/abi/wire.zig index cbe255f4..0cb55a32 100644 --- a/abi/wire.zig +++ b/abi/wire.zig @@ -10,6 +10,9 @@ const pardes = @import("core"); const config = @import("pardes_options"); const build_info = @import("build_info"); +/// 38: a pane's recipe's selections (`Pane.recipe_sels`, `recipe_pri`) +/// and the pane whose recipe a view's next sam prompt extends +/// (`Prompt.chain`) in the dump and the digest; /// 37: a view's text prompt in its tag (walk UI: `TagState.prompt`, which /// prompt, its history's place, what its field found) and the session's /// prompt histories (`prompt_history`) in the dump and the digest; @@ -83,7 +86,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 = 37; +pub const version: u16 = 38; /// The terminal's build and the window's step alike (`semantics`). const family = switch (config.platform) { diff --git a/core/Core.zig b/core/Core.zig index 95f3a3a8..e718149e 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -153,7 +153,13 @@ pub const View = struct { /// Whether the host window has the keyboard (Event.focus), and the pane /// whose program was last told it has it (reportFocus). window_focused: bool = true, - focus_told: ?struct { id: usize, serial: u32 } = null, + focus_told: ?struct { + // A slot of the session's, looked at before it is used, as + // `active` is (a damaged image's indexed past the panes). + pub const replica = .{ .index = .{.{ "id", Pardes, "panes" }} }; + id: usize, + serial: u32, + } = null, hover_col: u16 = 0, hover_row: u16 = 0, pointer_raw_col: u16 = 0, diff --git a/core/Field.zig b/core/Field.zig index 7b8ea399..2f668001 100644 --- a/core/Field.zig +++ b/core/Field.zig @@ -19,7 +19,13 @@ len: u16 = 0, /// A byte offset in the text, at a character's start. caret: u16 = 0, -pub const replica = .{ .len = .{.{ "buf", "len" }} }; +/// The caret held to the text there is (walk.zig `.place`): a damaged +/// image's past it typed out of the buffer. +pub const replica = .{ .len = .{.{ "buf", "len" }}, .place = .{.{ "caret", "lastCaret" }} }; + +pub fn lastCaret(f: *const Field) usize { + return f.len; +} pub fn text(f: *const Field) []const u8 { return f.buf[0..f.len]; diff --git a/core/Places.zig b/core/Places.zig index 4c04555b..7ffcb6cb 100644 --- a/core/Places.zig +++ b/core/Places.zig @@ -733,7 +733,8 @@ pub fn addTicks(set: *Places, p: *Pardes, pane: *Pane, s: *Surface, owner: u8) v if (!set.shows(pane)) return; const f = &pane.file.?; set.buildTicks(p, f); - const cur = if (set.current) |c| set.tickOf(p, f, c) else null; + // (A damaged image's `current` may name no place: none current then.) + const cur = if (set.current) |c| (if (c < set.hits.items.len) set.tickOf(p, f, c) else null) else null; for (set.ticks.items) |b| { if (s.nrail_ticks == s.rail_ticks.len) return; s.rail_ticks[s.nrail_ticks] = .{ .owner = owner, .at = b, .current = cur != null and cur.? == b }; diff --git a/core/Prompt.zig b/core/Prompt.zig index 53f6cd5c..1c0b1d31 100644 --- a/core/Prompt.zig +++ b/core/Prompt.zig @@ -6,6 +6,11 @@ //! 6 lines`), its effect drawn live in the body on every key; Enter applies //! it and keeps the line in its history, Esc puts the body back. //! +//! A sam prompt (`s S K A-K | A-|`, sam's `x y g v | >`) right after +//! another of the same pane's, no key between, extends one recipe word in +//! the pane's trail, the Edit line it is (`Edit x/self/ |tr a-z A-Z`): Look +//! on it puts back the selections it made, Exec runs it as Edit (SPEC §7.5). +//! //! A view's own (TagState.prompt, the coordinator's R4): its field the //! head's (TagState.field); its histories the session's, three of them //! (`/ ? s S K A-K` share one, the pipes another, `:` its own). A prompt for @@ -60,6 +65,9 @@ seeking: bool = false, /// the places' `hits_gen` `counted`. lines: u32 = 0, counted: u32 = std.math.maxInt(u32), +/// The pane, by serial, whose sam prompt Enter took last with no key since: +/// the next one extends its recipe (0: none). +chain: u32 = 0, /// The session's prompt histories: the lines Enter took, newest last. pub const History = struct { @@ -215,7 +223,17 @@ pub fn open(p: *Pardes, pane: *Pane, op: Op) void { s.host = pane.serial; s.field.clear(); s.rows = .{}; - s.prompt = .{ .op = op, .scope = scope }; + s.prompt = .{ .op = op, .scope = scope, .chain = s.prompt.chain }; +} + +/// A key the tag at rest takes (keys.handleKey): any but one that opens a +/// sam prompt ends the recipe Enter left open (a motion, an edit). +pub fn keyAtRest(p: *Pardes, k: Key) void { + const s = &p.view().tag_state; + if (s.prompt.chain == 0) return; + if (hit(k, config.select_regex) or hit(k, config.split_regex) or hit(k, config.keep_regex) or + hit(k, config.remove_regex) or hit(k, config.pipe_selection) or hit(k, config.pipe_selection_to)) return; + s.prompt.chain = 0; } /// A key in the prompt of the live view's tag: the field's editing keys, @@ -331,10 +349,16 @@ fn commit(p: *Pardes, id: usize, pane: *Pane) void { // helix keeps the pattern in `/` p.registers.put(p.gpa, '/', typed, 0, 1, true) catch |err| return p.reportError(.at(id), "prompt", err); p.registers.last_search = '/'; + // Nothing found: nothing changed, no link. + if (s.prompt.found == 0) return; + link(p, pane, op, typed); + keepSelections(p, pane); return; } if (behavior(op)) |how| { p.registers.put(p.gpa, '|', typed, 0, 1, true) catch |err| return p.reportError(.at(id), "prompt", err); + // `! A-! $` apply, and end the recipe: no Edit line says them. + if (op == .pipe or op == .pipe_to) link(p, pane, op, typed) else s.prompt.chain = 0; return Pipe.submit(p, id, &pane.body, how, typed); } } @@ -344,6 +368,8 @@ fn commit(p: *Pardes, id: usize, pane: *Pane) void { /// `/re/ 3/7` in its trail (SPEC §7.3). fn land(p: *Pardes, id: usize, pane: *Pane, op: Op, pat: []const u8, bad: bool) void { const set = &pane.places; + // A search moves the selection: the recipe ends. + p.view().tag_state.prompt.chain = 0; if (bad) { undo(p, pane, op); return p.setMessage(.at(id), regexMessage(pat)); @@ -431,6 +457,77 @@ pub fn dims(p: *const Pardes, pane: *const Pane) bool { return s.kind == .prompt and searches(s.prompt.op) and s.host == pane.serial and s.prompt.bad; } +// ---- the recipe word (SPEC §7.5) ---- + +fn recipeOf(pane: *Pane) ?*Trail.Word { + for (pane.trail.steps[0..pane.trail.n]) |*step| if (step.* == .recipe) return &step.recipe; + return null; +} + +/// Sam prompt `op`'s `line` as a link of `pane`'s recipe: after the one +/// its last sam prompt left open, else a recipe of its own in place of the +/// pane's one. One past the trail's room starts none. +fn link(p: *Pardes, pane: *Pane, op: Op, line: []const u8) void { + const s = &p.view().tag_state; + var buf: [Trail.max_text]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + const open_recipe = if (s.prompt.chain == pane.serial) recipeOf(pane) else null; + s.prompt.chain = 0; + (if (open_recipe) |r| w.writeAll(r.text.slice()) else w.writeAll("Edit")) catch return; + w.writeByte(' ') catch return; + const said = switch (op) { + .select => samWord(&w, 'x', line), + .split => samWord(&w, 'y', line), + .keep => samWord(&w, 'g', line), + .remove => samWord(&w, 'v', line), + .pipe => w.print("|{s}", .{line}), + .pipe_to => w.print(">{s}", .{line}), + else => return, + }; + said catch return; + var word_: Trail.Word = .{}; + word_.text.set(w.buffered()); + pane.trail.setWord(.{ .recipe = word_ }); + s.prompt.chain = pane.serial; +} + +/// The selections a recipe's sam prompts made, kept for Look on its word. +fn keepSelections(p: *Pardes, pane: *Pane) void { + const text = edit.flatSurface(p.editor(), &pane.body) catch return; + var ranges: [Text.max_selections]modal.Selection = undefined; + const got = pane.body.ranges(text, 0, &ranges); + const kept = p.gpa.dupe(modal.Selection, ranges[0..got.n]) catch return; + p.gpa.free(pane.recipe_sels); + pane.recipe_sels = kept; + pane.recipe_pri = @intCast(got.pri); +} + +/// Look on pane `id`'s recipe word: the selections it made, again. +pub fn lookRecipe(p: *Pardes, id: usize) void { + const pane = p.panes[id] orelse return; + p.view().active = id; + if (pane.recipe_sels.len == 0) return; + const text = edit.flatSurface(p.editor(), &pane.body) catch |err| return p.reportError(.at(id), "recipe", err); + for (pane.recipe_sels) |*r| { + r.anchor = @min(r.anchor, text.len); + r.head = @min(r.head, text.len); + } + pane.body.setRanges(p.settings.tab, text, pane.recipe_sels, &.{}, @min(pane.recipe_pri, pane.recipe_sels.len - 1), true); + pane.body.show(p.settings.tab); +} + +/// Exec on it: the Edit line it is, run on what is selected now +/// (edit_cmd.zig, sam's dot the primary selection). +pub fn execRecipe(p: *Pardes, id: usize) void { + const pane = p.panes[id] orelse return; + const r = recipeOf(pane) orelse return; + var line: [Trail.max_text]u8 = undefined; + const text = r.text.slice(); + @memcpy(line[0..text.len], text); + p.view().active = id; + pardes.edit_cmd.run(p, id, line["Edit ".len..text.len]); +} + // ---- the search word (SPEC §7.3) ---- /// Pane `pane`'s search word, `/re/ 3/7`: one a pane, its `index` the @@ -441,8 +538,14 @@ fn wordOf(pane: *Pane) ?*Trail.Word { } fn patternOf(w: *const Trail.Word) []const u8 { - const end: u16 = @truncate(w.index); - return w.text.slice()[1 .. end - 1]; + const end = patternEnd(w); + return if (end < 2) "" else w.text.slice()[1 .. end - 1]; +} + +/// Where a search word's `/re/` ends: held to its text (a damaged image's +/// says anything). +fn patternEnd(w: *const Trail.Word) u16 { + return std.math.clamp(@as(u16, @truncate(w.index)), @min(2, w.text.len), w.text.len); } /// Whether the places the pane's body shows are its search word's. @@ -472,7 +575,7 @@ fn refresh(pane: *Pane, wrapped: ?bool) void { if (!lights(pane, w)) return; const set = &pane.places; const f = &pane.file.?; - const end: u16 = @truncate(w.index); + const end = patternEnd(w); const round = wrapped orelse (w.index >> 16 != 0); const hits = set.hits.items; const sel = pane.body.primaryRange(f.content, 0); @@ -525,6 +628,7 @@ pub fn stepped(p: *Pardes, id: usize, forward: bool, before: ?usize) void { const set = &pane.places; if (!lights(pane, w)) return; const after = set.current orelse return; + if (after >= set.hits.items.len) return; refresh(pane, if (before) |b| (if (forward) after <= b else after >= b) else false); const index = File.lineIndex(p.gpa, &pane.file.?) catch return; var said: [Trail.max_text + 32]u8 = undefined; @@ -550,8 +654,7 @@ pub fn lookWord(p: *Pardes, id: usize) void { set.search(p, pane, .search, 0, pat, false, null, false); set.fill(p, pane, std.math.maxInt(usize), regexp.Regex.budget); p.view().active = id; - const end: u16 = @truncate(w.index); - const rest = w.text.slice()[end..]; + const rest = w.text.slice()[patternEnd(w)..]; const n = std.fmt.parseInt(usize, std.mem.trim(u8, rest[0 .. std.mem.indexOfScalar(u8, rest, '/') orelse rest.len], " "), 10) catch return; if (n > 0 and n <= set.hits.items.len) set.goTo(p.settings.tab, pane, n - 1, false); } @@ -587,17 +690,21 @@ pub fn unlit(pane: *Pane) ?[2]usize { /// The gutter's marks while a prompt is typed (SPEC §7.1): `▸` on the /// current place's line and `▪` on every other line holding a place (`/ -/// ?`). In the blank after a row's line number, on a line's first row. +/// ?`); `┃` on each line the selections a sam prompt began with cover (`s +/// S K A-K`), its scope. In the blank after a row's line number, on a +/// line's first row. pub fn paintGutter(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, body_h: u16) void { const ts = &p.view().tag_state; - if (ts.kind != .prompt or ts.host != pane.serial or !searches(ts.prompt.op)) return; + if (ts.kind != .prompt or ts.host != pane.serial) return; const f = &(pane.file orelse return); + if (mode(ts.prompt.op) != null) return fence(p, s, pane, r, body_h); + if (!searches(ts.prompt.op)) return; const set = &pane.places; if (!set.shows(pane)) return; const hits = set.hits.items; if (hits.len == 0) return; const tab = p.settings.tab; - const x = r.x + config.GUTTER + (File.gutterWidth(pane) -| File.laneCells(pane) -| pane.layers.heat -| 1); + const x = gutterX(pane, r); const y = p.bodyTop(pane, r); const ink = p.chromeTheme().box; const nlines = File.nlines(p.gpa, f); @@ -612,7 +719,7 @@ pub fn paintGutter(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, body_h: const next = File.lineStart(p.gpa, f, @intCast(line + 1)); const i = Places.firstFrom(hits, ls); if (i == hits.len or hits[i].start >= @max(next, ls + 1)) continue; - const current = if (set.current) |c| hits[c].start >= ls and hits[c].start < @max(next, ls + 1) else false; + const current = if (set.current) |c| c < hits.len and hits[c].start >= ls and hits[c].start < @max(next, ls + 1) else false; var style = s.at(x, y + vr).style; style.fg = .{ .rgb = ink }; s.set(x, y + vr, if (current) "▸" else "▪", style); @@ -654,6 +761,90 @@ fn plainWord(w: *std.Io.Writer, op: Op, line: []const u8) !?[]const u8 { return if (op == .search or op == .search_back) "Look" else "Exec"; } +/// The x of the blank after pane `pane`'s line numbers. +fn gutterX(pane: *const Pane, r: pardes.Rect) u16 { + return r.x + config.GUTTER + (File.gutterWidth(pane) -| File.laneCells(pane) -| pane.layers.heat -| 1); +} + +/// `┃` on the lines the selections a sam prompt began with cover, and +/// the ones `K` or `A-K` would drop dimmed and struck through. +fn fence(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, body_h: u16) void { + const f = &pane.file.?; + const tab = p.settings.tab; + const snap = pane.sel_snap[0..pane.nsel_snap]; + if (snap.len == 0) return; + const x = gutterX(pane, r); + const y = p.bodyTop(pane, r); + const ink = p.chromeTheme().box; + const nlines = File.nlines(p.gpa, f); + const op = p.view().tag_state.prompt.op; + var kept: [Text.max_selections]modal.Selection = undefined; + const now = if (op == .keep or op == .remove) pane.body.ranges(f.content, 0, &kept).n else 0; + var last: i32 = -1; + var vr: u16 = 0; + while (vr < body_h) : (vr += 1) { + const line = pane.wrapAt(tab, vr).line; + if (line == last or line < 0) continue; + if (line >= nlines) break; + last = line; + const ls = File.lineStart(p.gpa, f, @intCast(line)); + const le = File.lineStart(p.gpa, f, @intCast(line + 1)); + // The ranges are in the text's order: the first ending past the + // line's start, on while they start before its end. + var i = endingPast(snap, ls); + if (i < snap.len and @min(snap[i].anchor, snap[i].head) < @max(le, ls + 1)) { + var style = s.at(x, y + vr).style; + style.fg = .{ .rgb = ink }; + s.set(x, y + vr, "┃", style); + } + // K and A-K: the selections that would go, on this line. + if (op != .keep and op != .remove) continue; + while (i < snap.len and @min(snap[i].anchor, snap[i].head) < le) : (i += 1) { + const lo = @min(snap[i].anchor, snap[i].head); + const hi = @max(snap[i].anchor, snap[i].head); + const k = endingPast(kept[0..now], lo); + const stays = k < now and @min(kept[k].anchor, kept[k].head) == lo and @max(kept[k].anchor, kept[k].head) == hi; + if (!stays) strike(p, s, pane, r, line, @intCast(@max(lo, ls) - ls), @intCast(@min(hi, le) - ls)); + } + } +} + +/// The first of `ranges` (in the text's order) ending past byte `at`. +fn endingPast(ranges: []const modal.Selection, at: usize) usize { + return std.sort.partitionPoint(modal.Selection, ranges, at, struct { + fn before(byte: usize, r: modal.Selection) bool { + return @max(r.anchor, r.head) <= byte; + } + }.before); +} + +/// Bytes [lo, hi) of `line`, as many of its rows as show them, dimmed and +/// struck through (File.paintWordSelection's walk). +fn strike(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, line: i32, lo_: i32, hi_: i32) void { + const tab = p.settings.tab; + const tw = r.w - config.GUTTER; + const prefix: i32 = File.gutterWidth(pane); + const body_y = p.bodyTop(pane, r); + var vr: i32 = 0; + while (vr + @as(i32, pane.tag_rows) < @as(i32, r.h)) : (vr += 1) { + const here = pane.wrapAt(tab, vr); + if (here.line != line) continue; + var hi = hi_; + const next = pane.wrapAt(tab, vr + 1); + if (next.line == line) hi = @min(hi, next.at); + const lo = @max(lo_, here.at); + if (hi <= lo) continue; + const c0 = prefix + here.pad + File.displayOffset(tab, pane, line, here.at, lo); + const c1 = prefix + here.pad + File.displayEndOffset(tab, pane, line, here.at, hi - 1); + var col = @max(prefix, c0); + while (col <= c1 and col < tw) : (col += 1) { + const style = &s.at(r.x + config.GUTTER + @as(u16, @intCast(col)), body_y + @as(u16, @intCast(vr))).style; + style.dim = true; + style.strikethrough = true; + } + } +} + /// The head of the prompt's tag: ` s self▌ = Exec Edit x/self/ 4 /// selections in 6 lines ⏎ select · C-r history · esc`. pub fn head(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) !TagState.Head { @@ -702,11 +893,12 @@ fn count(arena: std.mem.Allocator, text: *std.ArrayList(u8), pane: *Pane, pr: *c const hits = set.hits.items; if (set.complete() and hits.len == 0) return text.appendSlice(arena, " 0"); try text.appendSlice(arena, " "); - if (set.current) |c| try text.print(arena, "{d}", .{c + 1}) else try text.appendSlice(arena, "–"); + const at = if (set.current) |c| (if (c < hits.len) c else null) else null; + if (at) |c| try text.print(arena, "{d}", .{c + 1}) else try text.appendSlice(arena, "–"); if (!set.complete()) return text.appendSlice(arena, "/⋯"); try text.print(arena, "/{d} · {d} line{s}", .{ hits.len, pr.lines, plural(pr.lines) }); // Round the end from where it began. - const c = set.current orelse return; + const c = at orelse return; const origin = set.origin(pane); if (if (pr.op == .search) hits[c].start < origin else hits[c].start > origin) try text.appendSlice(arena, " · wrapped"); }, @@ -940,3 +1132,52 @@ test "? searches back from the caret; no match is 0; a pattern that is no regex try std.testing.expectEqual(TagState.Kind.rest, p.view().tag_state.kind); try std.testing.expect(p.panes[p.view().active].?.query != null); } + +test "sam prompts one after another make one recipe word, the Edit line it is; a motion ends it and the next starts the pane's one again; ! adds nothing; the scope fenced in the gutter, what K drops struck; Look puts its selections back, Exec runs it as Edit" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 200, .rows = 30 }); + defer p.deinit(); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + while (p.nextEffect()) |_| {} + const pane = try p.setTestFile("self.a = 1;\nself.b = 2;\nother = 3;\n"); + typeKeys(p, "%sother"); + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expect(std.mem.startsWith(u8, try tagOf(p), "Edit x/other/ › /test.txt ")); + // Look on it: the selection it made, again. + typeKeys(p, "gg"); + Trail.lookStep(p, 0, 0); + const back = pane.body.primaryRange(pane.file.?.content, 0); + try std.testing.expectEqual(@as(usize, 24), @min(back.anchor, back.head)); + try std.testing.expectEqual(@as(usize, 29), @max(back.anchor, back.head)); + // A motion ends it: the next s is a recipe of its own, the pane's one. + typeKeys(p, "j%sself.."); + for ([_]u16{ 0, 1, 2 }) |row| try std.testing.expectEqualStrings("┃", try gutterAt(p, frame.allocator(), row)); + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expect(std.mem.startsWith(u8, try tagOf(p), "Edit x/self../ › /test.txt ")); + try std.testing.expectEqual(@as(u8, 1), pane.trail.n); + // K right after: `self.b` would go, struck through. + typeKeys(p, "Ka"); + p.sync(); + const s = try p.render(frame.allocator()); + const r = p.view().rects[0]; + const cell = s.at(r.x + config.GUTTER + File.gutterWidth(pane), p.bodyTop(pane, r) + 1); + try std.testing.expect(cell.style.strikethrough and cell.style.dim); + try std.testing.expect(!s.at(r.x + config.GUTTER + File.gutterWidth(pane), p.bodyTop(pane, r)).style.strikethrough); + p.update(.{ .key = .{ .cp = Key.enter } }); + typeKeys(p, "|"); + p.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expect(std.mem.startsWith(u8, try tagOf(p), "Edit x/self../ g/a/ |tr a-z A-Z › /test.txt ")); + // `!` applies and adds nothing: an Edit line cannot say it. + typeKeys(p, "!"); + p.update(.{ .key = .{ .cp = 'e', .text = "echo" } }); + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expect(std.mem.startsWith(u8, try tagOf(p), "Edit x/self../ g/a/ |tr a-z A-Z › /test.txt ")); + while (p.nextEffect()) |_| {} + if (p.pipe.wait) |*w| w.deinit(); + p.pipe.wait = null; + // Exec on it: Edit runs it, its command off the loop. + typeKeys(p, "%"); + Trail.execStep(p, 0, 0); + try std.testing.expect(p.pipe.edit_run != null); +} diff --git a/core/Trail.zig b/core/Trail.zig index 0ea893e2..cb5dedf8 100644 --- a/core/Trail.zig +++ b/core/Trail.zig @@ -338,8 +338,8 @@ pub fn stepAt(t: *const Trail, part: Part, off: usize) ?u8 { } /// Look on step `i` of pane `id`'s trail (§6.3): a place is gone back or -/// forward to, the owner focused, a search lit again (Prompt.zig); a list -/// or a recipe is the pickers' and the prompts' to take (not yet: said). +/// forward to, the owner focused, a search lit again, a recipe's +/// selections put back (Prompt.zig); a list is the pickers' (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]) { @@ -348,7 +348,8 @@ pub fn lookStep(p: *Pardes, id: usize, i: u8) void { p.view().active = owner; } else p.reportFailure(id, "walk: its owner is closed"), .search => pardes.Prompt.lookWord(p, id), - .list, .recipe => p.setMessage(.at(id), "walk: a list or a recipe is not walked yet"), + .recipe => pardes.Prompt.lookRecipe(p, id), + .list => p.setMessage(.at(id), "walk: a list is not walked yet"), } } @@ -359,7 +360,8 @@ pub fn execStep(p: *Pardes, id: usize, i: u8) void { switch (pane.trail.steps[i]) { .place, .owner => lookStep(p, id, i), .search => pardes.Prompt.execWord(p, id), - .list, .recipe => p.setMessage(.at(id), "walk: a list or a recipe is not run again yet"), + .recipe => pardes.Prompt.execRecipe(p, id), + .list => p.setMessage(.at(id), "walk: a list is not run again yet"), } } diff --git a/core/keys.zig b/core/keys.zig index 6ffca8e1..a0aa9692 100644 --- a/core/keys.zig +++ b/core/keys.zig @@ -214,6 +214,7 @@ pub fn handleKey(p: *Pardes, key: Key) void { } // A tag in a typing state takes every key (TagState: Help, describe-key). if (p.view().tag_state.kind != .rest) return tagStateKey(p, key); + Prompt.keyAtRest(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); diff --git a/core/panes.zig b/core/panes.zig index 0590a80d..e15ad180 100644 --- a/core/panes.zig +++ b/core/panes.zig @@ -273,6 +273,10 @@ pub const Pane = struct { /// 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 = .{}, + /// The selections its recipe word's sam prompts made (gpa), for Look + /// on the word to put back (Prompt.zig, SPEC §7.5). + recipe_sels: []modal.Selection = &.{}, + recipe_pri: u16 = 0, /// `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, @@ -1296,6 +1300,7 @@ pub fn teardownPane(p: *Pardes, pane: *Pane) void { pane.input.deinit(p.gpa); pane.jump.deinit(p.gpa); pane.places.deinit(p.gpa); + p.gpa.free(pane.recipe_sels); @import("jj.zig").forget(p, pane.serial); if (pane.query) |q| { q.deinit(p.gpa); diff --git a/test/daemon.py b/test/daemon.py index 4bc2658f..bb159424 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 = 37 + WIRE = 38 def __init__(self, path, timeout=10): self.path, self.timeout = path, timeout diff --git a/test/snapshots/pipe.golden b/test/snapshots/pipe.golden index 641418f9..04921c77 100644 --- a/test/snapshots/pipe.golden +++ b/test/snapshots/pipe.golden @@ -5,8 +5,8 @@ | 1 alpha beta | 2 gamma delta == snap filtered grid=180x13 cursor=17,3 -|2: */tmp/pardes-snap/pipe/cwd/pipe.txt Save Term Collapse Follow Del +|2: *Edit |tr a-z A-Z › /tmp/pardes-snap/pipe/cwd/pipe.txt Save Term Collapse Follow Del |3: 1 ALPHA BETA == snap undone grid=180x13 cursor=17,3 -|2: /tmp/pardes-snap/pipe/cwd/pipe.txt Save Term Collapse Follow Del +|2: Edit |tr a-z A-Z › /tmp/pardes-snap/pipe/cwd/pipe.txt Save Term Collapse Follow Del |3: 1 alpha beta diff --git a/test/snapshots/selregex.golden b/test/snapshots/selregex.golden index cc460f03..7a760e2b 100644 --- a/test/snapshots/selregex.golden +++ b/test/snapshots/selregex.golden @@ -2,9 +2,9 @@ | Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config History Debug Exit | New Term Find Grep Joincol Delcol |^ /tmp/pardes-snap/selregex/cwd/m.zig s ⏎ select · C-r history · esc -| 1 const one = 1; -| 2 const two = 2; -| 3 const three = 3; +| 1┃const one = 1; +| 2┃const two = 2; +| 3┃const three = 3; | ~ == snap preview grid=160x25 cursor=45,2 |2: ^ /tmp/pardes-snap/selregex/cwd/m.zig s const = Exec Edit x/const/ 3 selections in 3 lines ⏎ select · C-r history · esc @@ -12,9 +12,9 @@ |0: 0-1 d,#1d2824, 2-159 #b2c3b8,#1d2824, |1: 0-1 d,#887455, 2-159 #becfc4,#314738, |2: 0-1 #000000,#add38a, 2-31 #becfc4,#314738, 32-37 #dfbce5,#314738, 38-38 #add38a,#314738,b 39-39 #add38a,#314738, 40-44 #becfc4,#314738, 45-52 #becfc4,#314738,f 53-95 #becfc4,#314738, 96-123 #becfc4,#314738,f 124-159 #becfc4,#314738, -|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-10 #f5f7ee,#3c614a, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-159 #e5eee5,#0d1410, -|4: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f5f7ee,#243a2d, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-159 #e5eee5,#0d1410, -|5: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f5f7ee,#243a2d, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-20 #e5eee5,#0d1410, 21-21 #f8c082,#0d1410, 22-159 #e5eee5,#0d1410, +|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-5 #616f64,#0d1410,b 6-6 #add38a,#0d1410,b 7-10 #f5f7ee,#3c614a, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-159 #e5eee5,#0d1410, +|4: 0-0 d,#608269, 1-4 d,#0d1410, 5-5 #59675c,#0d1410, 6-6 #add38a,#0d1410, 7-10 #f5f7ee,#243a2d, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-159 #e5eee5,#0d1410, +|5: 0-0 d,#608269, 1-4 d,#0d1410, 5-5 #59675c,#0d1410, 6-6 #add38a,#0d1410, 7-10 #f5f7ee,#243a2d, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-20 #e5eee5,#0d1410, 21-21 #f8c082,#0d1410, 22-159 #e5eee5,#0d1410, |6: 0-0 d,#608269, 1-4 d,#0d1410, 5-159 #59675c,#0d1410, |7: 0-0 d,#608269, 1-159 d,#0d1410, |8: 0-0 d,#608269, 1-159 d,#0d1410, @@ -35,31 +35,42 @@ |23: 0-0 d,#608269, 1-159 d,#0d1410, |24: 0-0 d,#608269, 1-159 d,#0d1410, == snap three-selected grid=160x25 cursor=11,3 -|2: /tmp/pardes-snap/selregex/cwd/m.zig Save Term Collapse Follow TreeContext Def Refs Del +|2: Edit x/const/ › /tmp/pardes-snap/selregex/cwd/m.zig Save Term Collapse Follow TreeContext Def Refs Del +|3: 1 const one = 1; +|4: 2 const two = 2; +|5: 3 const three = 3; == style three-selected grid=160x25 -|2: 0-1 d,#add38a, 2-31 #becfc4,#314738, 32-37 #dfbce5,#314738, 38-159 #becfc4,#314738, +|2: 0-1 d,#add38a, 2-47 #becfc4,#314738, 48-53 #dfbce5,#314738, 54-159 #becfc4,#314738, |3: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-11 #f5f7ee,#3c614a, 12-12 #f5f7ee,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-159 #e5eee5,#0d1410, -== snap narrowed grid=160x25 cursor=41,2 -|2: ^ /tmp/pardes-snap/selregex/cwd/m.zig s t = Exec Edit x/t/ 3 selections in 3 lines ⏎ select · C-r history · esc +|4: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f5f7ee,#243a2d, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-159 #e5eee5,#0d1410, +|5: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f5f7ee,#243a2d, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-20 #e5eee5,#0d1410, 21-21 #f8c082,#0d1410, 22-159 #e5eee5,#0d1410, +== snap narrowed grid=160x25 cursor=57,2 +|2: ^ Edit x/const/ › /tmp/pardes-snap/selregex/cwd/m.zig s t = Exec Edit x/t/ 3 selections in 3 lines ⏎ select · C-r history · esc +|3: 1┃const one = 1; +|4: 2┃const two = 2; +|5: 3┃const three = 3; == style narrowed grid=160x25 -|2: 0-1 #000000,#add38a, 2-31 #becfc4,#314738, 32-37 #dfbce5,#314738, 38-38 #add38a,#314738,b 39-39 #add38a,#314738, 40-40 #becfc4,#314738, 41-48 #becfc4,#314738,f 49-87 #becfc4,#314738, 88-115 #becfc4,#314738,f 116-159 #becfc4,#314738, -|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-10 #e5eee5,#0d1410, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-159 #e5eee5,#0d1410, -|4: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-159 #e5eee5,#0d1410, -|5: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-20 #e5eee5,#0d1410, 21-21 #f8c082,#0d1410, 22-159 #e5eee5,#0d1410, +|2: 0-1 #000000,#add38a, 2-47 #becfc4,#314738, 48-53 #dfbce5,#314738, 54-54 #add38a,#314738,b 55-55 #add38a,#314738, 56-56 #becfc4,#314738, 57-64 #becfc4,#314738,f 65-103 #becfc4,#314738, 104-131 #becfc4,#314738,f 132-159 #becfc4,#314738, +|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-5 #616f64,#0d1410,b 6-6 #add38a,#0d1410,b 7-10 #e5eee5,#0d1410, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-159 #e5eee5,#0d1410, +|4: 0-0 d,#608269, 1-4 d,#0d1410, 5-5 #59675c,#0d1410, 6-6 #add38a,#0d1410, 7-10 #e5eee5,#0d1410, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-159 #e5eee5,#0d1410, +|5: 0-0 d,#608269, 1-4 d,#0d1410, 5-5 #59675c,#0d1410, 6-6 #add38a,#0d1410, 7-10 #e5eee5,#0d1410, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-20 #e5eee5,#0d1410, 21-21 #f8c082,#0d1410, 22-159 #e5eee5,#0d1410, == snap esc-restores grid=160x25 cursor=11,3 -|2: /tmp/pardes-snap/selregex/cwd/m.zig Save Term Collapse Follow TreeContext Def Refs Del +|2: Edit x/const/ › /tmp/pardes-snap/selregex/cwd/m.zig Save Term Collapse Follow TreeContext Def Refs Del +|3: 1 const one = 1; +|4: 2 const two = 2; +|5: 3 const three = 3; == style esc-restores grid=160x25 -|2: 0-1 d,#add38a, 2-31 #becfc4,#314738, 32-37 #dfbce5,#314738, 38-159 #becfc4,#314738, +|2: 0-1 d,#add38a, 2-47 #becfc4,#314738, 48-53 #dfbce5,#314738, 54-159 #becfc4,#314738, |3: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-11 #f5f7ee,#3c614a, 12-12 #f5f7ee,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-159 #e5eee5,#0d1410, |4: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f5f7ee,#243a2d, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-159 #e5eee5,#0d1410, |5: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f5f7ee,#243a2d, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-20 #e5eee5,#0d1410, 21-21 #f8c082,#0d1410, 22-159 #e5eee5,#0d1410, == snap commented grid=160x25 cursor=14,3 -|2: */tmp/pardes-snap/selregex/cwd/m.zig Save Term Collapse Follow TreeContext Def Refs Del +|2: *Edit x/const/ › /tmp/pardes-snap/selregex/cwd/m.zig Save Term Collapse Follow TreeContext Def Refs Del |3: 1 // const one = 1; |4: 2 // const two = 2; |5: 3 // const three = 3; == snap uncommented grid=160x25 cursor=11,3 -|2: /tmp/pardes-snap/selregex/cwd/m.zig Save Term Collapse Follow TreeContext Def Refs Del +|2: Edit x/const/ › /tmp/pardes-snap/selregex/cwd/m.zig Save Term Collapse Follow TreeContext Def Refs Del |3: 1 const one = 1; |4: 2 const two = 2; |5: 3 const three = 3; -- cgit v1.3 From b44a129a8854483dbe45ce2bcfa09f33ccbd6e8c Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 24 Nov 2026 22:16:38 -0300 Subject: registers: `"` shows the registers rolled in the tag, each its key and the first line of its value (`" ▸ " self.dirty = true; a const best = rank(q, nam… / — … % core/x.zig . o # 1 _ —`), `↓` unrolls them a row each (key, what it is, first line) beside the cursor's value in full, and choosing one (its key, or Enter) goes down to its verbs rolled (`" a ▸ p after P before R replace y into`), Backspace back up, Esc to rest (pick-ui SPEC §9, walk UI line F item 1): the level is built from the registers (and the four computed from the pane with the keyboard) when it is read, as the addon words join SPC's (bindings.registerLevel, registerValue: the first value only, a first line cut at 24 columns and never scanned past 96 bytes, the value step reading only the lines the band shows); a register named (`t.normal.register`, the parser's) is the root `"` with that key as its path (TagState.current), its verbs a node of normal mode's paste, yank and replace roles (bindings.register_verbs, a group slot of its own: TagState.used one longer, the dump with it); keys.prefixKey reads the level at the current path, Esc there goes to rest (normal mode's Esc would have named the register ESC, then left the pane), Backspace from the verbs goes back to `"`; TEST: bindings.zig "\" shows the registers rolled ..." (the level, the band's rows and value, Enter, Backspace, `a p` pasting, Esc); core-test 1024/1191 (167 skipped), 0 failed, load 5 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- core/Band.zig | 66 ++++++++++++++++++++- core/TagState.zig | 11 +++- core/bindings.zig | 172 +++++++++++++++++++++++++++++++++++++++++++++++++++++- core/keys.zig | 28 +++++++-- 4 files changed, 266 insertions(+), 11 deletions(-) diff --git a/core/Band.zig b/core/Band.zig index 3c800bf0..13c4b9c0 100644 --- a/core/Band.zig +++ b/core/Band.zig @@ -105,6 +105,8 @@ pub fn takes(p: *Pardes, id: usize) u16 { 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); + // The registers, one column of eleven at most (registerSteps). + if (cur.root == .register and cur.path.len == 0) return @max(doc_rows, @min(Cursor.shown, n)); return @max(doc_rows, levelRows(n)); } @@ -151,6 +153,11 @@ pub fn of(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, id: usize) !?Band { }, } const cur = TagState.current(p, v).?; + if (cur.root == .register) { + try band.registerSteps(p, arena, pane, cur.path); + try band.place(p, arena, pane, id); + return band; + } // 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); @@ -196,6 +203,63 @@ fn helpSteps(band: *Band, p: *Pardes, arena: std.mem.Allocator, s: *const TagSta band.add(try docStep(p, arena, at.root, at.path[0 .. at.path.len - 1], at.child)); } +/// `"` unrolled (SPEC §9): the registers, a row each (its key, what it +/// is, its first line) around the cursor, or under `"a` its verbs; beside +/// them the value of the one on the cursor (or named) in full, as many of +/// its lines as the band has rows, only those read. +fn registerSteps(band: *Band, p: *Pardes, arena: std.mem.Allocator, pane: *const Pane, path: []const u8) !void { + const s = &p.view().tag_state; + var children: [bindings.max_children]bindings.Child = undefined; + const level = bindings.level(p, .register, path, &children); + const node = bindings.nodeAt(.register, path); + const used = if (node) |n| s.used[n.group] else 0; + var at: usize = 0; + for (level, 0..) |c, i| if (c.key == (if (s.hi != 0) s.hi else used)) { + at = i; + }; + if (path.len > 0) band.add(try levelStep(arena, pane, level, at, used)) else { + const w = (Cursor{ .at = @intCast(at) }).window(@intCast(level.len)); + const rows = try arena.alloc(Row, w.hi - w.lo); + for (rows, w.lo..) |*row, i| { + const c = level[i]; + const name = for (bindings.register_names) |r| { + if (r.key == c.key) break r.name; + } else "named"; + row.* = .{ + .text = try std.fmt.allocPrint(arena, "{s} {s: <17} {s}{s}", .{ bindings.keyName(c.key), name, c.label, if (c.more) "…" else "" }), + .on = i == at, + .key = 1, + .under = c.key == used, + .index = @intCast(i), + }; + } + band.add(.{ .rows = rows }); + } + const key = if (path.len > 0) path[0] else level[at].key; + const name = for (bindings.register_names) |r| { + if (r.key == key) break r.name; + } else "named"; + var rows: std.ArrayList(Row) = .empty; + try rows.append(arena, .{ .text = try std.fmt.allocPrint(arena, "\"{s} · {s}", .{ bindings.keyName(key), name }), .key = 2 }); + const value = bindings.registerValue(p, key); + if (value.len == 0) try rows.append(arena, .{ .text = "(empty)", .dim = true }); + // A line is cut at what the band could show of it: a long one is + // never scanned past that. + const most = @as(usize, band.columns) * band.height; + var rest = value; + while (rest.len > 0 and rows.items.len + 1 < band.height) { + const look = rest[0..@min(rest.len, most)]; + const end = std.mem.indexOfScalar(u8, look, '\n') orelse { + try rows.append(arena, .{ .text = rest[0..if (look.len < rest.len) modal.graphemeStart(rest, look.len) else look.len] }); + break; + }; + try rows.append(arena, .{ .text = look[0..end] }); + rest = rest[end + 1 ..]; + } + if (path.len == 0) try rows.append(arena, .{ .text = "next p after P before R replace y into", .dim = true }); + band.add(.{ .rows = rows.items, .doc = true }); +} + /// 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. @@ -245,7 +309,7 @@ pub fn levelStep(arena: std.mem.Allocator, pane: *const Pane, level: []const bin 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 "" }), + .text = try std.fmt.allocPrint(arena, "{s} {s}{s}", .{ key, c.label, if (c.group or c.more) "…" else "" }), .on = i == at, .key = @intCast(key.len), .dim = bindings.dimmed(pane, c), diff --git a/core/TagState.zig b/core/TagState.zig index 5a30f182..95df8937 100644 --- a/core/TagState.zig +++ b/core/TagState.zig @@ -152,7 +152,11 @@ pub fn current(p: *const Pardes, v: *const View) ?Current { 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 prefix = t.normal.prefix orelse { + // `"a`: the register named, its verbs next (SPEC §9). + const r = t.normal.register; + return if (r > ' ' and r <= '~') .{ .root = .register, .path = bindings.keyName(@intCast(r)) } else null; + }; const root: Root = switch (prefix) { .goto_prefix => .goto, .view_prefix => if (t.normal.sticky) .view_sticky else .view, @@ -188,7 +192,8 @@ pub fn hostOf(p: *const Pardes) ?usize { 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; + return pane.body.normal.prefix != null or pane.tag.normal.prefix != null or + pane.body.normal.register != 0 or pane.tag.normal.register != 0; } /// After a key (keys.handleKey): a root newly current starts its delay; one @@ -515,7 +520,7 @@ pub fn head(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) !?Head { try b.styled(bindings.keyName(c.key), .key); try b.put(" "); try b.put(c.label); - if (c.group) try b.put("…"); + if (c.group or c.more) 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 }); diff --git a/core/bindings.zig b/core/bindings.zig index b2d84a7c..f7be1a43 100644 --- a/core/bindings.zig +++ b/core/bindings.zig @@ -15,6 +15,8 @@ const Pardes = pardes.Pardes; const Pane = pardes.Pane; const Key = pardes.Key; const Role = modal.Normal.Role; +const edit = @import("edit.zig"); +const File = @import("File.zig"); /// The keys a sequence starts with. `register` (`"`) is drawn the same way /// but its rows are the registers' contents, not a tree. @@ -87,8 +89,9 @@ pub const groups = groups: { }; break :groups paths; }; -/// SPC's groups, then one for each other root. -pub const ngroups = groups.len + std.enums.values(Root).len - 1; +/// SPC's groups, then one for each other root, then the verbs a register +/// takes (`"a ▸`). +pub const ngroups = groups.len + std.enums.values(Root).len; fn rootGroup(comptime r: Root) u8 { return @intCast(groups.len + @intFromEnum(r) - 1); @@ -233,6 +236,15 @@ const view_sticky_tree: Node = .{ .key = config.view_prefix_sticky, .label = "vi 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) }; +/// What the register `"` named does next (SPEC §9: `"a ▸ p after P before +/// y into R replace`): normal mode's paste, yank and replace, which read +/// the register the parser holds. +const register_verbs: Node = .{ .key = 0, .label = "register", .group = ngroups - 1, .children = sorted(&.{ + .{ .key = roleKey(.paste_after).?, .label = "after", .leaf = .{ .role = .paste_after } }, + .{ .key = roleKey(.paste_before).?, .label = "before", .leaf = .{ .role = .paste_before } }, + .{ .key = roleKey(.yank).?, .label = "into", .leaf = .{ .role = .yank } }, + .{ .key = roleKey(.replace_with_yank).?, .label = "replace", .leaf = .{ .role = .replace_with_yank } }, +}) }; /// 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: { @@ -248,7 +260,13 @@ const window_tree: Node = .{ .key = 'w', .label = "window", .group = rootGroup(. /// 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| { + var keys = path; + // A register's name is any key: under each, its verbs. + if (root == .register and path.len > 0) { + n = ®ister_verbs; + keys = path[1..]; + } + for (keys) |k| n = for (n.children) |*c| { if (c.key == k) break c; } else return null; return n; @@ -263,6 +281,8 @@ pub const Child = struct { word: ?*const pardes.Kind.Word = null, group: bool = false, lsp: bool = false, + /// Its label is cut (a register's first line): `…` after it. + more: 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. @@ -273,6 +293,7 @@ pub const max_children = 96; /// 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 { + if (root == .register and path.len == 0) return registerLevel(p, out); 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; @@ -300,6 +321,87 @@ pub fn level(p: *const Pardes, root: Root, path: []const u8, out: *[max_children return shown; } +/// The registers `"` shows (SPEC §9), in its order, and what each is: the +/// default first, the ones a name was given (`"ay`) after it, by name, +/// then these, the last four computed from the pane with the keyboard. +pub const register_names = [_]struct { key: u8, name: []const u8 }{ + .{ .key = '"', .name = "yank" }, + .{ .key = '/', .name = "last search" }, + .{ .key = ':', .name = "last command" }, + .{ .key = '|', .name = "last pipe" }, + .{ .key = '+', .name = "system clipboard" }, + .{ .key = '@', .name = "last macro" }, + .{ .key = '%', .name = "this file's name" }, + .{ .key = '.', .name = "the selections" }, + .{ .key = '#', .name = "selection numbers" }, + .{ .key = '_', .name = "black hole" }, +}; + +/// The display columns of a register's first line which-key shows; the +/// rest is `…`. +pub const register_cut = 24; + +/// `"`'s level: a child a register, its label the first line of its value +/// (`—` when empty), cut. Read when the level is (a key, a frame), never +/// kept: the first `register_cut` columns of each, the named ones bounded +/// by the level's room. +fn registerLevel(p: *const Pardes, out: *[max_children]Child) []Child { + var n: usize = 1; + for (p.registers.list.items) |*reg| { + if (reg.name <= ' ' or reg.name > '~' or n == out.len - (register_names.len - 1)) continue; + const k: u8 = @intCast(reg.name); + for (register_names) |r| { + if (r.key == k) break; + } else { + var j = n; + while (j > 1 and out[j - 1].key > k) : (j -= 1) out[j] = out[j - 1]; + out[j] = .{ .key = k, .label = "" }; + n += 1; + } + } + out[0] = .{ .key = '"', .label = "" }; + for (register_names[1..]) |r| { + out[n] = .{ .key = r.key, .label = "" }; + n += 1; + } + for (out[0..n]) |*c| { + const value = registerValue(p, c.key); + const bound = if (value.len > 4 * register_cut) modal.graphemeStart(value, 4 * register_cut) else value.len; + const line = value[0 .. std.mem.indexOfScalar(u8, value[0..bound], '\n') orelse bound]; + const cut = File.byteAtDisplay(p.settings.tab, line, register_cut); + c.label = if (value.len == 0) "—" else line[0..cut]; + c.more = cut < value.len; + } + return out[0..n]; +} + +/// Register `key`'s value as a paste of the pane with the keyboard reads +/// its first range's (edit.registerValue): a stored one's first value; `%` +/// the file's name, `.` the primary selection's text, `#` its number, `_` +/// nothing. Borrowed from the register or the pane, for the frame. +pub fn registerValue(p: *const Pardes, key: u8) []const u8 { + const pane = p.panes[p.view().active] orelse return ""; + switch (key) { + '_' => return "", + '#' => return "1", + '%' => return if (pane.file) |*f| f.path else "", + '.' => { + const f = if (pane.file) |*f| f else return ""; + const t = &pane.body; + const b = edit.cellBounds(.{ .row = t.cur_row, .col = t.cur_col, .arow = if (t.vsel.active) t.vsel.row else t.cur_row, .acol = if (t.vsel.active) t.vsel.col else t.cur_col }); + const first = File.sourceLine(pane, b.lo_row); + const last = File.sourceLine(pane, b.hi_row); + if (f.content.len == 0) return ""; + const lo = @min(f.content.len, first.ptr - f.content.ptr + @as(usize, @intCast(@max(0, b.lo_col)))); + const hi = @min(f.content.len, last.ptr - f.content.ptr + @as(usize, @intCast(@max(0, b.hi_col)))); + return f.content[lo..modal.nextGrapheme(f.content, @max(lo, hi))]; + }, + else => for (p.registers.list.items) |*reg| { + if (reg.name == key) return if (reg.values.len == 0) "" else reg.values[0]; + } else return "", + } +} + /// 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]); @@ -450,3 +552,67 @@ test "Help's rows: every leaf of every root, spelled as its chord, its word and try std.testing.expectEqual(@as(usize, 4), found); for (flat) |f| try std.testing.expectEqual(f.row.len, f.lower.len); } + +test "\" shows the registers rolled, each its first line; Down unrolls them beside the cursor's value; a register's key goes down to its verbs, Backspace back up, p pastes it" { + const tagline = @import("tagline.zig"); + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 40 }); + defer p.deinit(); + const pane = try p.setTestFile("one\ntwo\n"); + try p.registers.put(p.gpa, 'a', "const best = rank(q, name) orelse continue;\nreturn best;", 0, 1, true); + try p.registers.put(p.gpa, '"', "self.dirty = true;", 0, 1, true); + 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(); + // Its key cell at once, the level 300 ms on. + p.update(.{ .key = .{ .cp = '"' } }); + try std.testing.expect(std.mem.endsWith(u8, try tagline.tagText(p, a, pane), " \" …")); + p.advance(p.clock.now_ns); + try std.testing.expectEqual(p.clock.now_ns + 300 * std.time.ns_per_ms, p.view().tag_state.due_ns); + p.clock.now_ns = p.view().tag_state.due_ns; + const rolled = try tagline.tagText(p, a, pane); + try std.testing.expect(std.mem.indexOf(u8, rolled, " \" ▸ \" self.dirty = true; a const best = rank(q, nam… / —") != null); + try std.testing.expect(std.mem.indexOf(u8, rolled, "% /test.txt . o # 1 _ —") != null); + // Down unrolls: a row each, the cursor on the default, its value + // beside them. + p.update(.{ .key = .{ .cp = Key.down } }); + try std.testing.expect(p.view().tag_state.unrolled); + try std.testing.expect(pane.band_rows >= 4); + _ = try p.render(a); + const layer = &p.surface.tag_layers[pardes.BAND_LAYER_BASE + p.view().active]; + var band: std.ArrayList(u8) = .empty; + for (0..layer.rows) |row| for (layer.cells[row * layer.cols ..][0..layer.cols]) |cell| try band.appendSlice(a, cell.grapheme()); + try std.testing.expect(std.mem.indexOf(u8, band.items, "▶ \" yank self.dirty = true;") != null); + try std.testing.expect(std.mem.indexOf(u8, band.items, "\"\" · yank") != null); + // The next row's value in full, every line of it. + p.update(.{ .key = .{ .cp = Key.down } }); + _ = frame.reset(.retain_capacity); + _ = try p.render(a); + band = .empty; + for (0..layer.rows) |row| for (layer.cells[row * layer.cols ..][0..layer.cols]) |cell| try band.appendSlice(a, cell.grapheme()); + try std.testing.expect(std.mem.indexOf(u8, band.items, "const best = rank(q, name) orelse continue;") != null); + try std.testing.expect(std.mem.indexOf(u8, band.items, "return best;") != null); + // Enter chooses it: its verbs, rolled. + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expect(std.mem.indexOf(u8, try tagline.tagText(p, a, pane), " \" a ▸ p after P before R replace y into") != null); + try std.testing.expect(!p.view().tag_state.unrolled); + // Backspace: the registers again; a register's own key goes down too. + p.update(.{ .key = .{ .cp = Key.backspace } }); + try std.testing.expect(std.mem.indexOf(u8, try tagline.tagText(p, a, pane), " \" ▸ \" self.dirty") != null); + p.update(.{ .key = .{ .cp = 'a' } }); + try std.testing.expect(std.mem.indexOf(u8, try tagline.tagText(p, a, pane), " \" a ▸ p after") != null); + // p pastes it after the selection, and the tag is at rest. + p.update(.{ .key = .{ .cp = 'p' } }); + try std.testing.expect(std.mem.indexOf(u8, pane.file.?.content, "const best = rank(q, name) orelse continue;") != null); + try std.testing.expect(p.view().tag_state.root == null); + try std.testing.expect(@import("TagState.zig").hostOf(p) == null); + // Esc from the registers: rest, the keyboard where it was. + const id = p.view().active; + p.update(.{ .key = .{ .cp = '"' } }); + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expect(p.view().tag_state.root == null); + try std.testing.expectEqual(id, p.view().active); + try std.testing.expectEqual(@as(u21, 0), pane.body.normal.register); +} diff --git a/core/keys.zig b/core/keys.zig index 04a3cc35..78f45820 100644 --- a/core/keys.zig +++ b/core/keys.zig @@ -376,7 +376,7 @@ pub fn handleKey(p: *Pardes, key: Key) void { 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 (prefixKey(p, t, cur, 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 @@ -679,15 +679,27 @@ fn levelKey(p: *Pardes, root: bindings.Root, path: []const u8, key: Key) LevelSt /// 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 { +fn prefixKey(p: *Pardes, t: *Text, cur: TagState.Current, key: Key) bool { + const root = cur.root; 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)) { + // `"` and a register's verbs: Esc goes to rest (normal mode's would + // name the register, or leave the pane). + if (root == .register and hit(key, config.escape)) { + t.normal.clear(); + return true; + } + switch (levelKey(p, root, cur.path, key)) { .taken => return true, .up => { t.normal = .{}; + // A register's verbs go back up to the registers (SPEC §9). + if (root == .register and cur.path.len > 0) { + t.normal.prefix = .register_prefix; + p.view().tag_state.hi = 0; + } return true; }, .take => |c| { @@ -697,7 +709,15 @@ fn prefixKey(p: *Pardes, t: *Text, root: bindings.Root, key: Key) bool { .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); + var buf: [2]u8 = .{ 0, k }; + if (cur.path.len > 0) buf[0] = cur.path[0]; + const here = if (cur.path.len > 0) buf[0..2] else buf[1..2]; + if (bindings.nodeAt(root, here) != null) TagState.ran(p.view(), root, cur.path, k); + // A register named: its verbs, rolled, the cursor afresh. + if (root == .register) { + p.view().tag_state.hi = 0; + p.view().tag_state.unrolled = false; + } } return false; }, -- cgit v1.3 From 89b3e7365bac28c4cd7d52d40c1786c01db5af52 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 24 Nov 2026 22:24:29 -0300 Subject: body_layer: a motion root's level paints its targets in the gutter while it shows: `g` its first and last lines, the window's top and bottom and the last edit (`g e t b .`); `]` the next and `[` the previous function, paragraph, test, comment, change, diagnostic, type and argument (`f p T c g d t a`); browsing `m` unrolled on `a` or `i` tints the brackets' region around the caret (pick-ui SPEC §4.4, walk UI line F item 2): the keys are the level's own (bindings.level, each leaf's role), each target looked for in the rows shown alone and a target off them not painted (the tag's arrows of §15 not built): the tree objects through syntax.objectNext given the shown bytes (QueryCursor.setByteRange; the motion passes null), `]g` through jj.nextChange bounded to the shown lines (`most`; the motion unbounded), `]d` a binary search of the fed diagnostics, `]p` the shown lines, `g t`/`g b` normal.gotoWindow's rows; drawn into the body as the `gw` labels are (R3), never written; at rest one test of the view's tag state (TagState.hostOf); the tree is the one the motion reads (normal.fileTree, made once a revision), not painted while the Changes layer's lines are in the buffer; TEST: body_layer.zig "a motion root's level paints its targets in the gutter ..." (`]` p, `g` g e, `m` on i tinted, rest as before); core-test 1025/1192 (167 skipped), 0 failed, load 9 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- core/body_layer.zig | 263 ++++++++++++++++++++++++++++++++++++++++++++++++++++ core/jj.zig | 8 +- core/normal.zig | 4 +- core/syntax.zig | 5 +- 4 files changed, 274 insertions(+), 6 deletions(-) diff --git a/core/body_layer.zig b/core/body_layer.zig index 9c4a4c73..13fc7a85 100644 --- a/core/body_layer.zig +++ b/core/body_layer.zig @@ -25,6 +25,9 @@ const tagline = @import("tagline.zig"); const Text = panes.Text; const Layer = @import("Layer.zig"); +const TagState = @import("TagState.zig"); +const bindings = @import("bindings.zig"); +const File = panes.File; // ---- drawing a pane body into the surface ---- @@ -468,6 +471,8 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane } } + if (pane.file != null) paintTargets(p, s, arena, pane, r, tx, tw, body_y, body_h); + // `gw`'s labels, two letters over the start of each word if (pane.jump.items.len > 0) labels: { const flat = edit.flatSurface(p.editor(), &pane.body) catch break :labels; @@ -548,6 +553,207 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane }; } +/// Painted targets (SPEC §4.4), while a motion root's level shows in this +/// body's tag: each of its keys at the line it would go to, in the gutter +/// (`g e t b .` for `g`; for `]` the next and for `[` the previous +/// function, paragraph, test, comment, change, diagnostic, type, argument: +/// `f p T c g d t a`); browsing `m a` or `m i` unrolled, the brackets' +/// region around the caret tinted. Only the rows shown are looked at: a +/// target off them is not painted (the tag's arrows, SPEC §15, are not +/// built). At rest it costs one test of the view's tag state. +fn paintTargets(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, r: Rect, tx: u16, tw: u16, body_y: u16, body_h: u16) void { + const host = TagState.hostOf(p) orelse return; + if (p.panes[host] != pane) return; + const v = p.view(); + const cur = TagState.current(p, v) orelse return; + if (!TagState.shown(p, v)) return; + const f = &pane.file.?; + if (f.line_starts.len == 0) return; + const tab = p.settings.tab; + const held = pane.context_rows; + if (body_h <= held) return; + // The lines the rows show, past the context rows held at the top. + const lo: usize = @intCast(@max(0, pane.wrapAt(tab, held).line)); + var hi = lo; + for (held..body_h) |row| { + const line = pane.wrapAt(tab, @intCast(row)).line; + if (line >= 0 and line < f.line_starts.len) hi = @max(hi, @as(usize, @intCast(line))); + } + var children: [bindings.max_children]bindings.Child = undefined; + const level = bindings.level(p, cur.root, cur.path, &children); + if (cur.root == .match) { + const st = &v.tag_state; + if (!st.unrolled) return; + const on = for (level) |c| { + if (c.key == st.hi) break c; + } else return; + const leaf = (on.node orelse return).leaf orelse return; + if (leaf != .role or (leaf.role != .match_inside and leaf.role != .match_around)) return; + const role = leaf.role; + const caret = lineStart(f, @intCast(@max(0, pane.body.cur_row))) + @as(usize, @intCast(@max(0, pane.body.cur_col))); + const span = enclosing(f.content, @min(caret, f.content.len), lineStart(f, lo), lineStart(f, hi + 1)) orelse return; + const from = if (role == .match_inside) span[0] + 1 else span[0]; + const to = if (role == .match_inside) span[1] else span[1] + 1; + const first = lineOf(f, from); + const last = lineOf(f, to -| 1); + const rows = arena.alloc(Pane.PointerRow, last - first + 1) catch return; + for (rows, first..) |*row, line| row.* = .{ + .row = @intCast(line), + .lo = if (line == first) from - lineStart(f, line) else 0, + .hi = if (line == last) to - lineStart(f, line) else File.sourceLine(pane, @intCast(line)).len, + .to_edge = line != last, + }; + const th = p.theme(); + const page = th.bg orelse th.tag_bg; + paintSourceSelection(p, s, pane, r, rows, colors.mix(page, colors.mix(page, th.sel_bg)), null); + return; + } + if (cur.root != .goto and cur.root != .next and cur.root != .prev) return; + const th = p.theme(); + const style: CellStyle = .{ .fg = .{ .rgb = p.chromeTheme().box }, .bg = if (th.bg) |c| .{ .rgb = c } else .default, .bold = true }; + // The rows painted so far: a second key on a row goes after the first. + var painted: [bindings.max_children]u16 = undefined; + var n: usize = 0; + for (level) |c| { + const leaf = (c.node orelse continue).leaf orelse continue; + if (leaf != .role) continue; + const line = targetLine(p, pane, f, leaf.role, cur.root != .prev, lo, hi) orelse continue; + if (line < lo or line > hi) continue; + var row: u16 = held; + while (row < body_h) : (row += 1) { + const w = pane.wrapAt(tab, row); + if (w.line == line and w.at == 0) break; + } else continue; + const x: u16 = @intCast(std.mem.count(u16, painted[0..n], &.{row})); + if (x >= tw) continue; + s.set(tx + x, body_y + row, bindings.keyName(c.key), style); + painted[n] = row; + n += 1; + } +} + +/// The line a motion role would go to from the caret of `pane`, looked for +/// in lines `lo` to `hi` (the rows shown) alone; null for none there, or a +/// role that is no line's. +fn targetLine(p: *Pardes, pane: *Pane, f: *panes.File.State, role: modal.Normal.Role, forward: bool, lo: usize, hi: usize) ?usize { + const tab = p.settings.tab; + const caret: usize = @intCast(@max(0, pane.body.cur_row)); + const nlines = f.line_starts.len; + switch (role) { + .goto_file_start => return 0, + .goto_last_line => return if (nlines > 1 and f.line_starts[nlines - 1] == f.content.len) nlines - 2 else nlines - 1, + .goto_last_modification => return if (pane.body.last_edit) |at| @intCast(@max(0, at.row)) else null, + // helix's goto_window, as normal.gotoWindow counts its rows. + .goto_view_top, .goto_view_bottom => { + const shown: i32 = File.shownRows(tab, pane); + const held: i32 = pane.context_rows; + var last: i32 = shown - 1; + while (last > 0 and pane.wrapAt(tab, held + last).line >= @as(i32, @intCast(nlines))) last -= 1; + const margin: i32 = @min(config.scroll_off, @divTrunc(shown - 1, 2)); + const vr = std.math.clamp(@min(@max(if (role == .goto_view_top) margin else last - margin, margin), last - margin), 0, last); + const line = pane.wrapAt(tab, held + vr).line; + return if (line < 0) null else @intCast(line); + }, + // helix's paragraph: past the lines with text, then past the blank + // ones (modal.moveParagraph). + .goto_paragraph => { + var l = caret; + if (forward) { + while (l <= hi and !blank(pane, l)) l += 1; + while (l <= hi and blank(pane, l)) l += 1; + return if (l <= hi and l != caret) l else null; + } + while (l > lo and blank(pane, l - 1)) l -= 1; + while (l > lo and !blank(pane, l - 1)) l -= 1; + return if (l == caret or (l == lo and lo > 0)) null else l; + }, + .goto_change => return @import("jj.zig").nextChange(p, pane, caret, forward, hi - lo + 1), + // Once a Diagnostics list fed them, the pane's places (normal.zig's + // `]d`): the first after the caret's line, or the last before it. + .goto_diagnostic => { + const set = &pane.places; + const fed = set.started and set.provenance == .list and if (p.paneBySerial(set.from)) |qid| + (if (p.panes[qid].?.query) |q| q.source == .diagnostics else false) + else + false; + if (!fed) return null; + const hits = set.hits.items; + const edge = if (forward) lineStart(f, caret + 1) else lineStart(f, caret); + var a: usize = 0; + var b: usize = hits.len; + while (a < b) { + const m = (a + b) / 2; + if (hits[m].start < edge) a = m + 1 else b = m; + } + if (forward) return if (a < hits.len) lineOf(f, hits[a].start) else null; + return if (a > 0) lineOf(f, hits[a - 1].start) else null; + }, + inline .goto_function, .goto_class, .goto_parameter, .goto_comment, .goto_test, .goto_entry, .goto_xml_element => |r| { + // The tree as the motion reads it, made once a revision; with + // the Changes layer's lines in the buffer its offsets are not the + // buffer's: not painted then. + if (f.layer.lines.len > 0) return null; + const tree = normal.fileTree(p, f) orelse return null; + const object = @field(modal.Normal.Object, @tagName(r)["goto_".len..]); + const at = lineStart(f, caret) + @as(usize, @intCast(@max(0, pane.body.cur_col))); + const span = @import("syntax.zig").objectNext(f.path, tree, f.content, object, forward, @min(at, f.content.len), .{ lineStart(f, lo), lineStart(f, hi + 1) }) orelse return null; + return lineOf(f, span.from); + }, + else => return null, + } +} + +fn blank(pane: *const Pane, line: usize) bool { + return std.mem.trim(u8, File.sourceLine(pane, @intCast(line)), " \t\r").len == 0; +} + +/// Where line `line` starts in a file's buffer; past its last, its end. +fn lineStart(f: *const panes.File.State, line: usize) usize { + return if (line < f.line_starts.len) f.line_starts[line] else f.content.len; +} + +/// The line holding byte `off` of a file's buffer. +fn lineOf(f: *const panes.File.State, off: usize) usize { + var a: usize = 0; + var b = f.line_starts.len; + while (a + 1 < b) { + const m = (a + b) / 2; + if (f.line_starts[m] <= off) a = m else b = m; + } + return a; +} + +/// The innermost bracket pair around byte `at` of `text`, both in bytes +/// `lo` to `hi` (the rows shown): its opening and its closing byte. +fn enclosing(text: []const u8, at: usize, lo: usize, hi: usize) ?[2]usize { + var depth: usize = 0; + var i = at; + const open = while (i > lo) { + i -= 1; + switch (text[i]) { + ')', ']', '}' => depth += 1, + '(', '[', '{' => if (depth == 0) break i else { + depth -= 1; + }, + else => {}, + } + } else return null; + const close: u8 = switch (text[open]) { + '(' => ')', + '[' => ']', + else => '}', + }; + depth = 0; + i = at; + while (i < @min(hi, text.len)) : (i += 1) { + if (text[i] == text[open]) depth += 1 else if (text[i] == close) { + if (depth == 0) return .{ open, i }; + depth -= 1; + } + } + return null; +} + pub fn bodyText(tab: u16, arena: std.mem.Allocator, pane: *Pane) ![]const u8 { if (pane.addon != null) { const buf = try arena.alloc(u8, pane.rows -| 1); @@ -656,3 +862,60 @@ fn fillBody(dst: ?[]u8, pane: *Pane, viewport: []const []const u8) usize { } return written; } + +test "a motion root's level paints its targets in the gutter: `]` the next paragraph's p, `g` g and e; `m` browsed on `i` tints the braces' inside; nothing at rest" { + const Key = pardes.Key; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 20 }); + defer p.deinit(); + const pane = try p.setTestFile("fn a() {\n one;\n}\n\nfn b() {\n two;\n}\n"); + const id = p.view().active; + 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; + pane.focus = .body; + pane.body.cur_row = 1; + pane.body.cur_col = 4; + p.sync(); + var s = try p.render(a); + const body = s.region(.body, id).?.rect; + const gutter = body.x; + const at_rest = [_][]const u8{ s.at(gutter, body.y).grapheme(), s.at(gutter, body.y + 4).grapheme(), s.at(gutter, body.y + 6).grapheme() }; + for (at_rest) |g| try std.testing.expect(!std.mem.eql(u8, g, "p") and !std.mem.eql(u8, g, "g") and !std.mem.eql(u8, g, "e")); + const plain_bg = s.at(gutter + panes.File.gutterWidth(pane) + 4, body.y + 1).style.bg; + // `]`: nothing until its level shows; then `p` on the next paragraph. + p.update(.{ .key = .{ .cp = ']' } }); + p.advance(p.clock.now_ns); + _ = frame.reset(.retain_capacity); + s = try p.render(a); + try std.testing.expect(!std.mem.eql(u8, s.at(gutter, body.y + 4).grapheme(), "p")); + p.clock.now_ns = p.view().tag_state.due_ns; + _ = frame.reset(.retain_capacity); + s = try p.render(a); + try std.testing.expectEqualStrings("p", s.at(gutter, body.y + 4).grapheme()); + p.update(.{ .key = .{ .cp = Key.escape } }); + // `g`: its first and last lines. + p.update(.{ .key = .{ .cp = 'g' } }); + p.advance(p.clock.now_ns); + p.clock.now_ns = p.view().tag_state.due_ns; + _ = frame.reset(.retain_capacity); + s = try p.render(a); + try std.testing.expectEqualStrings("g", s.at(gutter, body.y).grapheme()); + try std.testing.expectEqualStrings("e", s.at(gutter, body.y + 6).grapheme()); + p.update(.{ .key = .{ .cp = Key.escape } }); + // `m` unrolled, its cursor on `i`: the inside of the braces around the + // caret tinted. + p.update(.{ .key = .{ .cp = 'm' } }); + p.update(.{ .key = .{ .cp = Key.down } }); + p.view().tag_state.hi = bindings.nodeAt(.match, "i").?.key; + _ = frame.reset(.retain_capacity); + s = try p.render(a); + const lit = s.at(gutter + panes.File.gutterWidth(pane) + 4, body.y + 1).style.bg; + try std.testing.expect(!std.meta.eql(plain_bg, lit)); + // At rest again: the gutter as it was. + p.update(.{ .key = .{ .cp = Key.escape } }); + _ = frame.reset(.retain_capacity); + s = try p.render(a); + try std.testing.expectEqualStrings(at_rest[1], s.at(gutter, body.y + 4).grapheme()); +} diff --git a/core/jj.zig b/core/jj.zig index c1d07662..7f1e5623 100644 --- a/core/jj.zig +++ b/core/jj.zig @@ -2030,14 +2030,15 @@ fn ownerOf(ch: *const Changes, f: *const File.State, row: usize) PinIndex { /// The line `]g` (`forward`) or `[g` goes to from buffer line `from` of /// the pane: the next or the previous change's first line (the first of a /// run of lines one pin wrote or took away: a ghost line is a line); null -/// with none shown, or none that way. -pub fn nextChange(p: *Pardes, pane: *const Pane, from: usize, forward: bool) ?usize { +/// with none shown, or none that way, or none in the `most` lines looked +/// at (a body's painted targets look at the rows shown alone). +pub fn nextChange(p: *Pardes, pane: *const Pane, from: usize, forward: bool, most: usize) ?usize { if (pane.layers.lanes == 0) return null; const f = if (pane.file) |*file| file else return null; const ch = answered(p, f.layer.owner) orelse return null; const n = File.lineCount(f.content); var row = from; - while (true) { + for (0..most) |_| { if (forward) { row += 1; if (row >= n) return null; @@ -2048,6 +2049,7 @@ pub fn nextChange(p: *Pardes, pane: *const Pane, from: usize, forward: bool) ?us const owner = ownerOf(ch, f, row); if (owner != .none and (row == 0 or ownerOf(ch, f, row - 1) != owner)) return row; } + return null; } /// A Look (B3) at column `col` of body row `vr` of pane `id` on the id of diff --git a/core/normal.zig b/core/normal.zig index 2ec8a4da..ea2bbc31 100644 --- a/core/normal.zig +++ b/core/normal.zig @@ -249,7 +249,7 @@ fn objectJump(e: Editor, t: *Text, text: []const u8, range: modal.Selection, obj const tree = nodeTree(e, t, text) orelse return; var last = range; for (0..count) |_| { - const s = syntax.objectNext(tree.path, tree.root, tree.text, object, forward, tree.in(modal.selectionCursor(text, last))) orelse break; + const s = syntax.objectNext(tree.path, tree.root, tree.text, object, forward, tree.in(modal.selectionCursor(text, last)), null) orelse break; const next: modal.Selection = .{ .anchor = tree.out(s.from, false), .head = tree.out(s.to, s.to > s.from) }; if (std.meta.eql(next, last)) break; last = next; @@ -1317,7 +1317,7 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error! .view_scroll_down => if (t.what == .body) return t.scrollViewMove(p.settings.tab, text, range, 1), .view_scroll_up => if (t.what == .body) return t.scrollViewMove(p.settings.tab, text, range, -1), // The next and the previous of the changes this view shows (jj.zig). - .goto_change => if (@import("jj.zig").nextChange(p, pane, @intCast(@max(0, t.cur_row)), a.forward)) |line| + .goto_change => if (@import("jj.zig").nextChange(p, pane, @intCast(@max(0, t.cur_row)), a.forward, std.math.maxInt(usize))) |line| return pointMove(p.settings.tab, t, text, range, modal.lineStartOffset(text, line)), .goto_diagnostic, .goto_diagnostic_end => { // Once a Diagnostics query fed them, the diagnostics are this diff --git a/core/syntax.zig b/core/syntax.zig index 08ea1fb4..a388573b 100644 --- a/core/syntax.zig +++ b/core/syntax.zig @@ -566,7 +566,7 @@ pub fn objectAt(path: []const u8, tree_ptr: *anyopaque, text: []const u8, object /// `]f`/`[f` and kin: the next object starting after byte `at`, or the /// previous one ending before it (helix goto_treesitter_object), from the /// first of `.movement`, `.around`, `.inside` the query names. -pub fn objectNext(path: []const u8, tree_ptr: *anyopaque, text: []const u8, object: Object, forward: bool, at: usize) ?Span { +pub fn objectNext(path: []const u8, tree_ptr: *anyopaque, text: []const u8, object: Object, forward: bool, at: usize, within: ?[2]usize) ?Span { const q = objectQuery(path) orelse return null; var buf: [32]u8 = undefined; const capture = for ([_][]const u8{ "movement", "around", "inside" }) |kind| { @@ -576,6 +576,9 @@ pub fn objectNext(path: []const u8, tree_ptr: *anyopaque, text: []const u8, obje const tree: *const ts.Tree = @ptrCast(@alignCast(tree_ptr)); const cursor = ts.QueryCursor.create(); defer cursor.destroy(); + // Only the objects these bytes hold (a body's rows shown): its painted + // targets (body_layer.paintTargets). + if (within) |w| cursor.setByteRange(@intCast(w[0]), @intCast(w[1])) catch return null; cursor.exec(q, tree.rootNode()); var best: ?Span = null; while (cursor.nextMatch()) |match| { -- cgit v1.3 From 791d47a64db09f842d23b3d0b03c40951f30aae6 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 24 Nov 2026 22:32:25 -0300 Subject: walk: Enter on a word of the walk with the keyboard in the tag Looks it as a click does (Tab Execs it, as B2), and out of rest the walk folds to its newest word, its older ones `·` (pick-ui SPEC §6.3, §3.4.3, walk UI line F item 5, the gaps line B left): keys.zig handleKey's Enter-in-a-tag asks tagline.trailAt at the cursor's byte before taking the word as a builtin's operand, the keyboard back in the body as a click leaves it; Trail.folded says how many back steps a tag writes whole (shown_steps at rest, one while TagState.hostOf is its pane), which Trail.write, bytes and stepAt now take (wordOf's fold the caller's), so the name's offset (tagline.nameAt), the forward span, a click on a step, the drafted name and the name's tint all read the trail as it is drawn (nameAt, forwardSpan, onName and draw.tagTintRange take the session); TEST: Trail.zig "Enter on a word of the walk, the keyboard in the tag, goes back to its step ..." (SPC folds `‹@pN › · › rank.zig:20 ›`, Esc unfolds, Enter on rank.zig:10 goes back there); core-test 1026/1193 (167 skipped), 0 failed, load 8 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- core/Trail.zig | 61 ++++++++++++++++++++++++++++++++++++++++++++++---------- core/draw.zig | 10 +++++----- core/keys.zig | 7 +++++++ core/mouse.zig | 2 +- core/tagline.zig | 46 ++++++++++++++++++++++++------------------ 5 files changed, 91 insertions(+), 35 deletions(-) diff --git a/core/Trail.zig b/core/Trail.zig index b5dff554..571779b4 100644 --- a/core/Trail.zig +++ b/core/Trail.zig @@ -18,6 +18,7 @@ const look = @import("look.zig"); const Pardes = pardes.Pardes; const Pane = panes.Pane; const Spot = look.Spot; +const TagState = @import("TagState.zig"); const Trail = @This(); @@ -275,9 +276,9 @@ 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 { +fn wordOf(t: *const Trail, i: usize, whole: 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 "·"; + if (s != .owner and i < t.cur and t.cur - i > whole) 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 @@ -297,34 +298,43 @@ fn range(t: *const Trail, part: Part) [2]usize { } /// 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 { +/// path), or the forward steps', each with one before it (after the path): +/// the newest `whole` back steps whole, older ones `·` (`folded`). +pub fn write(t: *const Trail, part: Part, whole: usize, 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)}), + .back => try w.print("{s}" ++ sep, .{wordOf(t, i, whole, &buf)}), + .forward => try w.print(sep ++ "{s}", .{wordOf(t, i, whole, &buf)}), }; } /// The bytes `write` writes for `part`. -pub fn bytes(t: *const Trail, part: Part) usize { +pub fn bytes(t: *const Trail, part: Part, whole: usize) 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; + for (r[0]..r[1]) |i| n += wordOf(t, i, whole, &buf).len + sep.len; return n; } +/// The back steps pane `pane`'s tag writes whole: `shown_steps` at rest, +/// the newest alone while its tag is out of rest (SPEC §3.4.3), so a +/// state's head and the band's spines keep their room. +pub fn folded(p: *const Pardes, pane: *const Pane) usize { + const host = TagState.hostOf(p) orelse return shown_steps; + return if (p.panes[host] == pane) 1 else shown_steps; +} + /// 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 { +pub fn stepAt(t: *const Trail, part: Part, whole: usize, 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; + const n = wordOf(t, i, whole, &buf).len; if (off >= x and off < x + n) return @intCast(i); x += n; if (part == .back) x += sep.len; @@ -722,3 +732,34 @@ test "Jumps new-pane jumps as before the walk: a new pane for a file no pane sho }; try std.testing.expectEqual(open + 2, now); } + +test "Enter on a word of the walk, the keyboard in the tag, goes back to its step as a click does; out of rest the walk folds to its newest word" { + 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 }) |line| f.look(f.held, "rank.zig", line); + const r = p.view().active; + const pane = p.panes[r].?; + var buf: [4096 + 128]u8 = undefined; + var at: [64]u8 = undefined; + const rest = try std.fmt.bufPrint(&buf, "‹@p{d} › rank.zig:10 › rank.zig:20 › {s}/rank.zig Keep", .{ owner, f.dir }); + try std.testing.expect(std.mem.startsWith(u8, try tagOf(p, pane), rest)); + // SPC: out of rest, the older steps are `·`, the owner and the newest + // whole; back at rest, as they were. + p.update(.{ .key = .{ .cp = ' ' } }); + var folded_buf: [4096 + 128]u8 = undefined; + try std.testing.expect(std.mem.startsWith(u8, try tagOf(p, pane), try std.fmt.bufPrint(&folded_buf, "‹@p{d} › · › rank.zig:20 › {s}/rank.zig", .{ owner, f.dir }))); + p.update(.{ .key = .{ .cp = pardes.Key.escape } }); + try std.testing.expect(std.mem.startsWith(u8, try tagOf(p, pane), rest)); + // The keyboard in the tag, its cursor on `rank.zig:10`: Enter goes back + // to that step, the keyboard in the body again. + pane.focus = .tag; + pane.tag.cur_row = 0; + pane.tag.cur_col = @intCast(std.mem.indexOf(u8, rest, "rank.zig:10").? + 2); + p.update(.{ .key = .{ .cp = pardes.Key.enter } }); + p.sync(); + try std.testing.expectEqualStrings("rank.zig:10", f.at(&at)); + try std.testing.expect(pane.focus == .body); +} diff --git a/core/draw.zig b/core/draw.zig index 5282b1c9..cf62adf8 100644 --- a/core/draw.zig +++ b/core/draw.zig @@ -631,7 +631,7 @@ fn joinCells(s: *Surface, x: u16, y: u16, cells: []const Cell, from: usize, w: u if (!cells[from].default and cells[from].len == 0) blank(&row[x], ink); } -fn tagTintRange(pane: *const Pane, tag: []const u8, prefix_len: usize) ?struct { lo: usize, hi: usize } { +fn tagTintRange(p: *const Pardes, pane: *const Pane, tag: []const u8, prefix_len: usize) ?struct { lo: usize, hi: usize } { if (pane.isTerminal()) { // `tag` is the first row; a prefix longer than it ran to a second. var words = std.mem.tokenizeAny(u8, tag[@min(prefix_len, tag.len)..], " \t\r\n"); @@ -642,7 +642,7 @@ fn tagTintRange(pane: *const Pane, tag: []const u8, prefix_len: usize) ?struct { } return null; } - var start: usize = tagline.nameAt(pane); + var start: usize = tagline.nameAt(p, 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: { @@ -955,7 +955,7 @@ 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(tagline.nameAt(pane) + @as(usize, @intCast(@max(0, pane.input.cur_col))))); + const at = modal.positionAt(shown.text, shown.fromReal(tagline.nameAt(p, 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 and head == null) caret: { @@ -975,10 +975,10 @@ 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) + if (tagTintRange(p, 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); + const ahead = tagline.forwardSpan(p, 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. diff --git a/core/keys.zig b/core/keys.zig index 78f45820..651d6417 100644 --- a/core/keys.zig +++ b/core/keys.zig @@ -401,6 +401,13 @@ pub fn handleKey(p: *Pardes, key: Key) void { break :word .{ b.lo, b.hi }; }; const txt = shown[span[0]..span[1]]; + // On a word of the pane's walk, the step's Look or Exec, as a + // click there (SPEC §6.3). + if (header == null and t.what == .tag) if (tagline.trailAt(p, pane, modal.selectionCursor(shown, range))) |step| { + pane.focus = .body; + if (cmd == config.look_cmd) pardes.Trail.lookStep(p, p.view().active, step) else pardes.Trail.execStep(p, p.view().active, step); + return; + }; // A column tag's command acts on that column, empty or not. p.exec_column = if (header != null) p.headerColumn() else null; defer p.exec_column = null; diff --git a/core/mouse.zig b/core/mouse.zig index 400d020b..48546c12 100644 --- a/core/mouse.zig +++ b/core/mouse.zig @@ -1265,7 +1265,7 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { // (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| { + if (if (dragged) null else tagline.onName(p, 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); diff --git a/core/tagline.zig b/core/tagline.zig index 78d5a256..e95d68de 100644 --- a/core/tagline.zig +++ b/core/tagline.zig @@ -163,11 +163,12 @@ pub fn pathPrefix(p: *const Pardes, arena: std.mem.Allocator, pane: *Pane) ![]co // 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); + const whole = pardes.Trail.folded(p, pane); + const room = try arena.alloc(u8, pane.trail.bytes(.back, whole) + name.len + pane.trail.bytes(.forward, whole) + keep_word.len); var w: std.Io.Writer = .fixed(room); - pane.trail.write(.back, &w) catch return error.OutOfMemory; + pane.trail.write(.back, whole, &w) catch return error.OutOfMemory; w.writeAll(name) catch return error.OutOfMemory; - pane.trail.write(.forward, &w) catch return error.OutOfMemory; + pane.trail.write(.forward, whole, &w) catch return error.OutOfMemory; w.writeAll(keep_word) catch return error.OutOfMemory; return w.buffered(); } @@ -183,17 +184,29 @@ pub fn pathPrefix(p: *const Pardes, arena: std.mem.Allocator, pane: *Pane) ![]co } /// 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; +pub fn nameAt(p: *const Pardes, pane: *const Pane) usize { + return if (pane.file != null and pane.trail.n > 0) pane.trail.bytes(.back, pardes.Trail.folded(p, pane)) 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 { +pub fn forwardSpan(p: *const Pardes, pane: *const Pane) [2]usize { const f = pane.file orelse return .{ 0, 0 }; if (pane.trail.n == 0) return .{ 0, 0 }; + const whole = pardes.Trail.folded(p, pane); 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) }; + const lo = pane.trail.bytes(.back, whole) + name.len; + return .{ lo, lo + pane.trail.bytes(.forward, whole) }; +} + +/// The step of pane `pane`'s walk whose word is at byte `at` of its tag's +/// text, if one is there. +pub fn trailAt(p: *const Pardes, pane: *const Pane, at: usize) ?u8 { + if (pane.trail.n == 0 or pane.file == null) return null; + const whole = pardes.Trail.folded(p, pane); + const ahead = forwardSpan(p, pane); + if (at < nameAt(p, pane)) return pane.trail.stepAt(.back, whole, at); + if (at >= ahead[0] and at < ahead[1]) return pane.trail.stepAt(.forward, whole, at - ahead[0]); + return null; } /// A click at shown row `row`, display column `col` of pane `id`'s tag on @@ -201,15 +214,9 @@ pub fn forwardSpan(pane: *const Pane) [2]usize { /// (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; + const i = trailAt(p, pane, at.col) orelse return false; if (run) pardes.Trail.execStep(p, id, i) else pardes.Trail.lookStep(p, id, i); return true; } @@ -402,14 +409,15 @@ pub fn tagOffsetAt(p: *Pardes, pane: *Pane, row: usize, col: usize) ?modal.Curso /// 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 { +pub fn onName(p: *const Pardes, pane: *Pane, row: usize, col: usize) ?usize { + const tab = p.settings.tab; 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; 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; + pane.trail.write(.back, pardes.Trail.folded(p, pane), &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; @@ -424,8 +432,8 @@ pub fn typedIntoName(p: *Pardes, pane: *Pane, key: pardes.Key) bool { if (!panes.Output.fileTraits(f.output).saves or pane.tag.cur_row != 0) return false; // 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); + if (col < nameAt(p, pane)) return false; + const at = col - nameAt(p, 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; -- cgit v1.3 From 806dc79a694c9df50cf3e13e9091986ebc74cb96 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 24 Nov 2026 22:46:35 -0300 Subject: Pick: SPC t t (Themes) is a picker of the themes in the asking pane's own tag, the whole window wearing the theme under the cursor and no pane dimmed (every one flagged previewing), Enter wearing it, Esc putting the session's own back (pick-ui SPEC §5.1, §3.6, walk UI line F item 4): a source `themes` (Pick.Source; its rows the themes in their order, the cursor starting on the one worn; no reader, no acts, no other sources, no second row), its preview colors.previewTheme, the one function the `:theme ` argument rows can call too: Pardes.theme_preview over the session's theme in theme() and chromeTheme() (its chrome worked out once a theme, never a frame; nothing loaded, a ThemeFile and a custom theme untouched under it), set in the step of the key that moved the cursor (Pick.produceAll) and cleared at the roll-up; both fields on root.zig's kept_out list (derived from the picker's cursor, which the digest has); Themes from a 9P script or under `Jumps new-pane` opens +Themes as before; TEST: Pick.zig "SPC t t is a picker of the themes ..." (its host, the cursor on the worn theme, every pane previewing, Down wears the next with the session's unchanged, Esc, Enter); core-test 1027/1194 (167 skipped), 0 failed, load 8 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- core/Core.zig | 9 +++++- core/Pick.zig | 87 +++++++++++++++++++++++++++++++++++++++++++++++++++++-- core/builtins.zig | 3 ++ core/colors.zig | 15 ++++++++++ core/root.zig | 1 + 5 files changed, 112 insertions(+), 3 deletions(-) diff --git a/core/Core.zig b/core/Core.zig index 6ee82370..d0011048 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -337,6 +337,11 @@ locations_cache: locations.Cache = .{}, tty_filter_palette: pardes.Term.FilterPalette = .{}, font_request_taken: bool = false, custom_theme: ?Theme = null, +/// The theme the window wears while a picker of them (or `:theme `) +/// previews one, by index, and its chrome (colors.previewTheme); the +/// session's own theme untouched under it. +theme_preview: ?u16 = null, +preview_chrome: ChromeTheme = colors.initial_chrome, /// bodyChrome's: the theme it was worked out for, and it. body_chrome: ?struct { theme: Theme, chrome: ChromeTheme } = null, theme_file_path: config.Settings.Text(limits.host_path_cap) = .{}, @@ -525,7 +530,7 @@ pub const replica = .{ "opts", "dump_out", "dump_export", "tape", }, - .derived = .{ "shell_rows", "diff_output", "locations_cache", "retired_panes", "tty_filter_palette", "body_chrome" }, + .derived = .{ "shell_rows", "diff_output", "locations_cache", "retired_panes", "tty_filter_palette", "body_chrome", "theme_preview", "preview_chrome" }, // The host's handles, the state file every session of the user // shares (and Recent read from it), this session's closed panes, and // the files of a host with no file system of its own. (The 9P @@ -2130,12 +2135,14 @@ fn sizes(p: *const Pardes, pane: *const Pane) bool { } pub fn theme(p: *const Pardes) *const Theme { + if (p.theme_preview) |i| return &themes[i]; if (p.custom_theme) |*custom| return custom; return &themes[p.settings.theme]; } /// The colours of the chrome: the theme's, set as it changes. pub fn chromeTheme(p: *const Pardes) *const ChromeTheme { + if (p.theme_preview != null) return &p.preview_chrome; return &p.chrome; } diff --git a/core/Pick.zig b/core/Pick.zig index 7913a7e0..a7a0d899 100644 --- a/core/Pick.zig +++ b/core/Pick.zig @@ -48,7 +48,7 @@ const Key = pardes.Key; /// 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 }; +pub const Source = enum { find, grep, recent, panes, symbols, all, jumplist, list, themes }; /// Each source's word in the tag and the leader keys of the builtin that /// opens it, its key cells (`␣ f Find`). @@ -61,6 +61,7 @@ const words = std.EnumArray(Source, struct { word: []const u8, keys: []const u8 .all = .{ .word = "All", .keys = "" }, .jumplist = .{ .word = "Jumplist", .keys = "j" }, .list = .{ .word = "List", .keys = "l" }, + .themes = .{ .word = "Themes", .keys = "t" }, }); /// The pickers kept after they roll up, for their list words and Resume. @@ -181,6 +182,8 @@ pub fn open(p: *Pardes, from: usize, source: Source, word: []const u8, query: [] unroll(p, pk, query); start(p, pk); filter(p, pk); + // The themes: the cursor on the one worn (their order, the field empty). + if (source == .themes and query.len == 0 and p.custom_theme == null) p.view().tag_state.rows.at = @intCast(p.settings.theme); } /// A new picker in the ring, the oldest kept one dropped for it. @@ -217,6 +220,13 @@ fn hostIn(p: *Pardes, pk: *Pick, from: usize) !void { const asker = p.panes[from].?; pk.owner = asker.serial; pk.made = false; + // A theme is no place: its list is the asking pane's own tag (§3.5), + // and its preview the whole window. + if (pk.source == .themes) { + pk.landing = asker.serial; + p.view().active = from; + return; + } 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; @@ -247,6 +257,8 @@ fn unroll(p: *Pardes, pk: *Pick, query: []const u8) void { s.rows = .{ .at = @intCast(@min(pk.at, std.math.maxInt(u16))) }; pk.unrolled = true; pk.shown = no_row; + // The whole window previews a theme: no pane dimmed (SPEC §3.6). + if (pk.source == .themes) s.previewing = .full; if (p.paneBySerial(pk.landing)) |id| { s.previewing.set(id); const pane = p.panes[id].?; @@ -278,6 +290,9 @@ fn start(p: *Pardes, pk: *Pick) void { addRows(p, pk, out.written()); }, .list => addRows(p, pk, pk.rows), + .themes => for (pardes.colors.themes, 0..) |t, i| { + pk.names.add(p.gpa, t.name, 0, t.name.len, 0, @intCast(i)) catch return; + }, } } @@ -375,6 +390,8 @@ pub fn declsArrived(p: *Pardes, serial: u32) void { 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); + // A theme's preview in the step of the key that moved to it. + if (pk.source == .themes) pardes.colors.previewTheme(p, themeAt(p, pk)); if (tick) preview(p, pk); }; } @@ -389,6 +406,14 @@ pub fn busy(p: *const Pardes) bool { // ---- the rows ---- +/// The theme the cursor of a themes picker is on. +fn themeAt(p: *const Pardes, pk: *const Pick) ?usize { + const n = pk.names.hits.items.len; + if (n == 0) return null; + const at = @min(p.view().tag_state.rows.at, n - 1); + return pk.names.cands.items[pk.names.hits.items[at].cand].ref; +} + /// 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; @@ -492,6 +517,7 @@ fn rowAt(p: *Pardes, pk: *const Pick, arena: std.mem.Allocator, i: usize) !Row { const f = owner.file orelse return row; row.target = .{ .place = .{ .path = f.path, .at = .{ .line = cand.ref } } }; }, + .themes => {}, .recent, .jumplist, .list, .grep, .all => { const t = look.parsePathLine(text); row.pre = @intCast(t.end); @@ -534,6 +560,12 @@ pub fn head(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) !?TagState.Head { 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, " ⋯"); + // Themes have no acts and no other sources: no second row. + if (pk.source == .themes) { + try text.appendSlice(arena, " ⏎ wear it · esc"); + 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 = @intCast(ncells), .caret = caret }; + } // 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'); @@ -553,7 +585,7 @@ pub fn head(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) !?TagState.Head { 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) { + inline for (comptime std.enums.values(Source)) |src| if (src != .list and src != .themes) { if (src != pk.source) { if (!first) try text.append(arena, ' '); first = false; @@ -697,6 +729,7 @@ fn openText(p: *Pardes, path: []const u8) ?[]u8 { /// 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 { + if (pk.source == .themes) return pardes.colors.previewTheme(p, null); 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) { @@ -779,6 +812,18 @@ pub fn key(p: *Pardes, k: Key) void { return; } if (pk.spine == .acts) return actKey(p, pk, k); + // Themes: Enter wears the one under the cursor; the rows and the field. + if (pk.source == .themes) { + if (plain and k.cp == Key.enter) { + const at = themeAt(p, pk) orelse return; + TagState.toRest(p); + pardes.colors.setThemeIndex(p, at); + return; + } + if (s.rows.key(k, n)) return; + if (s.field.key(k)) filter(p, pk); + return; + } 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') { @@ -1779,3 +1824,41 @@ test "a picker from a reading pane unrolls in that pane, its own text set aside try std.testing.expect(p.panes[id].?.file.?.output == null); try std.testing.expectEqual(npanes, paneCount(p)); } + +test "SPC t t is a picker of the themes in the asking pane's tag, the whole window wearing the row under the cursor and nothing dimmed; Esc puts the theme back, Enter wears it" { + 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"); + const asker = p.view().active; + p.newScratchBelow(asker); + p.view().active = asker; + p.settings.jumps = .walk; + const themes = pardes.colors.themes; + const was = p.settings.theme; + const worn = p.theme().name; + for (" tt") |c| p.update(.{ .key = .{ .cp = c } }); + const s = &p.view().tag_state; + try std.testing.expectEqual(TagState.Kind.pick, s.kind); + try std.testing.expectEqual(Source.themes, live(p).?.source); + try std.testing.expectEqual(p.panes[asker].?.serial, s.host); + try std.testing.expectEqual(@as(u16, @intCast(was)), s.rows.at); + try std.testing.expectEqual(pardes.MAX_PANES, s.previewing.count()); + // Down: the window wears the next theme, the session's unchanged. + p.update(.{ .key = .{ .cp = if (was + 1 < themes.len) Key_.down else Key_.up } }); + const shown = s.rows.at; + try std.testing.expect(std.mem.eql(u8, p.theme().name, themes[shown].name) and shown != was); + try std.testing.expectEqual(was, p.settings.theme); + // Esc: its own again. + p.update(.{ .key = .{ .cp = Key_.escape } }); + try std.testing.expectEqualStrings(worn, p.theme().name); + try std.testing.expect(p.theme_preview == null); + // Again, and Enter wears it. + for (" tt") |c| p.update(.{ .key = .{ .cp = c } }); + p.update(.{ .key = .{ .cp = if (was + 1 < themes.len) Key_.down else Key_.up } }); + p.update(.{ .key = .{ .cp = Key_.enter } }); + try std.testing.expectEqual(@as(@TypeOf(p.settings.theme), @intCast(shown)), p.settings.theme); + try std.testing.expectEqual(TagState.Kind.rest, s.kind); + try std.testing.expect(p.theme_preview == null); + try std.testing.expectEqualStrings(themes[shown].name, p.theme().name); +} diff --git a/core/builtins.zig b/core/builtins.zig index c7e821dd..eac52555 100644 --- a/core/builtins.zig +++ b/core/builtins.zig @@ -797,6 +797,9 @@ pub const Themes = struct { pub const scope: Scope = .session; pub const output: OutputTraits = .{ .name = config.themes_buffer, .steps = true, .commands = true }; pub fn run(c: Ctx) void { + // From the keyboard, where the walk is on: a picker in the tag, the + // window wearing its row (Pick.zig, SPEC §5.1). + if (pardes.Pick.asked(c.p)) return pardes.Pick.open(c.p, c.id, .themes, "", "", ""); panes.Output.openThemes(c.p, c.id) catch |err| c.p.reportError(.at(c.id), "themes", err); } }; diff --git a/core/colors.zig b/core/colors.zig index 84595a30..0751d8c5 100644 --- a/core/colors.zig +++ b/core/colors.zig @@ -832,6 +832,21 @@ pub fn themeIndex(name: []const u8) ?usize { return null; } +/// The window wearing theme `index` (SPEC §5.1, a theme's preview), or +/// its own again (null): nothing loaded, the session's theme and a theme +/// file as they were; its chrome worked out once a theme, never a frame. +/// The themes picker's (Pick.zig), and `:theme `'s argument rows'. +pub fn previewTheme(p: *Pardes, index: ?usize) void { + const i = index orelse { + p.theme_preview = null; + return; + }; + if (i >= themes.len) return; + if (p.theme_preview) |had| if (had == i) return; + p.theme_preview = @intCast(i); + p.preview_chrome = ChromeTheme.fromTheme(&themes[i]); +} + pub fn setThemeIndex(p: *Pardes, index: usize) void { if (index >= themes.len or (p.custom_theme == null and p.theme_file_path.get().len == 0 and diff --git a/core/root.zig b/core/root.zig index a4adf7b1..88ae821b 100644 --- a/core/root.zig +++ b/core/root.zig @@ -761,6 +761,7 @@ const kept_out = [_]struct { []const u8, []const u8, []const u8 }{ .{ "Core.zig", "shell_rows", "a terminal's rows as read here, swept at every update; the terminal's own digest covers its active area, not its history (Term.zig `calls`)" }, .{ "Core.zig", "diff_output locations_cache tty_filter_palette body_chrome", "caches of pure functions of their key (a text, a theme): a step finds what it would make; a query row's colours from them are out of its digest (locations.Row.digest), and what a step asks a worker to paint is never decided by them (Stream.paintRows)" }, .{ "Core.zig", "retired_panes", "panes torn down this step, freed at its end" }, + .{ "Core.zig", "theme_preview preview_chrome", "a themes picker's preview (colors.previewTheme): made from the live picker's cursor, in the digest with it, after every step (Pick.produceAll) and gone at its roll-up; a step reading a theme meanwhile reads the one its own state previews" }, .{ "Core.zig", "multi_first multi_stop multi_index multi_count exec_depth exec_column", "a step's own: set by a key's replay across the ranges (normal.replaySels) and a word's run (exec.zig), each put back before the step ends; between steps what `init` makes, so a load takes them as it makes them (a dump's said 2^30 ranges once: a yank sized its register by it)" }, .{ "Core.zig", "rects col_x col_w", "a view's geometry: the layout pass's (layout.compute) over its columns and screen, at every sync and resize, and at a load (dump.afterLoad); never read before it" }, .{ "Core.zig", "distrusted frames tape", "Options: the client's own list, its runner's statistics, its tape" }, -- cgit v1.3 From 5d091b37b4641c274900d4d02b7f1d61b5a9301f Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 24 Nov 2026 22:51:55 -0300 Subject: lsp: a hover (SPC l k) and a rename (SPC l r) asked from the keyboard show in the edited pane's own body: the hover as ghost lines under the line it was asked at, no +Hover pane, Esc taking them away; Rename typed in that pane's tag (` Rename best → bester▌`, the old name struck), each whole-word place of the old name in the rows shown drawn struck with the new name after it as it is typed, Enter asking the server for it (its edits applied as before), Esc asking nothing (pick-ui SPEC §3.5, §14.1, R3, walk UI line F item 3, its hover and rename; code actions NOT done: the protocol client sends an action's title alone, no edit to preview or apply): Ask.hover (its pane, line, revision and first 1,024 bytes, in the dump; an edit of the text stops it showing), body_layer.hoverGhosts and renameGhosts (drawn after the rows as the message ghosts are, the rows below pushed down or a row's cells pushed right, never written, the rows shown alone), TagState.Kind.rename (its head; no band), Ask.openRename and renameKey, the name under the caret Ask.renamedWord (the preview is pardes's own whole-word match in view, the edit the server's on Enter); under `Jumps new-pane` or from a 9P script, +Hover and the rename prompt as before; TESTS: Ask.zig "a hover asked from the keyboard is ghost lines ..." and "SPC l r types the new name in the pane's own tag ..."; core-test 1029/1196 (167 skipped), 0 failed, load 8 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- core/Band.zig | 2 + core/TagState.zig | 17 +++++- core/body_layer.zig | 90 +++++++++++++++++++++++++++++++ core/builtins.zig | 3 ++ core/keys.zig | 7 +++ core/lsp/Ask.zig | 149 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 267 insertions(+), 1 deletion(-) diff --git a/core/Band.zig b/core/Band.zig index 13c4b9c0..63407626 100644 --- a/core/Band.zig +++ b/core/Band.zig @@ -100,6 +100,7 @@ pub fn takes(p: *Pardes, id: usize) u16 { 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), + .rename => return 0, } if (!s.unrolled) return 0; const cur = TagState.current(p, v) orelse return 0; @@ -151,6 +152,7 @@ pub fn of(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, id: usize) !?Band { try band.place(p, arena, pane, id); return band; }, + .rename => return null, } const cur = TagState.current(p, v).?; if (cur.root == .register) { diff --git a/core/TagState.zig b/core/TagState.zig index 95df8937..1d6abace 100644 --- a/core/TagState.zig +++ b/core/TagState.zig @@ -24,12 +24,13 @@ const Root = bindings.Root; const Field = @import("Field.zig"); const Band = @import("Band.zig"); const Names = @import("Names.zig"); +const Ask = @import("lsp/Ask.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 Kind = enum(u8) { rest, help, describe, pick, rename }; pub const replica = .{ .len = .{ .{ "scope", "scope_n" }, .{ "hits", "nhits" } } }; @@ -483,6 +484,20 @@ pub fn head(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) !?Head { return b.done(); }, .pick => return @import("Pick.zig").head(p, arena, pane), + // `Rename`, the name under the caret struck, the new one typed: + // ` Rename best → top▌ ⏎ rename · esc` (SPEC §3.5). + .rename => { + try b.put(" Rename "); + try b.styled(Ask.renamedWord(pane) orelse "", .strike); + try b.put(" → "); + var h = b.done(); + h.caret = @intCast(b.text.items.len + s.field.caret); + try b.put(s.field.text()); + try b.put(" ⏎ rename · esc"); + h.text = b.text.items; + h.spans = b.spans.items; + return h; + }, } const cur = current(p, v) orelse return null; try b.put(" "); diff --git a/core/body_layer.zig b/core/body_layer.zig index 13fc7a85..13c24f97 100644 --- a/core/body_layer.zig +++ b/core/body_layer.zig @@ -472,6 +472,8 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane } if (pane.file != null) paintTargets(p, s, arena, pane, r, tx, tw, body_y, body_h); + if (p.lsp_ask.hover != null) hoverGhosts(p, s, pane, tx, tw, body_y, body_h); + if (p.view().tag_state.kind == .rename) renameGhosts(p, s, pane, tx, tw, body_y, body_h); // `gw`'s labels, two letters over the start of each word if (pane.jump.items.len > 0) labels: { @@ -632,6 +634,94 @@ fn paintTargets(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, } } +/// A hover's answer as ghost lines under the line it was asked at (SPEC +/// §3.5, R3): the rows below move down by its lines (those past the body's +/// foot not shown meanwhile), the buffer untouched. Bounded by the rows +/// shown and the hover's `Ask.hover_max` bytes. +fn hoverGhosts(p: *Pardes, s: *Surface, pane: *Pane, tx: u16, tw: u16, body_y: u16, body_h: u16) void { + const h = &p.lsp_ask.hover.?; + if (h.serial != pane.serial) return; + const f = if (pane.file) |*file| file else return; + if (f.revision != h.revision) return; + const tab = p.settings.tab; + // The last row the line is shown on. + var under: ?u16 = null; + var row: u16 = pane.context_rows; + while (row < body_h) : (row += 1) { + if (pane.wrapAt(tab, row).line == h.row) under = row else if (under != null) break; + } + const at = under orelse return; + const text = std.mem.trimEnd(u8, h.text.slice(), "\n"); + const k: u16 = @intCast(@min(std.mem.count(u8, text, "\n") + 1, body_h - at - 1)); + if (k == 0) return; + var dst: u16 = body_h - 1; + while (dst >= at + 1 + k) : (dst -= 1) { + const to = @as(usize, body_y + dst) * s.cols + tx; + const from = @as(usize, body_y + dst - k) * s.cols + tx; + @memcpy(s.cells[to..][0..tw], s.cells[from..][0..tw]); + } + const th = p.theme(); + const style: CellStyle = .{ .fg = .{ .rgb = th.tag_fg }, .bg = .{ .rgb = th.tag_bg } }; + const gutter: u16 = File.gutterWidth(pane); + var lines = std.mem.splitScalar(u8, text, '\n'); + for (0..k) |i| { + const y = body_y + at + 1 + @as(u16, @intCast(i)); + s.fill(tx, y, tw, 1, .{ .bg = .{ .rgb = th.tag_bg } }); + if (gutter + 2 < tw) _ = s.print(tx + gutter + 2, y, tw - gutter - 2, lines.next() orelse "", style); + } +} + +/// A Rename typed in this body's tag, shown in its rows (SPEC §3.5, R3): +/// each whole-word place of the name under the caret in the rows shown +/// struck, the name typed after it, the rest of its row pushed right. +/// Never written; bounded by the rows shown. +fn renameGhosts(p: *Pardes, s: *Surface, pane: *Pane, tx: u16, tw: u16, body_y: u16, body_h: u16) void { + const host = TagState.hostOf(p) orelse return; + if (p.panes[host] != pane or pane.file == null) return; + const old = @import("lsp/Ask.zig").renamedWord(pane) orelse return; + const new = p.view().tag_state.field.text(); + const tab = p.settings.tab; + const chrome = p.chromeTheme(); + const th = p.theme(); + const added: CellStyle = .{ .fg = .{ .rgb = chrome.diagnostic_hint }, .bg = if (th.bg) |c| .{ .rgb = c } else .default, .bold = true }; + const wide: u16 = @intCast(@min(File.displayWidth(tab, new), tw)); + const gutter: i32 = File.gutterWidth(pane); + var row: u16 = pane.context_rows; + while (row < body_h) : (row += 1) { + const w = pane.wrapAt(tab, row); + if (w.line < 0) continue; + const line = File.sourceLine(pane, w.line); + const from: usize = @min(line.len, @as(usize, @intCast(@max(0, w.at)))); + const next = pane.wrapAt(tab, row + 1); + const to: usize = if (next.line == w.line) @min(line.len, @as(usize, @intCast(@max(0, next.at)))) else line.len; + // Right to left, so a push leaves the places before it where they are. + var end = to; + while (std.mem.lastIndexOf(u8, line[from..end], old)) |k| { + const at = from + k; + end = at; + const before = at > 0 and (std.ascii.isAlphanumeric(line[at - 1]) or line[at - 1] == '_'); + const after = at + old.len < line.len and (std.ascii.isAlphanumeric(line[at + old.len]) or line[at + old.len] == '_'); + if (before or after) continue; + const c0 = gutter + w.pad + File.displayOffset(tab, pane, w.line, w.at, @intCast(at)); + const c1 = gutter + w.pad + File.displayOffset(tab, pane, w.line, w.at, @intCast(at + old.len)); + if (c0 < gutter or c1 > tw) continue; + const y = body_y + row; + var c: u16 = @intCast(c0); + while (c < c1) : (c += 1) { + const cell = s.at(tx + c, y); + cell.style.strikethrough = true; + cell.style.fg = .{ .rgb = chrome.diagnostic_error }; + } + const x: u16 = @intCast(c1); + if (x + wide < tw) { + const cells = s.cells[@as(usize, y) * s.cols + tx ..][0..tw]; + std.mem.copyBackwards(Cell, cells[x + wide ..], cells[x .. tw - wide]); + } + _ = s.print(tx + x, y, tw - x, new, added); + } + } +} + /// The line a motion role would go to from the caret of `pane`, looked for /// in lines `lo` to `hi` (the rows shown) alone; null for none there, or a /// role that is no line's. diff --git a/core/builtins.zig b/core/builtins.zig index eac52555..ffb82c4b 100644 --- a/core/builtins.zig +++ b/core/builtins.zig @@ -2275,6 +2275,9 @@ pub const Rename = struct { pub fn run(c: Ctx) void { const a = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); if (a.len > 0) return c.p.lspRequest(c.id, .rename, a); + // From the keyboard, where the walk is on: typed in the pane's own + // tag, its edits drawn in its body as they are typed (SPEC §3.5). + if (pardes.Pick.asked(c.p) and c.pane.file != null) return @import("lsp/Ask.zig").openRename(c.p, c.id); panes.startPrompt(c.p, c.pane, &c.pane.body, .{ .search = config.rename_marker }); } }; diff --git a/core/keys.zig b/core/keys.zig index 651d6417..6dea7278 100644 --- a/core/keys.zig +++ b/core/keys.zig @@ -213,6 +213,12 @@ pub fn handleKey(p: *Pardes, key: Key) void { } // A tag in a typing state takes every key (TagState: Help, describe-key). if (p.view().tag_state.kind != .rest) return tagStateKey(p, key); + // Esc takes a hover's ghost lines away (SPEC §3.5) before anything else + // it does. + if (p.lsp_ask.hover != null and hit(key, config.escape)) { + p.lsp_ask.hover = null; + return; + } if (p.view().window_pick != null) return layout.windowKey(p, key); const pane = p.panes[p.view().active] orelse return; layout.noteTyped(p); @@ -583,6 +589,7 @@ fn tagStateKey(p: *Pardes, key: Key) void { TagState.describeKey(p, key); }, .pick => return @import("Pick.zig").key(p, key), + .rename => return @import("lsp/Ask.zig").renameKey(p, key), .help => { const plain = !key.ctrl and !key.alt; if (plain and key.cp == Key.enter) { diff --git a/core/lsp/Ask.zig b/core/lsp/Ask.zig index 976821d5..f8cb8cfc 100644 --- a/core/lsp/Ask.zig +++ b/core/lsp/Ask.zig @@ -18,6 +18,7 @@ const memory = @import("../memory.zig"); const Pardes = pardes.Pardes; const Pane = panes.Pane; const Effect = pardes.Effect; +const TagState = @import("../TagState.zig"); const Ask = @This(); @@ -38,6 +39,12 @@ wait: ?struct { row: i32 = 0, col: i32 = 0, } = null, +/// A hover asked from the keyboard (where the walk is on), drawn as ghost +/// lines under the line it was asked at in its own body (pick-ui SPEC §3.5, +/// the coordinator's R3: never written): until Esc, an edit of that text, +/// or the next hover. Its first `hover_max` bytes. +hover: ?struct { serial: u32, row: i32, revision: u32, text: Effect.Buf(hover_max) } = null, +pub const hover_max = 1024; const TAG_TEXT_INSET = pardes.TAG_TEXT_INSET; pub fn lspRequest(p: *Pardes, asked: usize, kind: lsp.Kind, arg_in: []const u8) void { @@ -247,6 +254,48 @@ fn applyLspEdits(p: *Pardes, pane: *Pane, revision: u32, edits: []const LspEdit) return true; } +/// Rename typed in pane `id`'s own tag (SPEC §3.5): the field the name +/// under its caret, which the body shows renamed as it is typed +/// (body_layer.renameGhosts) until Enter asks the server, or Esc. +pub fn openRename(p: *Pardes, id: usize) void { + const pane = p.panes[id] orelse return; + const old = renamedWord(pane) orelse return p.reportFailure(id, "Rename: nothing here to rename"); + TagState.toRest(p); + const s = &p.view().tag_state; + s.kind = .rename; + s.host = pane.serial; + s.field.set(old); + s.previewing.set(id); +} + +/// A key in Rename's field: Enter asks the server to rename to it (a name +/// the same as the old is no question), Esc (the tag's) puts it away. +pub fn renameKey(p: *Pardes, key: pardes.Key) void { + const s = &p.view().tag_state; + if (!key.ctrl and !key.alt and key.cp == pardes.Key.enter) { + const id = TagState.hostOf(p) orelse return TagState.toRest(p); + var name: Effect.Buf(128) = .{}; + const typed = std.mem.trim(u8, s.field.text(), " "); + const same = std.mem.eql(u8, typed, renamedWord(p.panes[id].?) orelse ""); + if (typed.len <= 128) name = .from(typed); + TagState.toRest(p); + if (same) return; + if (typed.len > 128) return p.reportFailure(id, "Rename: a name is at most 128 bytes"); + return lspRequest(p, id, .rename, name.slice()); + } + _ = s.field.key(key); +} + +/// The name under pane `pane`'s caret, which a Rename renames. +pub fn renamedWord(pane: *const Pane) ?[]const u8 { + const line = panes.File.sourceLine(pane, pane.body.cur_row); + var lo: usize = @min(@as(usize, @intCast(@max(0, pane.body.cur_col))), line.len); + var hi = lo; + while (lo > 0 and (std.ascii.isAlphanumeric(line[lo - 1]) or line[lo - 1] == '_')) lo -= 1; + while (hi < line.len and (std.ascii.isAlphanumeric(line[hi]) or line[hi] == '_')) hi += 1; + return if (hi > lo) line[lo..hi] else null; +} + /// The builtin word that asks `kind`, for what it says. fn lspWord(kind: lsp.Kind) []const u8 { return switch (kind) { @@ -333,6 +382,14 @@ pub fn lspResponse(p: *Pardes, id: u32, response: ?[]const u8) void { return; } + // A hover asked from the keyboard: ghost lines in its own body, no + // +Hover pane (SPEC §3.5). + if (w.kind == .hover and pardes.Pick.asked(p)) { + var cut = @min(rows.len, hover_max); + while (cut < rows.len and cut > 0 and rows[cut] & 0xC0 == 0x80) cut -= 1; + p.lsp_ask.hover = .{ .serial = pane.serial, .row = w.row, .revision = w.revision, .text = .from(rows[0..cut]) }; + return; + } const from: panes.Output.Origin = .{ .query = w.kind }; const nrows = std.mem.count(u8, rows, "\n"); if ((panes.Output.traits(from).jumps or w.kind == .diagnostics) and nrows == 1) { @@ -626,3 +683,95 @@ test "LSP failure clears only its matching wait without completion indentation" try std.testing.expectEqualStrings("x ", pane.file.?.content); try std.testing.expectEqual(@as(i32, 4), pane.body.cur_col); } + +test "a hover asked from the keyboard is ghost lines under the line it was asked at, drawn and never written, no +Hover pane; Esc takes them away" { + if (!lsp.supports.contains(.hover)) return error.SkipZigTest; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 20 }); + defer p.deinit(); + const pane = try p.setTestFile("one\ntwo\nthree\nfour\n"); + const id = p.view().active; + p.settings.jumps = .walk; + while (p.nextEffect()) |_| {} + pane.focus = .body; + pane.body.cur_row = 1; + var npanes: usize = 0; + for (p.panes) |slot| npanes += @intFromBool(slot != null); + p.lspRequest(id, .hover, ""); + while (p.nextEffect()) |_| {} + lspResponse(p, p.lsp_ask.seq, "pub fn add(a: i32) i32\nadds them\n"); + var now: usize = 0; + for (p.panes) |slot| now += @intFromBool(slot != null); + try std.testing.expectEqual(npanes, now); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + p.sync(); + var s = try p.render(frame.allocator()); + const body = s.region(.body, id).?.rect; + var buf: [256]u8 = undefined; + try std.testing.expect(std.mem.indexOf(u8, rowText(s, body.x, body.y + 1, &buf), "two") != null); + try std.testing.expect(std.mem.indexOf(u8, rowText(s, body.x, body.y + 2, &buf), "pub fn add(a: i32) i32") != null); + try std.testing.expect(std.mem.indexOf(u8, rowText(s, body.x, body.y + 3, &buf), "adds them") != null); + try std.testing.expect(std.mem.indexOf(u8, rowText(s, body.x, body.y + 4, &buf), "three") != null); + try std.testing.expectEqualStrings("one\ntwo\nthree\nfour\n", pane.file.?.content); + p.update(.{ .key = .{ .cp = pardes.Key.escape } }); + try std.testing.expect(p.lsp_ask.hover == null); + try std.testing.expectEqual(id, p.view().active); + _ = frame.reset(.retain_capacity); + s = try p.render(frame.allocator()); + try std.testing.expect(std.mem.indexOf(u8, rowText(s, body.x, body.y + 2, &buf), "three") != null); +} + +/// Grid row `y` of `s` from column `x`, as text. +fn rowText(s: *const pardes.Surface, x: u16, y: u16, buf: []u8) []const u8 { + var n: usize = 0; + for (x..s.cols) |col| { + const g = s.cells[@as(usize, y) * s.cols + col].grapheme(); + if (n + g.len > buf.len) break; + @memcpy(buf[n..][0..g.len], g); + n += g.len; + } + return buf[0..n]; +} + +test "SPC l r types the new name in the pane's own tag, the body showing each place in view renamed as it is typed, never written; Enter asks the server for it, Esc puts it away" { + if (!lsp.supports.contains(.rename)) return error.SkipZigTest; + const Key = pardes.Key; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 20 }); + defer p.deinit(); + const pane = try p.setTestFile("const best = 1;\nconst b = best + best;\nconst bestow = 2;\n"); + const id = p.view().active; + p.settings.jumps = .walk; + pane.focus = .body; + pane.body.cur_row = 0; + pane.body.cur_col = 7; + for (" lr") |c| p.update(.{ .key = .{ .cp = c } }); + const s = &p.view().tag_state; + try std.testing.expectEqual(TagState.Kind.rename, s.kind); + try std.testing.expectEqualStrings("best", s.field.text()); + for ("er") |c| p.update(.{ .key = .{ .cp = c } }); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + const a = frame.allocator(); + try std.testing.expect(std.mem.indexOf(u8, try pardes.tagline.tagText(p, a, pane), " Rename best → bester") != null); + p.sync(); + const sf = try p.render(a); + const body = sf.region(.body, id).?.rect; + var buf: [256]u8 = undefined; + // Each `best` in view struck and followed by the new name; `bestow` is + // another word. + try std.testing.expect(std.mem.indexOf(u8, rowText(sf, body.x, body.y, &buf), "const bestbester = 1;") != null); + try std.testing.expect(std.mem.indexOf(u8, rowText(sf, body.x, body.y + 1, &buf), "const b = bestbester + bestbester;") != null); + try std.testing.expect(std.mem.indexOf(u8, rowText(sf, body.x, body.y + 2, &buf), "const bestow = 2;") != null); + try std.testing.expectEqualStrings("const best = 1;\nconst b = best + best;\nconst bestow = 2;\n", pane.file.?.content); + // Enter: the server asked to rename it, the tag at rest. + while (p.nextEffect()) |_| {} + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expectEqual(TagState.Kind.rest, s.kind); + try std.testing.expectEqualStrings("bester", p.lsp_ask.wait.?.arg.slice()); + // Esc from the field asks nothing. + p.lsp_ask.wait = null; + for (" lr") |c| p.update(.{ .key = .{ .cp = c } }); + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expectEqual(TagState.Kind.rest, s.kind); + try std.testing.expect(p.lsp_ask.wait == null); +} -- cgit v1.3 From b40ce1fcea232b99f28462c54cffc9fdd78abbad Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 24 Nov 2026 23:01:19 -0300 Subject: Prompt: a pipe prompt runs a known filter live, a run a selection (walk UI, pick-ui SPEC.md §7.4, item 4 of line E): `| A-| ! A-! $` from a body run the command as typed at each key when its first word is a known filter (`sort uniq tr cut sed awk jq column fmt fold rev head tail wc grep nl tac cat`), else the count says ` isn't a known filter · C-p runs it` and C-p runs it live all the same; the live run is a pipe request of its own, off the loop (Pipe.preview, out with the host as `wait` is; a later key's supersedes it, its answer then no one's), its command framed so that each selection's run says its stdout, its stderr and its status (Pipe.framed: sh, the runner's all-or-nothing answer kept as it is); counted `2 lines → 2 · exit 0`, `2 runs · 1 ok · 1 exit 2 `, `keeps 4 of 6` (`$`), `⋯` while it runs; the outputs drawn in the body as ghost lines under the lines they replace (Prompt.ghosts, renderBody's last step: the replaced lines on the diff's deleted ground, each output on the added ground, `!`'s before its selection, `A-!`'s after, the rows below pushed down; drawn, never written: R3), `A-|`'s runs a band step, each `#1 exit 0` and its output; Enter over runs that failed is refused once (` — ⏎ again applies the 1 that worked`), again applies what the live run made, the selections whose runs failed left as they were (Pipe.applyLive: pipeResponse's apply split out, a run's status its verdict), and nothing when every run failed (said, the prompt open); a command not run live, and `A-|` (its point is what it does), runs on Enter as before, one request; wire 39; THE FAULTS THE 40,000-SEED FUZZ MET (each in no code of this item, each a damaged dump's): Core.PendingWrite's `off` past its bytes (dropPendingWrite's count below zero), now a `.place`, the total saturating; the prompt histories' lines undefined past a damaged count (walk.hash read a length of 0xAAAA), now empty by default; TEST FIRST: Prompt.zig "a pipe prompt runs a known filter live, a run a selection ..." and "a live run's framing says each run's output, stderr and status in a real shell" (shell-test); Pipe.zig's tests take the request the keys made last (a known filter ran live before Enter ran it); golden pipe (the count of the live run); core-test 1018/1185 (167 skipped: the framing test wants a shell), shell-test 1232/1235, pane-test 182/184, behaviour-test 274/277 (the failures A's, as on item 1), process-test A's six and none of mine, term-test 17/17, kitty-test 45/45; the fuzz at 40,000 join and 1,779 image seeds: pass; the soak, 5 clients: diverged 0, unequal 0 at rtt 30/80/207, quiet checks 590/0 484/0 700/0, the corpus 22 scenes the same, exit 0 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- abi/wire.zig | 4 +- core/Core.zig | 15 +- core/Pipe.zig | 122 ++++++++++++++-- core/Prompt.zig | 344 ++++++++++++++++++++++++++++++++++++++++++++- core/body_layer.zig | 3 + test/daemon.py | 2 +- test/snapshots/pipe.golden | 5 +- 7 files changed, 473 insertions(+), 22 deletions(-) diff --git a/abi/wire.zig b/abi/wire.zig index 0cb55a32..1480bc32 100644 --- a/abi/wire.zig +++ b/abi/wire.zig @@ -10,6 +10,8 @@ const pardes = @import("core"); const config = @import("pardes_options"); const build_info = @import("build_info"); +/// 39: a pipe prompt's `forced` (C-p) and `refused` (Enter once over runs +/// that failed) in a view's `TagState.prompt`; /// 38: a pane's recipe's selections (`Pane.recipe_sels`, `recipe_pri`) /// and the pane whose recipe a view's next sam prompt extends /// (`Prompt.chain`) in the dump and the digest; @@ -86,7 +88,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 = 38; +pub const version: u16 = 39; /// The terminal's build and the window's step alike (`semantics`). const family = switch (config.platform) { diff --git a/core/Core.zig b/core/Core.zig index e718149e..61d8c7e9 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -1399,7 +1399,8 @@ fn refillPendingWrites(p: *Pardes) void { /// may be handed to a different pane next frame. pub fn dropPendingWrite(p: *Pardes, id: usize) void { const pw = p.pending_write[id] orelse return; - p.pending_write_bytes -= pw.bytes.len - pw.off; + // (Saturating: a damaged image's total may say less than its parts.) + p.pending_write_bytes -|= pw.bytes.len - pw.off; p.gpa.free(pw.bytes); p.pending_write[id] = null; } @@ -2303,7 +2304,17 @@ pub fn appendPlacement(p: *Pardes, place: Placement) bool { return true; } -pub const PendingWrite = struct { bytes: []u8, off: usize = 0 }; +pub const PendingWrite = struct { + /// What is written held to the bytes (walk.zig `.place`): a damaged + /// image's past them freed a count below zero. + pub const replica = .{ .place = .{.{ "off", "lastOff" }} }; + bytes: []u8, + off: usize = 0, + + pub fn lastOff(pw: *const PendingWrite) usize { + return pw.bytes.len; + } +}; /// The session layouts `init` can put on screen. One name each, so choosing /// between them reads as a choice instead of a chain of ifs over four options. diff --git a/core/Pipe.zig b/core/Pipe.zig index 70d551d0..d0413c08 100644 --- a/core/Pipe.zig +++ b/core/Pipe.zig @@ -18,12 +18,17 @@ const Pipe = @This(); /// A pipe's run, an Edit's and its writes, out with the host: errands of /// the session that performs them, not a dump's (core/walk.zig). -pub const replica = .{ .authority = .{ "wait", "edit_run", "writes" } }; +pub const replica = .{ .authority = .{ "wait", "preview", "edit_run", "writes" } }; /// Bumped for every request, so a late answer to an older one is ignored. seq: u32 = 0, /// The request in flight, and what it needs to apply its answer. wait: ?PendingPipe = null, +/// A pipe prompt's live run (Prompt.zig, pick-ui SPEC §7.4): each +/// selection through the command as typed, each run's outcome its own +/// (`framed`), drawn as ghost lines and counted; Enter applies the ones +/// that worked from it. +preview: ?PendingPipe = null, /// An Edit waiting on its `<`, `|` and `>` commands, which share the ids. edit_run: ?*edit_cmd.Pending = null, /// What an Edit's `w` took, for the `edit_write` effect to write. @@ -31,6 +36,7 @@ writes: std.ArrayList(edit_cmd.Write) = .empty, pub fn deinit(pipe: *Pipe, gpa: std.mem.Allocator) void { if (pipe.wait) |*wait| wait.deinit(); + if (pipe.preview) |*running| running.deinit(); if (pipe.edit_run) |pending| pending.deinit(gpa); for (pipe.writes.items) |*w| w.deinit(gpa); pipe.writes.deinit(gpa); @@ -72,6 +78,12 @@ pub const PendingPipe = struct { explicit: bool, how: modal.Normal.PipeBehavior, nranges: u16, + /// A live run's: the command as typed, and once answered each run's + /// output, stderr and exit status (`framed`). + typed: []u8 = &.{}, + outs: [][]const u8 = &.{}, + errs: [][]const u8 = &.{}, + codes: []u8 = &.{}, pub fn deinit(wait: *PendingPipe) void { wait.arena.deinit(); @@ -105,6 +117,27 @@ pub fn submitPipe(p: *Pardes, id: usize) void { /// Pipe text `t` of pane `id` through `command`, `how` says: one run per /// selection, off the loop. pub fn submit(p: *Pardes, id: usize, t: *Text, how: modal.Normal.PipeBehavior, command: []const u8) void { + send(p, id, t, how, command, false); +} + +/// The same run, live under a pipe prompt (`preview`): its outcome per +/// selection, the text left alone. +pub fn live(p: *Pardes, id: usize, t: *Text, how: modal.Normal.PipeBehavior, command: []const u8) void { + send(p, id, t, how, command, true); +} + +/// The live run let go: its answer, when it comes, is no one's. +pub fn dropLive(p: *Pardes) void { + if (p.pipe.preview) |*old| old.deinit(); + p.pipe.preview = null; +} + +/// A live run's command: its stdout as it is, then its stderr and its exit +/// status after a record separator each, so that each selection's run says +/// how it went where the runner's answer is all or nothing (as `$` does). +const framed = "exec 3>&1; e=$( {{ (\n{s}\n) 1>&3; }} 2>&1 ); s=$?; printf '\\036%s\\036%s' \"$e\" \"$s\""; + +fn send(p: *Pardes, id: usize, t: *Text, how: modal.Normal.PipeBehavior, command: []const u8, preview: bool) void { const pane = p.panes[id] orelse return; if (t.what == .body) { const f = pane.file orelse return; @@ -130,15 +163,20 @@ pub fn submit(p: *Pardes, id: usize, t: *Text, how: modal.Normal.PipeBehavior, c // `$` wants a verdict per selection where the runner's is all or // nothing: the command runs in a subshell whose exit status becomes the // output, so the runner always succeeds and the answer says which kept - const command_copy = (if (how == .keep) + const command_copy = (if (preview) + std.fmt.allocPrint(arena, framed, .{command}) + else if (how == .keep) std.fmt.allocPrint(arena, "(\n{s}\n) >/dev/null; echo $?", .{command}) else arena.dupe(u8, command)) catch return arena_state.deinit(); + const typed: []u8 = if (preview) arena.dupe(u8, command) catch return arena_state.deinit() else &.{}; const cwd_copy = arena.dupe(u8, Pardes.paneDir(pane)) catch return arena_state.deinit(); p.pipe.seq +%= 1; - if (p.pipe.wait) |*old| old.deinit(); - p.pipe.wait = .{ + const slot = if (preview) &p.pipe.preview else &p.pipe.wait; + if (slot.*) |*old| old.deinit(); + slot.* = .{ + .typed = typed, .id = p.pipe.seq, .pane = .at(id), .serial = pane.serial, @@ -165,6 +203,9 @@ pub fn pipeRequest(pipe: *const Pipe, id: u32) ?selection_pipe.Request { if (pipe.wait) |*wait| { if (wait.id == id) return wait.request(); } + if (pipe.preview) |*live_run| { + if (live_run.id == id) return live_run.request(); + } if (pipe.edit_run) |pending| if (pending.id == id) return pending.request; return null; } @@ -248,6 +289,7 @@ pub fn pipeResponse( failure: ?selection_pipe.Failure, ) void { if (p.pipe.edit_run) |pending| if (pending.id == id) return edit_cmd.finish(p, success, outputs, failure); + if (p.pipe.preview) |*live_run| if (live_run.id == id) return answered(live_run, success, outputs, failure); // A SUPERSEDED OR UNKNOWN id is the one silence worth keeping: it is // the answer to a question nobody is still asking. if (p.pipe.wait == null or p.pipe.wait.?.id != id) return; @@ -256,6 +298,60 @@ pub fn pipeResponse( defer wait.deinit(); if (!success or outputs.len != wait.inputs.len) return pipeFailed(p, &wait, failure); + apply(p, &wait, outputs, null); +} + +/// A live run answered: each run's stdout, stderr and status from what +/// `framed` made of it; a run the runner itself failed (no shell, too +/// much output) says so, as each of them. +fn answered(live_run: *PendingPipe, success: bool, outputs: []const []const u8, failure: ?selection_pipe.Failure) void { + const a = live_run.arena.allocator(); + const n = live_run.inputs.len; + const outs = a.alloc([]const u8, n) catch return; + const errs = a.alloc([]const u8, n) catch return; + const codes = a.alloc(u8, n) catch return; + for (outs, errs, codes, 0..) |*out, *err, *code, i| { + out.* = ""; + err.* = ""; + code.* = 255; + if (!success or outputs.len != n) { + if (failure) |f| { + code.* = if (f.kind == .exit) f.code else 255; + err.* = a.dupe(u8, f.stderr) catch ""; + } + continue; + } + const o = outputs[i]; + const last = std.mem.lastIndexOfScalar(u8, o, 0x1e) orelse continue; + const mid = std.mem.lastIndexOfScalar(u8, o[0..last], 0x1e) orelse continue; + out.* = a.dupe(u8, o[0..mid]) catch return; + err.* = a.dupe(u8, o[mid + 1 .. last]) catch return; + code.* = std.fmt.parseInt(u8, std.mem.trim(u8, o[last + 1 ..], " \n"), 10) catch 255; + } + live_run.outs = outs; + live_run.errs = errs; + live_run.codes = codes; +} + +/// Enter in a pipe prompt whose live run answered for the text as it is: +/// the outputs of the runs that worked applied from it, the selections of +/// the ones that failed left as they are. False when it has nothing to +/// apply from (the caller runs the command). +pub fn applyLive(p: *Pardes, serial: u32, typed: []const u8) bool { + var live_run = p.pipe.preview orelse return false; + p.pipe.preview = null; + defer live_run.deinit(); + const pane = p.panes[live_run.pane.index()] orelse return false; + if (pane.serial != serial or live_run.codes.len == 0 or !std.mem.eql(u8, live_run.typed, typed)) return false; + if (pane.file == null or pane.file.?.revision != live_run.revision) return false; + apply(p, &live_run, live_run.outs, live_run.codes); + return true; +} + +/// `wait`'s outputs applied to the text it piped: each range's cut with its +/// output in place, `$`'s kept; with `codes`, a run that failed leaves its +/// range as it was (`$`: a run's status is its verdict). +fn apply(p: *Pardes, wait: *const PendingPipe, outputs: []const []const u8, codes: ?[]const u8) void { const pane = p.panes[wait.pane.index()] orelse return; if (pane.serial != wait.serial) return; @@ -282,7 +378,8 @@ pub fn pipeResponse( var m: usize = 0; var pri: ?usize = null; for (0..wait.nranges) |i| { - if (!std.mem.eql(u8, std.mem.trim(u8, outputs[i], " \n"), "0")) continue; + const kept_here = if (codes) |c| c[i] == 0 else std.mem.eql(u8, std.mem.trim(u8, outputs[i], " \n"), "0"); + if (!kept_here) continue; if (i == wait.primary) pri = m; kept[m] = wait.ranges[i]; m += 1; @@ -300,8 +397,9 @@ pub fn pipeResponse( // answer from elsewhere past them is said, the text left as it was. var said: [128]u8 = undefined; for (0..n) |i| { - const cut = pipeCut(&wait, content, i) orelse return; - const output = pipeOutput(&wait, outputs, content, i); + const cut = pipeCut(wait, content, i) orelse return; + const failed = if (codes) |c| c[if (wait.how.pipes()) i else 0] != 0 else false; + const output = if (failed) content[cut.lo..cut.hi] else pipeOutput(wait, outputs, content, i); if (output.len > selection_pipe.max_stdout_bytes) return p.setMessage(wait.pane, std.fmt.bufPrint(&said, "pipe: an output of {d} bytes, past {d}: the text is left as it was", .{ output.len, selection_pipe.max_stdout_bytes }) catch unreachable); // two numbers fit 128 total_output += output.len; // each under 1 MiB, at most max_selections of them @@ -332,12 +430,15 @@ pub fn pipeResponse( t.show(p.settings.tab); } +/// The pipe request the keys made last: a known filter typed in a body's +/// prompt runs live at each key before Enter runs it (Prompt.zig). fn nextPipeEffect(p: *Pardes) ?u32 { + var last: ?u32 = null; while (p.nextEffect()) |effect| switch (effect) { - .pipe => |request| return request.id, + .pipe => |asked| last = asked.id, else => {}, }; - return null; + return last; } test "selection pipe prompt submits exact request and Escape cancels" { @@ -369,7 +470,8 @@ test "selection pipe prompt submits exact request and Escape cancels" { p.update(.{ .key = .{ .cp = Key.escape } }); try std.testing.expect(pane.focus == .body and p.view().tag_state.kind == .rest); try std.testing.expectEqualSlices(u8, before, pane.file.?.content); - try std.testing.expect(nextPipeEffect(p) == null); + // `cat`, a known filter, ran live as it was typed: Esc drops it. + try std.testing.expect(p.pipe.preview == null); } test "| in a tag pipes the tag's own text, and undo there brings it back" { diff --git a/core/Prompt.zig b/core/Prompt.zig index 1c0b1d31..2f42443b 100644 --- a/core/Prompt.zig +++ b/core/Prompt.zig @@ -36,6 +36,7 @@ const Places = @import("Places.zig"); const Trail = @import("Trail.zig"); const colors = @import("colors.zig"); const Surface = @import("surface.zig").Surface; +const Cell = @import("surface.zig").Cell; const File = panes.File; const Pardes = pardes.Pardes; const Pane = panes.Pane; @@ -68,6 +69,10 @@ counted: u32 = std.math.maxInt(u32), /// The pane, by serial, whose sam prompt Enter took last with no key since: /// the next one extends its recipe (0: none). chain: u32 = 0, +/// A pipe's: Ctrl-p ran a command that is no known filter live; Enter was +/// refused once over runs that failed. +forced: bool = false, +refused: bool = false, /// The session's prompt histories: the lines Enter took, newest last. pub const History = struct { @@ -80,7 +85,9 @@ pub const Ring = struct { pub const replica = .{ .len = .{.{ "lines", "n" }} }; /// The lines a history keeps; past it the oldest goes. pub const max = 16; - lines: [max]Kind.Buf(Field.max) = undefined, + /// Empty, not undefined: a damaged image's count past the lines it + /// holds reads empty lines, never undefined bytes. + lines: [max]Kind.Buf(Field.max) = @splat(.{}), n: u8 = 0, /// `line` the newest, an older copy of it gone. @@ -224,6 +231,7 @@ pub fn open(p: *Pardes, pane: *Pane, op: Op) void { s.field.clear(); s.rows = .{}; s.prompt = .{ .op = op, .scope = scope, .chain = s.prompt.chain }; + if (behavior(op) != null) Pipe.dropLive(p); } /// A key the tag at rest takes (keys.handleKey): any but one that opens a @@ -263,8 +271,14 @@ pub fn key(p: *Pardes, k: Key) void { s.prompt.history = !s.prompt.history; return; } + // A command no known filter: Ctrl-p runs it live all the same. + if (ctrl and k.cp == 'p' and behavior(s.prompt.op) != null) { + s.prompt.forced = true; + return live(p, pane); + } if (!s.field.key(k)) return; s.prompt.recall = 0; + s.prompt.forced = false; live(p, pane); } @@ -275,6 +289,13 @@ pub fn key(p: *Pardes, k: Key) void { fn live(p: *Pardes, pane: *Pane) void { const s = &p.view().tag_state; const pat = s.field.text(); + if (behavior(s.prompt.op)) |how| { + // A pipe: run live per selection when it is a known filter (or + // Ctrl-p said so), off the loop; Enter is asked again. + s.prompt.refused = false; + if (pat.len == 0 or !(s.prompt.forced or pure(pat))) return Pipe.dropLive(p); + return Pipe.live(p, p.view().active, &pane.body, how, pat); + } if (mode(s.prompt.op) == null and !searches(s.prompt.op)) return; s.prompt.bad = pat.len > 0 and if (regexp.Regex.compile(pat)) |_| false else |_| true; if (s.prompt.bad) return; @@ -329,6 +350,7 @@ fn seekBack(p: *Pardes, pane: *Pane) void { fn commit(p: *Pardes, id: usize, pane: *Pane) void { const s = &p.view().tag_state; const op = s.prompt.op; + if (behavior(op) != null and refuses(p, id, pane)) return; const line = s.field.text(); // The field is the view's: what is kept of it is copied before rest. var kept: [Field.max]u8 = undefined; @@ -359,6 +381,11 @@ fn commit(p: *Pardes, id: usize, pane: *Pane) void { p.registers.put(p.gpa, '|', typed, 0, 1, true) catch |err| return p.reportError(.at(id), "prompt", err); // `! A-! $` apply, and end the recipe: no Edit line says them. if (op == .pipe or op == .pipe_to) link(p, pane, op, typed) else s.prompt.chain = 0; + // What the live run made, applied (the runs that failed leaving + // their selections); else, or `A-|` (its point is what it does), + // the command run now. + if (op != .pipe_to and Pipe.applyLive(p, pane.serial, typed)) return; + Pipe.dropLive(p); return Pipe.submit(p, id, &pane.body, how, typed); } } @@ -403,6 +430,48 @@ fn asList(p: *Pardes, id: usize, pane: *Pane) void { panes.Query.open(p, id, .text, typed, true); } +/// The filters a pipe prompt runs live as it is typed: commands that +/// only read their input and write their output (SPEC §7.4). +const filters = [_][]const u8{ "sort", "uniq", "tr", "cut", "sed", "awk", "jq", "column", "fmt", "fold", "rev", "head", "tail", "wc", "grep", "nl", "tac", "cat" }; + +fn pure(line: []const u8) bool { + const name = commandName(line); + for (filters) |f| if (std.mem.eql(u8, f, name)) return true; + return false; +} + +fn commandName(line: []const u8) []const u8 { + var words = std.mem.tokenizeAny(u8, line, " \t"); + return words.next() orelse ""; +} + +/// The pipe prompt's live run, answered, for its field and `pane`'s text +/// as they are. +fn answered(p: *const Pardes, pane: *const Pane, line: []const u8) ?*const Pipe.PendingPipe { + const live_run = if (p.pipe.preview) |*l| l else return null; + if (live_run.serial != pane.serial or live_run.codes.len == 0 or !std.mem.eql(u8, live_run.typed, line)) return null; + if (pane.file == null or pane.file.?.revision != live_run.revision) return null; + return live_run; +} + +/// Enter over runs that failed: refused once, the count saying what a +/// second Enter applies; refused for good when every run failed. +fn refuses(p: *Pardes, id: usize, pane: *Pane) bool { + const s = &p.view().tag_state; + if (s.prompt.op == .keep_pipe or s.prompt.op == .pipe_to) return false; + const live_run = answered(p, pane, s.field.text()) orelse return false; + var failed: usize = 0; + for (live_run.codes) |c| failed += @intFromBool(c != 0); + if (failed == 0) return false; + if (failed == live_run.codes.len) { + p.setMessage(.at(id), "every run failed: nothing to apply"); + return true; + } + if (s.prompt.refused) return false; + s.prompt.refused = true; + return true; +} + /// Esc: the prompt goes and the body is as it was before it. fn cancel(p: *Pardes, pane: *Pane) void { const op = p.view().tag_state.prompt.op; @@ -413,6 +482,7 @@ fn cancel(p: *Pardes, pane: *Pane) void { /// The live effect of prompt `op` on `pane`'s body taken back. fn undo(p: *Pardes, pane: *Pane, op: Op) void { + if (behavior(op) != null) Pipe.dropLive(p); if (mode(op)) |m| _ = normal.applySelRegex(p, pane, &pane.body, "", m); pane.nsel_snap = 0; if (!searches(op)) return; @@ -761,6 +831,87 @@ fn plainWord(w: *std.Io.Writer, op: Op, line: []const u8) !?[]const u8 { return if (op == .search or op == .search_back) "Look" else "Exec"; } +/// A pipe prompt's live run in pane `pane`'s body, its rows painted in `s` +/// (joinBody's): each replaced selection's lines on the diff's deleted +/// ground, its run's output after them as ghost lines on the added ground +/// (`!` before them, `A-!` after, the text kept), the rows below pushed +/// down and the last ones off the view. Drawn, never written (the +/// coordinator's R3); a run that failed shows nothing. +pub fn ghosts(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, r: pardes.Rect, body_h: u16) !void { + const ts = &p.view().tag_state; + if (ts.kind != .prompt or ts.host != pane.serial) return; + const how = behavior(ts.prompt.op) orelse return; + if (how == .ignore or how == .keep) return; + const live_run = answered(p, pane, ts.field.text()) orelse return; + const f = &pane.file.?; + const tab = p.settings.tab; + const index = try File.lineIndex(p.gpa, f); + const y0 = p.bodyTop(pane, r); + const rows: usize = @min(body_h, s.rows -| y0); + const first: usize = pane.context_rows; + if (rows <= first) return; + const w: usize = s.cols; + const old = try arena.dupe(Cell, s.cells[(y0 + first) * w .. (y0 + rows) * w]); + const grounds = colors.Grounds.of(p.theme()); + const ink = p.theme().fg orelse p.theme().tag_fg; + const x0 = r.x + config.GUTTER + File.gutterWidth(pane); + const width = r.w -| (x0 - r.x); + const ranges = live_run.ranges[0..live_run.nranges]; + var out: usize = first; + var k: usize = 0; + var vr: usize = first; + while (vr < rows and out < rows) : (vr += 1) { + const line: usize = @intCast(@max(0, pane.wrapAt(tab, @intCast(vr)).line)); + const opens = vr == first or pane.wrapAt(tab, @intCast(vr - 1)).line != line; + const closes = vr + 1 >= rows or pane.wrapAt(tab, @intCast(vr + 1)).line != line; + while (k < ranges.len and lineAt(index, @max(ranges[k].anchor, ranges[k].head) -| 1) < line) k += 1; + // `!`: its output before the selection's first line. + var j = k; + if (how == .insert and opens) while (j < ranges.len and lineAt(index, @min(ranges[j].anchor, ranges[j].head)) == line) : (j += 1) { + out = ghostRows(s, live_run, j, out, rows, y0, x0, width, grounds.add.row, ink); + }; + if (out >= rows) break; + @memcpy(s.cells[(y0 + out) * w ..][0..w], old[(vr - first) * w ..][0..w]); + j = k; + while (j < ranges.len and lineAt(index, @min(ranges[j].anchor, ranges[j].head)) <= line) : (j += 1) { + if (how == .replace and outcome(live_run, j) == 0) s.tint(x0, @intCast(y0 + out), width, grounds.del.row, null); + } + out += 1; + // `|` and `A-!`: after the selection's last line. + if (how != .insert and closes) while (k < ranges.len and lineAt(index, @max(ranges[k].anchor, ranges[k].head) -| 1) == line) : (k += 1) { + out = ghostRows(s, live_run, k, out, rows, y0, x0, width, grounds.add.row, ink); + }; + } + // What was pushed past the view leaves blank rows behind it, none. +} + +fn lineAt(index: []const usize, at: usize) usize { + return Places.lineOf(index, at); +} + +/// Run `i`'s exit status (`!` and `A-!` run once for them all). +fn outcome(live_run: *const Pipe.PendingPipe, i: usize) u8 { + return live_run.codes[if (live_run.how.pipes()) i else 0]; +} + +/// Range `i`'s output as ghost rows from body row `out`, the rows it +/// reaches; none for a run that failed. +fn ghostRows(s: *Surface, live_run: *const Pipe.PendingPipe, i: usize, out_: usize, rows: usize, y0: usize, x0: u16, width: u16, ground: [3]u8, ink: [3]u8) usize { + if (outcome(live_run, i) != 0) return out_; + var out = out_; + const text = live_run.outs[if (live_run.how.pipes()) i else 0]; + var lines = std.mem.splitScalar(u8, if (std.mem.endsWith(u8, text, "\n")) text[0 .. text.len - 1] else text, '\n'); + while (lines.next()) |l| { + if (out >= rows) break; + const y: u16 = @intCast(y0 + out); + s.fill(0, y, @intCast(s.cols), 1, .{}); + s.fill(x0, y, width, 1, .{ .bg = .{ .rgb = ground } }); + _ = s.print(x0, y, width, l, .{ .fg = .{ .rgb = ink }, .bg = .{ .rgb = ground } }); + out += 1; + } + return out; +} + /// The x of the blank after pane `pane`'s line numbers. fn gutterX(pane: *const Pane, r: pardes.Rect) u16 { return r.x + config.GUTTER + (File.gutterWidth(pane) -| File.laneCells(pane) -| pane.layers.heat -| 1); @@ -869,6 +1020,8 @@ pub fn head(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) !TagState.Head { try text.appendSlice(arena, " "); try styled(arena, &text, &spans, regexMessage(line), .err); try text.print(arena, " · the {d} from before shown, dimmed", .{@as(usize, pane.body.nsel) + 1}); + } else if (behavior(pr.op) != null) { + try pipeCount(p, arena, &text, &spans, pane, pr, line); } else try count(arena, &text, pane, pr); } try text.appendSlice(arena, " "); @@ -911,6 +1064,43 @@ fn count(arena: std.mem.Allocator, text: *std.ArrayList(u8), pane: *Pane, pr: *c } } +/// A pipe prompt's count: `6 lines → 5 · exit 0`, `6 runs · 5 ok · 1 exit 2 +/// `, `keeps 4 of 6`, `⋯` while it runs, or why +/// it does not run live. +fn pipeCount(p: *const Pardes, arena: std.mem.Allocator, text: *std.ArrayList(u8), spans: *std.ArrayList(TagState.Span), pane: *const Pane, pr: *const Prompt, line: []const u8) !void { + if (!pr.forced and !pure(line)) { + try text.appendSlice(arena, " "); + try styled(arena, text, spans, commandName(line), .err); + return text.appendSlice(arena, " isn't a known filter · C-p runs it"); + } + const live_run = answered(p, pane, line) orelse return text.appendSlice(arena, " ⋯"); + const n = live_run.codes.len; + var ok: usize = 0; + var bad: ?usize = null; + for (live_run.codes, 0..) |c, i| { + if (c == 0) ok += 1 else if (bad == null) bad = i; + } + if (pr.op == .keep_pipe) return text.print(arena, " keeps {d} of {d}", .{ ok, n }); + if (bad) |i| { + const err = live_run.errs[i]; + try text.print(arena, " {d} run{s} · {d} ok · {d} exit {d} ", .{ n, plural(n), ok, n - ok, live_run.codes[i] }); + try styled(arena, text, spans, err[0 .. std.mem.indexOfScalar(u8, err, '\n') orelse err.len], .err); + if (pr.refused and ok > 0) try text.print(arena, " — ⏎ again applies the {d} that worked", .{ok}); + return; + } + if (pr.op == .pipe_to) return text.print(arena, " {d} run{s} · output below, the text stays", .{ n, plural(n) }); + var in: usize = 0; + for (live_run.inputs) |input| in += lineCount(input); + var out: usize = 0; + for (live_run.outs) |o| out += lineCount(o); + try text.print(arena, " {d} line{s} → {d} · exit 0", .{ in, plural(in), out }); +} + +fn lineCount(s: []const u8) usize { + if (s.len == 0) return 0; + return std.mem.count(u8, s, "\n") + @intFromBool(s[s.len - 1] != '\n'); +} + fn plural(n: usize) []const u8 { return if (n == 1) "" else "s"; } @@ -919,7 +1109,21 @@ fn plural(n: usize) []const u8 { /// lines the field is in, eleven at most. pub fn takes(p: *Pardes) u16 { const s = &p.view().tag_state; + if (s.prompt.op == .pipe_to) if (p.panes[TagState.hostOf(p) orelse return 0]) |pane| if (answered(p, pane, s.field.text())) |l| + return @max(runRows(l), if (s.prompt.history) historyRows(p) else 0); if (!s.prompt.history) return 0; + return historyRows(p); +} + +/// `A-|`'s runs as rows: each `#1 exit 0`, then its output's lines. +fn runRows(l: *const Pipe.PendingPipe) u16 { + var n: usize = 0; + for (l.outs) |o| n += 1 + lineCount(o); + return @intCast(@min(Band.Cursor.shown, n)); +} + +fn historyRows(p: *Pardes) u16 { + const s = &p.view().tag_state; var n: u16 = 0; const r = ring(p, s.prompt.op); for (r.lines[0..r.n]) |l| { @@ -932,7 +1136,30 @@ pub fn takes(p: *Pardes) u16 { /// holding the field, the one Up recalled on. pub fn steps(p: *Pardes, arena: std.mem.Allocator, out: *[Band.max_steps]Band.Step) ![]Band.Step { const s = &p.view().tag_state; - if (!s.prompt.history) return out[0..0]; + var made: usize = 0; + if (s.prompt.op == .pipe_to) if (p.panes[TagState.hostOf(p) orelse return out[0..0]]) |pane| if (answered(p, pane, s.field.text())) |l| { + var rows: std.ArrayList(Band.Row) = .empty; + for (l.outs, l.codes, 0..) |o, c, i| { + if (rows.items.len >= Band.Cursor.shown) break; + const said = try std.fmt.allocPrint(arena, "#{d} exit {d}", .{ i + 1, c }); + try rows.append(arena, .{ .text = said, .key = @intCast(said.len) }); + var lines = std.mem.splitScalar(u8, if (c == 0) o else l.errs[i], '\n'); + while (lines.next()) |line| { + if (rows.items.len >= Band.Cursor.shown) break; + if (line.len > 0) try rows.append(arena, .{ .text = line }); + } + } + out[made] = .{ .rows = rows.items, .doc = true }; + made += 1; + }; + if (!s.prompt.history) return out[0..made]; + return out[0 .. made + try historyStep(p, arena, &out[made])]; +} + +/// The history step (Ctrl-r): its lines newest first, those holding the +/// field, the one Up recalled on. +fn historyStep(p: *Pardes, arena: std.mem.Allocator, out: *Band.Step) !usize { + const s = &p.view().tag_state; const r = ring(p, s.prompt.op); var rows: std.ArrayList(Band.Row) = .empty; const q = s.field.text(); @@ -943,8 +1170,8 @@ pub fn steps(p: *Pardes, arena: std.mem.Allocator, out: *[Band.max_steps]Band.St try rows.append(arena, .{ .text = l, .on = back == s.prompt.recall, .index = back }); } if (rows.items.len == 0) try rows.append(arena, .{ .text = if (r.n == 0) "no history yet" else "no line holds it", .dim = true }); - out[0] = .{ .rows = rows.items }; - return out[0..1]; + out.* = .{ .rows = rows.items }; + return 1; } fn typeKeys(p: *Pardes, keys: []const u8) void { @@ -1025,7 +1252,7 @@ test "Enter keeps what s found, the pattern in / and in the history Up brings ba typeKeys(p, "|"); try std.testing.expectEqual(Pane.Prompt.none, pane.prompt); p.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); - try std.testing.expect(has(try tagOf(p), " | tr a-z A-Z = Exec Edit |tr a-z A-Z ⏎ replace")); + try std.testing.expect(has(try tagOf(p), " | tr a-z A-Z = Exec Edit |tr a-z A-Z ⋯ ⏎ replace")); p.update(.{ .key = .{ .cp = Key.enter } }); try std.testing.expectEqualStrings("tr a-z A-Z", p.registers.value('|', 0).?); var asked: ?u32 = null; @@ -1035,10 +1262,10 @@ test "Enter keeps what s found, the pattern in / and in the history Up brings ba const request = p.pipe.pipeRequest(asked orelse return error.MissingPipeEffect).?; try std.testing.expectEqualStrings("tr a-z A-Z", request.command); try std.testing.expectEqualSlices(u8, "self.b", request.inputs[0]); - // Esc in a pipe's prompt runs nothing. + // Esc in a pipe's prompt applies nothing: the live run dropped. typeKeys(p, "|cat"); p.update(.{ .key = .{ .cp = Key.escape } }); - while (p.nextEffect()) |effect| try std.testing.expect(effect != .pipe); + try std.testing.expect(p.pipe.preview == null); } const dirty = "dirty one\nclean\ndirty two dirty\nclean\ndirty three\ndirty four dirty\nclean\ndirty five\n"; @@ -1181,3 +1408,106 @@ test "sam prompts one after another make one recipe word, the Edit line it is; a Trail.execStep(p, 0, 0); try std.testing.expect(p.pipe.edit_run != null); } + +/// The pipe request the last key made, its id. +fn lastPipe(p: *Pardes) ?u32 { + var id: ?u32 = null; + while (p.nextEffect()) |effect| if (effect == .pipe) { + id = effect.pipe.id; + }; + return id; +} + +test "a pipe prompt runs a known filter live, a run a selection: the outputs ghost lines under the lines they replace, counted; one no filter waits for C-p; Enter over runs that failed is refused once, then applies the ones that worked; when every run failed nothing" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 200, .rows = 30 }); + defer p.deinit(); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + while (p.nextEffect()) |_| {} + const pane = try p.setTestFile("b\na\nc\n"); + typeKeys(p, "%s[ab]"); + p.update(.{ .key = .{ .cp = Key.enter } }); + typeKeys(p, "|"); + p.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); + try std.testing.expect(has(try tagOf(p), " | tr a-z A-Z = Exec Edit |tr a-z A-Z ⋯ ⏎ replace")); + const first = lastPipe(p) orelse return error.MissingLiveRun; + const asked = p.pipe.pipeRequest(first).?; + try std.testing.expectEqual(@as(usize, 2), asked.inputs.len); + try std.testing.expect(has(asked.command, "tr a-z A-Z") and has(asked.command, "\\036")); + p.update(.{ .pipe_resp = .{ .id = first, .success = true, .outputs = &.{ "B\x1e\x1e0", "A\x1e\x1e0" } } }); + try std.testing.expect(has(try tagOf(p), " 2 lines → 2 · exit 0 ⏎ replace")); + // The body: each output a ghost line under the line it replaces, the + // rows below pushed down; the text as it was. + p.sync(); + const s = try p.render(frame.allocator()); + const r = p.view().rects[0]; + const x = r.x + config.GUTTER + File.gutterWidth(pane); + const y = p.bodyTop(pane, r); + for ([_][]const u8{ "b", "B", "a", "A", "c" }, 0..) |want, row| try std.testing.expectEqualStrings(want, s.at(x, y + @as(u16, @intCast(row))).grapheme()); + try std.testing.expectEqual(pardes.Color{ .rgb = colors.Grounds.of(p.theme()).del.row }, s.at(x, y).style.bg); + try std.testing.expectEqual(pardes.Color{ .rgb = colors.Grounds.of(p.theme()).add.row }, s.at(x, y + 1).style.bg); + try std.testing.expectEqualStrings("b\na\nc\n", pane.file.?.content); + // Enter: what the live run made, applied. + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expectEqualStrings("B\nA\nc\n", pane.file.?.content); + try std.testing.expect(lastPipe(p) == null); + // No known filter: not run until C-p. + typeKeys(p, "|"); + p.update(.{ .key = .{ .cp = 'r', .text = "rot13" } }); + try std.testing.expect(has(try tagOf(p), " rot13 isn't a known filter · C-p runs it")); + try std.testing.expect(lastPipe(p) == null); + p.update(.{ .key = .{ .cp = 'p', .ctrl = true } }); + const second = lastPipe(p) orelse return error.MissingLiveRun; + p.update(.{ .pipe_resp = .{ .id = second, .success = true, .outputs = &.{ "\x1eoops: no\x1e2", "X\x1e\x1e0" } } }); + try std.testing.expect(has(try tagOf(p), " 2 runs · 1 ok · 1 exit 2 oops: no ")); + // Enter refused once, said; again, the one that worked applied. + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expectEqual(TagState.Kind.prompt, p.view().tag_state.kind); + try std.testing.expect(has(try tagOf(p), "oops: no — ⏎ again applies the 1 that worked")); + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expectEqual(TagState.Kind.rest, p.view().tag_state.kind); + try std.testing.expectEqualStrings("B\nX\nc\n", pane.file.?.content); + // Every run failed: Enter applies nothing, and says so. + typeKeys(p, "|sort"); + const third = lastPipe(p) orelse return error.MissingLiveRun; + p.update(.{ .pipe_resp = .{ .id = third, .success = true, .outputs = &.{ "\x1e\x1e1", "\x1e\x1e1" } } }); + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expectEqual(TagState.Kind.prompt, p.view().tag_state.kind); + try std.testing.expect(has(pane.msg[0..pane.msg_len], "every run failed")); + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expectEqualStrings("B\nX\nc\n", pane.file.?.content); + try std.testing.expect(p.pipe.preview == null); +} + +test "a live run's framing says each run's output, stderr and status in a real shell" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 30 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + _ = try p.setTestFile("one\ntwo\n"); + typeKeys(p, "%s\\w+"); + p.update(.{ .key = .{ .cp = Key.enter } }); + typeKeys(p, "|"); + p.update(.{ .key = .{ .cp = 'g', .text = "grep o" } }); + p.update(.{ .key = .{ .cp = 'p', .ctrl = true } }); + const id = lastPipe(p) orelse return error.MissingLiveRun; + const job = try @import("selection_pipe.zig").Job.copy(std.testing.allocator, p.pipe.pipeRequest(id).?); + defer job.deinit(std.testing.allocator); + var response = @import("selection_pipe.zig").runJob(std.testing.allocator, std.testing.io, job); + defer response.deinit(std.testing.allocator); + try std.testing.expect(response.success); + p.update(.{ .pipe_resp = .{ .id = id, .success = true, .outputs = response.outputs } }); + const live_run = p.pipe.preview.?; + try std.testing.expectEqualSlices(u8, &.{ 0, 0 }, live_run.codes); + try std.testing.expectEqualStrings("one\n", live_run.outs[0]); + p.update(.{ .key = .{ .cp = Key.backspace } }); + p.update(.{ .key = .{ .cp = 'x', .text = "x" } }); + const again = lastPipe(p) orelse return error.MissingLiveRun; + const job2 = try @import("selection_pipe.zig").Job.copy(std.testing.allocator, p.pipe.pipeRequest(again).?); + defer job2.deinit(std.testing.allocator); + var response2 = @import("selection_pipe.zig").runJob(std.testing.allocator, std.testing.io, job2); + defer response2.deinit(std.testing.allocator); + p.update(.{ .pipe_resp = .{ .id = again, .success = true, .outputs = response2.outputs } }); + // `grep x` finds nothing: exit 1 for both, an empty stderr. + try std.testing.expectEqualSlices(u8, &.{ 1, 1 }, p.pipe.preview.?.codes); +} diff --git a/core/body_layer.zig b/core/body_layer.zig index de822674..eded5439 100644 --- a/core/body_layer.zig +++ b/core/body_layer.zig @@ -542,6 +542,9 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane // A replica's predicted echo, over what its authority's screen shows. if (p.echo) |e| if (pane.isTerminal()) e.paint(p, s, pane, id, tx, tw, body_y, body_h, active); + // A pipe prompt's live run, as ghost lines over what is painted + // (Prompt.zig). + if (pane.file != null) try pardes.Prompt.ghosts(p, s, arena, pane, r, body_h); if (rail) |bar| if (bar.rect.h > 0) { // The rail covers the notice bands too: nothing else paints those // two gutter columns, so a gap there keeps the frame-wide border diff --git a/test/daemon.py b/test/daemon.py index bb159424..b71ec17d 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 = 38 + WIRE = 39 def __init__(self, path, timeout=10): self.path, self.timeout = path, timeout diff --git a/test/snapshots/pipe.golden b/test/snapshots/pipe.golden index 04921c77..4c156cc8 100644 --- a/test/snapshots/pipe.golden +++ b/test/snapshots/pipe.golden @@ -1,12 +1,15 @@ == snap prompt grid=180x13 cursor=49,2 | Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config History Debug Exit | New Term Find Grep Joincol Delcol -|^ /tmp/pardes-snap/pipe/cwd/pipe.txt | tr a-z A-Z = Exec Edit |tr a-z A-Z ⏎ replace · C-r history · esc +|^ /tmp/pardes-snap/pipe/cwd/pipe.txt | tr a-z A-Z = Exec Edit |tr a-z A-Z 1 line → 1 · exit 0 ⏎ replace · C-r history · esc | 1 alpha beta +| ALPHA BETA | 2 gamma delta == snap filtered grid=180x13 cursor=17,3 |2: *Edit |tr a-z A-Z › /tmp/pardes-snap/pipe/cwd/pipe.txt Save Term Collapse Follow Del |3: 1 ALPHA BETA +|4: 2 gamma delta +|5: == snap undone grid=180x13 cursor=17,3 |2: Edit |tr a-z A-Z › /tmp/pardes-snap/pipe/cwd/pipe.txt Save Term Collapse Follow Del |3: 1 alpha beta -- cgit v1.3 From d2984ed50f72468b1c7304f4b354a2a5f242e2ca Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 24 Nov 2026 23:05:03 -0300 Subject: perf: pardes-perf --walkf measures line F's hot paths in a 2,000-line file, each a step and its frame (a Down in the registers' level unrolled, a frame with `]`'s targets painted against one at rest, a Down in the themes picker), and the painted targets look for the spec's six alone (`f p T c g d`, pick-ui SPEC §4.4: the tree objects function, test, comment; a type's, an argument's, an entry's and an element's queries no longer run on the frame): a frame with `]` painted 18.1M instructions in Debug before, 11.7M after, against 1.17M at rest (walk UI line F, the brief's measures; the ReleaseFast counts in the report) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- core/body_layer.zig | 6 ++--- test/perf.zig | 77 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 79 insertions(+), 4 deletions(-) diff --git a/core/body_layer.zig b/core/body_layer.zig index 13c24f97..3736e467 100644 --- a/core/body_layer.zig +++ b/core/body_layer.zig @@ -558,8 +558,8 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane /// Painted targets (SPEC §4.4), while a motion root's level shows in this /// body's tag: each of its keys at the line it would go to, in the gutter /// (`g e t b .` for `g`; for `]` the next and for `[` the previous -/// function, paragraph, test, comment, change, diagnostic, type, argument: -/// `f p T c g d t a`); browsing `m a` or `m i` unrolled, the brackets' +/// function, paragraph, test, comment, change and diagnostic: `f p T c g +/// d`, the spec's, each tree object a query of the rows shown); browsing `m a` or `m i` unrolled, the brackets' /// region around the caret tinted. Only the rows shown are looked at: a /// target off them is not painted (the tag's arrows, SPEC §15, are not /// built). At rest it costs one test of the view's tag state. @@ -778,7 +778,7 @@ fn targetLine(p: *Pardes, pane: *Pane, f: *panes.File.State, role: modal.Normal. if (forward) return if (a < hits.len) lineOf(f, hits[a].start) else null; return if (a > 0) lineOf(f, hits[a - 1].start) else null; }, - inline .goto_function, .goto_class, .goto_parameter, .goto_comment, .goto_test, .goto_entry, .goto_xml_element => |r| { + inline .goto_function, .goto_comment, .goto_test => |r| { // The tree as the motion reads it, made once a revision; with // the Changes layer's lines in the buffer its offsets are not the // buffer's: not painted then. diff --git a/test/perf.zig b/test/perf.zig index 16066e9f..9308bbcd 100644 --- a/test/perf.zig +++ b/test/perf.zig @@ -396,6 +396,8 @@ const Options = struct { search: bool = false, /// A picker's key and frame (`measurePick`). pick: bool = false, + /// The walk UI's line F: registers, painted targets, themes (`measureWalkF`). + walkf: 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). @@ -412,7 +414,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, pick, @"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, walkf, @"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, @@ -421,6 +423,7 @@ const Options = struct { .mini => opts.mini = true, .search => opts.search = true, .pick => opts.pick = true, + .walkf => opts.walkf = true, .@"self-test" => opts.self_test = true, else => { i += 1; @@ -484,6 +487,7 @@ pub fn main(init: std.process.Init) !void { 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.walkf) return measureWalkF(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 @@ -1903,6 +1907,77 @@ fn measurePick(io: std.Io) !void { if (!std.mem.endsWith(u8, landing.file.?.path, ".zig") or std.mem.indexOf(u8, landing.file.?.path, "pickme_") == null) return error.NoPreview; } +/// `--walkf`: line F's hot paths in a 2,000-line file, each a step and +/// the frame that draws it, its instructions counted: a key in the +/// registers' level unrolled (Down, its value step read again); a frame +/// with `]`'s targets painted against one at rest; a cursor move in the +/// themes picker (the window wearing the next theme). +fn measureWalkF(io: std.Io) !void { + var random: [12]u8 = undefined; + io.random(&random); + const dir = try std.fmt.allocPrint(gpa, "/tmp/pardes-walkf-{x}", .{random}); + defer gpa.free(dir); + try std.Io.Dir.createDirAbsolute(io, dir, .default_dir); + defer std.Io.Dir.cwd().deleteTree(io, dir) catch {}; + const path = try std.fmt.allocPrint(gpa, "{s}/walkf.zig", .{dir}); + defer gpa.free(path); + var body: std.ArrayList(u8) = .empty; + defer body.deinit(gpa); + for (0..250) |i| try body.print(gpa, "/// The {d}th.\nfn f{d}(a: u32) u32 {{\n const b = a + {d};\n return b;\n}}\n\ntest \"f{d}\" {{\n}}\n", .{ i, i, i, i }); + try writeFile(path, body.items); + var counter: Instructions = try .open(); + defer counter.close(); + const core = try boot(); + defer core.deinit(); + core.settings.jumps = .walk; + pardes.look.lookAt(core, 0, path); + pump(core); + _ = filePane(core) orelse return error.OpenDidNotOpenFile; + for ("abcdefgh", 0..) |r, i| try core.registers.put(gpa, r, body.items[i * 40 ..][0..200], 0, 1, true); + try frame(core); + const Step = struct { + fn run(c: *pardes.Pardes, ev: pardes.Event, n: *Instructions, s: *Slowest) !void { + const was = n.read(); + const t0 = nowNs(); + c.update(ev); + try frame(c); + s.add(nowNs() -| t0, n.read() -| was, 0); + } + }; + const shown = struct { + fn wait(c: *pardes.Pardes) !void { + c.advance(c.clock.now_ns); + c.clock.now_ns = c.view().tag_state.due_ns; + try frame(c); + } + }; + // Registers: `"`, its level shown, unrolled; then Down over its rows. + core.update(.{ .key = .{ .cp = '"' } }); + try shown.wait(core); + core.update(.{ .key = .{ .cp = pardes.Key.down } }); + var regs: Slowest = .{}; + for (0..8) |_| try Step.run(core, .{ .key = .{ .cp = pardes.Key.down } }, &counter, ®s); + regs.report("registers Down + frame", "\"", 0); + core.update(.{ .key = .{ .cp = pardes.Key.escape } }); + // A frame at rest, then frames with `]`'s targets painted. + var rest: Slowest = .{}; + var painted: Slowest = .{}; + for (0..8) |_| try Step.run(core, .tick, &counter, &rest); + core.update(.{ .key = .{ .cp = ']' } }); + try shown.wait(core); + for (0..8) |_| try Step.run(core, .tick, &counter, &painted); + rest.report("tick + frame at rest", "", 0); + painted.report("tick + frame, ] painted", "]", 0); + core.update(.{ .key = .{ .cp = pardes.Key.escape } }); + // The themes picker: Down, the window wearing the next. + pardes.Pick.open(core, core.view().active, .themes, "", "", ""); + try frame(core); + var themes: Slowest = .{}; + for (0..8) |_| try Step.run(core, .{ .key = .{ .cp = pardes.Key.down } }, &counter, &themes); + themes.report("themes Down + frame", "", 0); + if (core.theme_preview == null) return error.NoThemePreview; +} + /// The longest of a scan's calls. const Slowest = struct { calls: usize = 0, -- cgit v1.3 From 8474b3a7c16cdac242f362144d100931f149ad6f Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 24 Nov 2026 23:36:49 -0300 Subject: Text.setRanges counts each range's rows on from the last one's, one pass over the text to the last range where a count from the top for each was a pass a range (walk UI, line E, for item 3's live s: "every key in a prompt draws its live effect in the same frame"): RUN (pardes-perf --search, ReleaseFast, a 1.08 MB file, `%s` then a pattern that finds 1024 ranges near the top): 442-451 million instructions, 25-27 ms a key and its frame; THE CAUSE: Text.zig setRanges put each range's two ends with modal.positionAt, whose row is lineAtOffset's count of every newline from the text's start (1024 ranges, two ends each, a pass each); THE FIX: the ranges are sorted and merged by then, so a Walked counter takes each end's row on from the last (positionAt's answer, from the top again for an end before the last); now 30-38 million, 1.6-2.3 ms, the no-match key (`qq`, a pass over the text) 50.8 million, 2.2-2.4 ms, `/` 1.5-2.1 million (9.7 million its first key); TEST FIRST: Text.zig "setRanges puts each range's ends where positionAt says, counting rows on from the last"; core-test 1019/1186 (167 skipped), shell-test 1233/1236, pane-test 182/184, behaviour-test 274/277, process-test A's six (the failures A's, as on item 1) Co-Authored-By: Claude Opus 5.5 --- core/Text.zig | 55 +++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 53 insertions(+), 2 deletions(-) diff --git a/core/Text.zig b/core/Text.zig index 37feb081..3cf65b74 100644 --- a/core/Text.zig +++ b/core/Text.zig @@ -315,11 +315,18 @@ pub fn setRanges(t: *Text, tab: u16, text: []const u8, in: []const modal.Selecti if (n > 1 and !t.reserveSels()) return; // no room: the primary alone t.sticky_col = st[pri]; var w: usize = 0; + // The ranges are in the text's order now: each end's row counted on + // from the last one's, one pass to the last range, where a count from + // the top for each was a pass a range (an `s` over a big text's 1024 + // ranges, 445 million instructions a key). + var walked: Walked = .{}; for (r[0..n], 0..) |x, idx| { if (idx == pri) continue; const c = rangeCells(text, x); - const cc = modal.positionAt(text, c.cur); - const ac = modal.positionAt(text, c.anc); + const first = walked.at(text, @min(c.cur, c.anc)); + const last = walked.at(text, @max(c.cur, c.anc)); + const cc = if (c.cur <= c.anc) first else last; + const ac = if (c.cur <= c.anc) last else first; t.sels[w] = .{ .row = @as(i32, @intCast(cc.row)), .col = @intCast(cc.col), @@ -332,6 +339,24 @@ pub fn setRanges(t: *Text, tab: u16, text: []const u8, in: []const modal.Selecti t.nsel = @intCast(w); } +/// Offsets' positions in a text, asked in order: the rows counted on from +/// the last asked (modal.positionAt's answer); one asked before it, from +/// the top. +const Walked = struct { + off: usize = 0, + row: usize = 0, + + fn at(w: *Walked, text: []const u8, off: usize) modal.Cursor { + const bounded = @min(off, text.len); + if (bounded < w.off) return modal.positionAt(text, bounded); + w.row += std.mem.count(u8, text[w.off..bounded], "\n"); + w.off = bounded; + const s = if (std.mem.lastIndexOfScalar(u8, text[0..bounded], '\n')) |nl| nl + 1 else 0; + const e = std.mem.indexOfScalarPos(u8, text, s, '\n') orelse text.len; + return .{ .row = w.row, .col = modal.graphemeStart(text[s..e], @min(bounded - s, e - s)) }; + } +}; + /// helix `scroll` without cursor sync (Ctrl-f/b, PgUp/PgDn, zj/zk): shift /// the view, then snap a fallen-out cursor to the near scrolloff edge, col 0 pub fn scrollViewMove(t: *Text, tab: u16, text: []const u8, range: modal.Selection, delta: i32) void { @@ -698,3 +723,29 @@ pub fn step(t: *Text, gpa: std.mem.Allocator, current: ?EditBuffer, back: bool) t.vsel = back_to.vsel; return back_to; } + +test "setRanges puts each range's ends where positionAt says, counting rows on from the last" { + const pardes = @import("root.zig"); + const p = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + const text = "ab\ncd ef\n\ngh ij kl\nmn\n"; + const t = &(try p.setTestFile(text)).body; + const in = [_]modal.Selection{ + .{ .anchor = 3, .head = 5 }, // cd + .{ .anchor = 8, .head = 6 }, // ef, backwards + .{ .anchor = 11, .head = 13 }, // gh + .{ .anchor = 14, .head = 16 }, // ij + .{ .anchor = 20, .head = 22 }, // mn + }; + t.setRanges(4, text, &in, &.{}, 0, true); + try std.testing.expectEqual(@as(u16, 4), t.nsel); + for (in[1..], t.sels[0..4]) |r, s| { + const c = rangeCells(text, r); + const cc = modal.positionAt(text, c.cur); + const ac = modal.positionAt(text, c.anc); + try std.testing.expectEqual(@as(i32, @intCast(cc.row)), s.row); + try std.testing.expectEqual(@as(i32, @intCast(cc.col)), s.col); + try std.testing.expectEqual(@as(i32, @intCast(ac.row)), s.arow); + try std.testing.expectEqual(@as(i32, @intCast(ac.col)), s.acol); + } +} -- cgit v1.3 From ffcdca15c7060929f98a90935c29254ea9c1c303 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 25 Nov 2026 00:11:07 -0300 Subject: docs: builtins-gui.json regenerated (zig build builtins-json -Dplatform=gui): Keys (line A's describe-key, SPC h k) was missing from the M1 base's gui listing, the one new failure of the gate walkF-g1's gui unit-test ('docs/typ/builtins-.json is what the registry says now'); the tui listing is unchanged (walk UI line F) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016Y9MNBFhdevVu48bvL9kCE --- docs/typ/builtins-gui.json | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/typ/builtins-gui.json b/docs/typ/builtins-gui.json index 28b824f9..a81fc107 100644 --- a/docs/typ/builtins-gui.json +++ b/docs/typ/builtins-gui.json @@ -59,6 +59,7 @@ {"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."}, -- cgit v1.3 From fc45a7c8ed3b279a803dd8daad81329920b0493e Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 25 Nov 2026 00:15:56 -0300 Subject: dump: a load refused after the core reads none of the namespace's opens again: they are what the load read, freed by the rollback, and their count may be the damaged one the load refused: a refused load's teardown (`p.fs.deinit` after `l.rollback()` in loadKnowing and loadImage) walked `opens[0..opens_len]` as the dump gave them; found by the 40,000-seed fuzz on the walk UI's merged tree M1 (xvnytwqm); RUN FIRST: fuzz.zig "a dump and an image cut ..." at join seed 31554: `panic: index out of bounds: index 255, len 64` (fs.zig:1029, Namespace.deinit, from dump.zig:402's errdefer: the dump's opens_len past the 64 slots, refused by walk.holdTo, then read that far by the teardown); and dump.zig's new test, a session with a script's open holding a half-written line (`pending`) whose load is refused after the core (a mount of the same name dialled elsewhere: error.MountConflict, dump.zig:432): `panic: double free` of the open's 9 bytes, the first free `l.rollback()` (dump.zig:401), the second Open.deinit through Namespace.deinit; THE CAUSE: the errdefer of both loaders tears the namespace down for what Pardes.create made (its log, its out, its mounts), and Namespace.deinit frees its opens too, which the load had read in place: the rollback's to free; THE FIX: the errdefer sets `p.fs.opens_len = 0` before `p.fs.deinit` (both loaders); a user could hit the double free with no damage at all: a Restore or a join of a dump taken while a script held an open with something in it (a half-written line, a frozen listing, a run's output) into a process started with a mount of the same name dialled elsewhere; the index past the slots only with a damaged or hostile dump; TESTS: dump.zig 'a load refused after the core frees what a script's open held once: the rollback's, not the namespace's' (fails before: double free), fuzz.zig checks join seed 31554 by name (fails before: index out of bounds); the fuzz at 40,000 join and 1,779 image seeds green in 158 s Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016Y9MNBFhdevVu48bvL9kCE --- core/dump.zig | 23 +++++++++++++++++++++++ core/fuzz.zig | 3 +++ 2 files changed, 26 insertions(+) diff --git a/core/dump.zig b/core/dump.zig index 683f043a..06a3eae5 100644 --- a/core/dump.zig +++ b/core/dump.zig @@ -399,6 +399,9 @@ fn loadKnowing(gpa: std.mem.Allocator, opts: Options, bytes: []const u8, notes: errdefer { if (notes) |n| n.appendSlice(gpa, l.notes.items) catch {}; l.rollback(); + // Its opens are what the load read: the rollback's, freed (and + // their count may be a damaged one, refused). + p.fs.opens_len = 0; p.fs.deinit(gpa); gpa.destroy(p); } @@ -475,6 +478,9 @@ fn loadImage(gpa: std.mem.Allocator, opts: Options, bytes: []const u8, notes: ?* errdefer { if (notes) |n| n.appendSlice(gpa, l.notes.items) catch {}; l.rollback(); + // Its opens are what the load read: the rollback's, freed (and + // their count may be a damaged one, refused). + p.fs.opens_len = 0; p.fs.deinit(gpa); gpa.destroy(p); } @@ -1417,3 +1423,20 @@ test "optional GPU addon reload generation survives a replica dump" { try std.testing.expectEqual(original.gen, restored.gen); try std.testing.expectEqual(walk.digest(Kind.Slot, &original), walk.digest(Kind.Slot, &restored)); } + +test "a load refused after the core frees what a script's open held once: the rollback's, not the namespace's" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .mounts = &.{.{ .name = "peer", .dial = "/tmp/peer.sock" }} }); + defer p.deinit(); + _ = try p.setTestFile("x\n"); + // A script's open of a file of command lines, its last line half + // written: bytes the load makes. + p.fs.opens[0] = .{ .node = 1, .what = .lines }; + try p.fs.opens[0].pending.appendSlice(gpa, "Look half"); + p.fs.opens_len = 1; + const bytes = try byteDump(p); + defer gpa.free(bytes); + // The mounts are read after the core: the same name dialled elsewhere + // refuses the load there. + try std.testing.expectError(error.MountConflict, load(gpa, .{ .mounts = &.{.{ .name = "peer", .dial = "/tmp/other.sock" }} }, bytes, null)); +} diff --git a/core/fuzz.zig b/core/fuzz.zig index c68c7810..dc3e8e07 100644 --- a/core/fuzz.zig +++ b/core/fuzz.zig @@ -790,6 +790,9 @@ test "a dump and an image cut, flipped and grown: refused or loaded, never a pan // 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); + // Join seed 31554: the namespace's opens_len past its 64 slots, refused, + // and the rollback's teardown of the namespace read that far. + try loadSeed(bytes, .join, 31554); 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); -- cgit v1.3