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 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'abi/wire.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) { -- 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(-) (limited to 'abi/wire.zig') 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 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(-) (limited to 'abi/wire.zig') 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