summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-24 23:01:19 -0300
committerGabriel Schneider <[email protected]>2026-11-24 23:01:19 -0300
commitb40ce1fcea232b99f28462c54cffc9fdd78abbad (patch)
tree56cf607744ab84b0516609909963351c14c1a32f
parent3da01ac676283c6d20ca6f2c0321b9dfe8cc59cd (diff)
downloadpardes-b40ce1fcea232b99f28462c54cffc9fdd78abbad.tar.gz
pardes-b40ce1fcea232b99f28462c54cffc9fdd78abbad.zip
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 `<cmd> 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 <its stderr's first line>`, `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
Co-Authored-By: Claude Opus 5.5 <[email protected]>
-rw-r--r--abi/wire.zig4
-rw-r--r--core/Core.zig15
-rw-r--r--core/Pipe.zig122
-rw-r--r--core/Prompt.zig344
-rw-r--r--core/body_layer.zig3
-rw-r--r--test/daemon.py2
-rw-r--r--test/snapshots/pipe.golden5
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
+/// <its stderr's first line>`, `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