//! The pipe inside the editor (`|`): the prompt, the request the core emits //! for the shell to run through selection_pipe.zig, and the atomic edit its //! answer makes. const std = @import("std"); const pardes = @import("root.zig"); const modal = @import("modal.zig"); const panes = @import("panes.zig"); const config = @import("config.zig"); const selection_pipe = @import("selection_pipe.zig"); const edit = @import("edit.zig"); const edit_cmd = @import("edit_cmd.zig"); const sam = @import("sam_edit.zig"); const Pane = panes.Pane; const Text = panes.Text; const Key = pardes.Key; const Pardes = pardes.Pardes; 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", "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. 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); } /// The tag-tail marker each behaviour arms with. One function so the prompt /// that is DRAWN and the command that is PARSED can never disagree. pub fn pipeMarker(how: modal.Normal.PipeBehavior) []const u8 { return switch (how) { .replace => config.pipe_marker, .ignore => config.pipe_marker_to, .insert => config.pipe_marker_insert, .append => config.pipe_marker_append, .keep => config.pipe_marker_keep, }; } pub const PendingPipe = struct { /// The digest's walk (core/walk.zig) of the ranges, as far as they go. pub const replica = .{ .len = .{.{ "ranges", "nranges" }} }; id: u32, pane: Pane.Id, serial: u32, /// The text piped: the pane's body or tag, or a header (`column` /// names which). what: Text.What, column: usize, /// What the answer is checked against before it is applied: a body's /// file revision, any other text's contents. revision: u32, sum: u64, /// What command, cwd and inputs are made in. arena: std.heap.ArenaAllocator, command: []u8, cwd: []u8, inputs: [][]const u8, ranges: [panes.Text.max_selections]modal.Selection, primary: u16, 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(); wait.* = undefined; } fn request(wait: *const PendingPipe) selection_pipe.Request { return .{ .id = wait.id, .command = wait.command, .cwd = wait.cwd, .inputs = wait.inputs, }; } }; /// The notice band's pipe prompt answered (a tag's text, a header's). pub fn submitPipe(p: *Pardes, id: usize) void { const pane = p.panes[id] orelse return; const t = panes.promptTarget(p, pane) orelse return; const how = switch (pane.prompt) { .pipe => |pipe| pipe, else => return, }; const armed = pane.promptText() orelse return; const marker = pipeMarker(how); if (!std.mem.startsWith(u8, armed, marker)) return; submit(p, id, t, how, armed[marker.len..]); } /// Pipe text `t` of pane `id` through `command`, `how` says: one run per /// selection, off the loop. pub fn submit(p: *Pardes, id: usize, t: *Text, how: modal.Normal.PipeBehavior, command: []const u8) void { 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; if (!panes.Output.fileTraits(f.output).saves) return; } const content = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(.at(id), "pipe", err); if (command.len == 0) return; var ranges: [panes.Text.max_selections]modal.Selection = undefined; const got = t.ranges(content, 0, &ranges); // `!`/`A-!` take no stdin and run ONCE โ€” see `PendingPipe.nranges`. const ninputs = if (how.pipes()) got.n else 1; var arena_state: std.heap.ArenaAllocator = .init(p.gpa); const arena = arena_state.allocator(); const inputs = arena.alloc([]const u8, ninputs) catch return arena_state.deinit(); for (ranges[0..ninputs], inputs) |range, *input| { const lo = @min(range.anchor, range.head); const hi = @max(range.anchor, range.head); if (how.pipes() and hi > content.len) return arena_state.deinit(); const bytes = if (how.pipes()) content[lo..hi] else ""; input.* = arena.dupe(u8, bytes) catch return arena_state.deinit(); } // `$` 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 (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; 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, .what = t.what, .column = p.headerColumn() orelse 0, .revision = if (pane.file) |f| f.revision else 0, .sum = std.hash.Wyhash.hash(0, content), .arena = arena_state, .command = command_copy, .cwd = cwd_copy, .inputs = inputs, .ranges = ranges, .primary = @intCast(got.pri), .explicit = t.vsel.active and t.vsel.explicit, .how = how, .nranges = @intCast(got.n), }; p.emit(.{ .pipe = .{ .id = p.pipe.seq } }); } /// Frontends call this while draining a .pipe effect, then immediately /// copy the borrowed view into a worker-owned selection_pipe.Job. 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; } fn pipeFailed(p: *Pardes, wait: *const PendingPipe, failure: ?selection_pipe.Failure) void { var out: std.Io.Writer.Allocating = .init(p.gpa); defer out.deinit(); const w = &out.writer; w.print("| {s}\n\n", .{wait.command}) catch |err| return p.reportError(wait.pane, "pipe", err); if (wait.inputs.len > 1) if (failure) |fail| w.print("selection {d} of {d}: ", .{ fail.index + 1, wait.inputs.len }) catch |err| return p.reportError(wait.pane, "pipe", err); writeFailure(w, failure) catch |err| return p.reportError(wait.pane, "pipe", err); const content = out.toOwnedSlice() catch |err| return p.reportError(wait.pane, "pipe", err); const was = p.view().active; panes.Output.openErrors(p, wait.pane.index(), content) catch |err| { p.gpa.free(content); // Nowhere to put the report is itself worth one line. p.reportError(wait.pane, "pipe", err); return; }; if (p.panes[was] != null) p.view().active = was; } /// How a filter failed, a line, and the command's stderr after it: what /// +Errors says of a `|` and of an Edit's `< | >`. pub fn writeFailure(w: *std.Io.Writer, failure: ?selection_pipe.Failure) std.Io.Writer.Error!void { const fail = failure orelse { // No diagnosis at all: nobody ran it. The detached daemon leaves // `pipe` null on purpose. return w.writeAll("this session cannot run filters\n"); }; switch (fail.kind) { .exit => try w.print("exit status {d}\n", .{fail.code}), .signal => try w.writeAll("killed by a signal\n"), .timeout => try w.print( "still running after {d} seconds, and stopped\n", .{selection_pipe.command_timeout_seconds}, ), .too_large => try w.writeAll("produced more output than a filter may return\n"), .spawn => try w.writeAll("could not be started\n"), .io => try w.writeAll("could not be read\n"), } if (fail.stderr.len > 0) try w.print("\n{s}", .{fail.stderr}); } fn pipeCut(wait: *const PendingPipe, content: []const u8, i: usize) ?struct { lo: usize, hi: usize } { const range = wait.ranges[i]; const lo = @min(range.anchor, range.head); const hi = @max(range.anchor, range.head); if (hi > content.len) return null; return switch (wait.how) { .replace, .ignore, .keep => .{ .lo = lo, .hi = hi }, .insert => .{ .lo = lo, .hi = lo }, .append => .{ .lo = hi, .hi = hi }, }; } fn pipeOutput( wait: *const PendingPipe, outputs: []const []const u8, content: []const u8, i: usize, ) []const u8 { var out = if (wait.how.pipes()) outputs[i] else outputs[0]; const range = wait.ranges[i]; const lo = @min(range.anchor, range.head); const hi = @max(range.anchor, range.head); const selected = if (hi <= content.len) content[lo..hi] else ""; if (!std.mem.endsWith(u8, selected, "\n") and std.mem.endsWith(u8, out, "\n")) { out = out[0 .. out.len - 1]; if (std.mem.endsWith(u8, out, "\r")) out = out[0 .. out.len - 1]; } return out; } pub fn pipeResponse( p: *Pardes, id: u32, success: bool, outputs: []const []const u8, 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; var wait = p.pipe.wait.?; p.pipe.wait = null; 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; const t: *Text = switch (wait.what) { .body => &pane.body, .tag => &pane.tag, .column => if (wait.column < p.view().ncol) &p.view().col_tags[wait.column] else return, .workspace => &p.global_tag, .input => return, }; const content = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(wait.pane, "pipe", err); const changed = if (t.what == .body) changed: { const f = pane.file orelse return; if (!panes.Output.fileTraits(f.output).saves) return; break :changed f.revision != wait.revision; } else std.hash.Wyhash.hash(0, content) != wait.sum; if (changed) return p.reportError(wait.pane, "pipe", error.FileChangedWhileFiltering); if (wait.how == .ignore) return; if (wait.how == .keep) { // helix shell_keep_pipe: the primary stays if kept, else the last // kept range takes over; keeping none changes nothing var kept: [panes.Text.max_selections]modal.Selection = undefined; var m: usize = 0; var pri: ?usize = null; for (0..wait.nranges) |i| { 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; } if (m == 0) return; return t.setRanges(p.settings.tab, content, kept[0..m], &.{}, pri orelse m - 1, wait.explicit); } // Each range's cut with its output in place, in order: one splice of // the text (sam_edit.apply), and each range over the output it got. const n = wait.nranges; var ops: [panes.Text.max_selections]sam.Op = undefined; var total_output: usize = 0; // The runner refuses these first (selection_pipe's too_large); an // 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 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 if (total_output > selection_pipe.max_total_stdout_bytes) return p.setMessage(wait.pane, std.fmt.bufPrint(&said, "pipe: {d} bytes of output in all, past {d}: the text is left as it was", .{ total_output, selection_pipe.max_total_stdout_bytes }) catch unreachable); // two numbers fit 128 if (i > 0 and cut.lo < ops[i - 1].q1) return p.setMessage(wait.pane, "pipe: the selections overlap: the text is left as it was"); ops[i] = .{ .q0 = @intCast(cut.lo), .q1 = @intCast(cut.hi), .text = output }; } const replacement = sam.apply(p.gpa, content, ops[0..n]) catch |err| return p.reportError(wait.pane, "pipe", err); var new_ranges: [panes.Text.max_selections]modal.Selection = undefined; var delta: isize = 0; for (ops[0..n], wait.ranges[0..n], new_ranges[0..n]) |op, range, *moved| { const start: usize = @intCast(@as(isize, op.q0) + delta); const end = start + op.text.len; delta += @as(isize, @intCast(op.text.len)) - @as(isize, op.q1 - op.q0); moved.* = if (range.anchor > range.head) .{ .anchor = end, .head = start } else .{ .anchor = start, .head = end }; } // One async request is one history transaction, even at 64 cursors. edit.pushUndo(p.editor(), t) catch |err| { p.gpa.free(replacement); return p.reportError(wait.pane, "pipe", err); }; edit.setEditText(p.editor(), t, replacement) catch |err| return p.reportError(wait.pane, "pipe", err); const now = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(wait.pane, "pipe", err); t.setRanges(p.settings.tab, now, new_ranges[0..n], &.{}, wait.primary, wait.explicit); t.select = false; 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 => |asked| last = asked.id, else => {}, }; return last; } test "selection pipe prompt submits exact request and Escape cancels" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true }); defer p.deinit(); while (p.nextEffect()) |_| {} const pane = try p.setTestFile("one\ntwo\n"); pane.body.cur_row = 0; pane.body.cur_col = 2; pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; p.update(.{ .key = .{ .cp = '|' } }); try std.testing.expect(pane.focus == .body and p.view().tag_state.kind == .prompt); try std.testing.expect(nextPipeEffect(p) == null); p.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); p.update(.{ .key = .{ .cp = Key.enter } }); try std.testing.expect(pane.focus == .body and p.view().tag_state.kind == .rest); const id = nextPipeEffect(p) orelse return error.MissingPipeEffect; const request = p.pipe.pipeRequest(id) orelse return error.MissingPipeRequest; try std.testing.expectEqualStrings("tr a-z A-Z", request.command); try std.testing.expectEqualStrings("/", request.cwd); try std.testing.expectEqual(@as(usize, 1), request.inputs.len); try std.testing.expectEqualSlices(u8, "one", request.inputs[0]); const before = pane.file.?.content; p.update(.{ .key = .{ .cp = '|' } }); p.update(.{ .key = .{ .cp = 'c', .text = "cat" } }); p.update(.{ .key = .{ .cp = Key.escape } }); try std.testing.expect(pane.focus == .body and p.view().tag_state.kind == .rest); try std.testing.expectEqualSlices(u8, before, pane.file.?.content); // `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" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true }); defer p.deinit(); while (p.nextEffect()) |_| {} const pane = try p.setTestFile("body\n"); pane.tag.own = try gpa.dupe(u8, "Look here"); // the user's text (UX K'1) for ("::") |c| p.update(.{ .key = .{ .cp = c } }); // the tag (`:` on the empty `:` field), on its own text p.update(.{ .key = .{ .cp = 'e' } }); // Look selected p.update(.{ .key = .{ .cp = '|' } }); try std.testing.expect(pane.focus == .tag and pane.prompt == .pipe and pane.prompt_for == .tag); p.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); p.update(.{ .key = .{ .cp = Key.enter } }); try std.testing.expect(pane.focus == .tag and pane.prompt == .none); const id = nextPipeEffect(p) orelse return error.MissingPipeEffect; const request = p.pipe.pipeRequest(id) orelse return error.MissingPipeRequest; try std.testing.expectEqual(@as(usize, 1), request.inputs.len); try std.testing.expectEqualSlices(u8, "Look", request.inputs[0]); const outputs: []const []const u8 = &.{"LOOK"}; p.update(.{ .pipe_resp = .{ .id = id, .success = true, .outputs = outputs } }); try std.testing.expectEqualStrings("LOOK here", pardes.tagline.curTail(pane)); try std.testing.expectEqualStrings("body\n", pane.file.?.content); p.update(.{ .key = .{ .cp = 'u' } }); try std.testing.expectEqualStrings("Look here", pardes.tagline.curTail(pane)); } test "$ keeps the selections the command exits 0 on, and a real shell gives that verdict" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true }); defer p.deinit(); while (p.nextEffect()) |_| {} const pane = try p.setTestFile("aa bb cc\n"); const ranges = [_]modal.Selection{ .{ .anchor = 0, .head = 2 }, .{ .anchor = 3, .head = 5 }, .{ .anchor = 6, .head = 8 }, }; pane.body.setRanges(config.tab_width, pane.file.?.content, &ranges, &.{}, 1, true); p.update(.{ .key = .{ .cp = '$' } }); try std.testing.expectEqual(pardes.Prompt.Op.keep_pipe, p.view().tag_state.prompt.op); p.update(.{ .key = .{ .cp = 'g', .text = "grep -v b" } }); p.update(.{ .key = .{ .cp = Key.enter } }); const id = nextPipeEffect(p) orelse return error.MissingPipeEffect; const request = p.pipe.pipeRequest(id) orelse return error.MissingPipeRequest; try std.testing.expectEqual(@as(usize, 3), request.inputs.len); // the wrapper turns each run's status into its output, as the runner sees it const job = try selection_pipe.Job.copy(gpa, request); defer job.deinit(gpa); var response = selection_pipe.runJob(gpa, std.testing.io, job); defer response.deinit(gpa); try std.testing.expect(response.success); try std.testing.expectEqualStrings("0\n", response.outputs[0]); try std.testing.expectEqualStrings("1\n", response.outputs[1]); p.update(.{ .pipe_resp = .{ .id = id, .success = true, .outputs = response.outputs } }); try std.testing.expectEqualStrings("aa bb cc\n", pane.file.?.content); var out: [panes.Text.max_selections]modal.Selection = undefined; const got = pane.body.ranges(pane.file.?.content, 0, &out); try std.testing.expectEqual(@as(usize, 2), got.n); try std.testing.expectEqual(@as(usize, 6), out[1].anchor); // the primary was dropped: the last kept range takes over try std.testing.expectEqual(@as(usize, 1), got.pri); } test "selection pipe replaces all ranges atomically and undo restores them" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true }); defer p.deinit(); while (p.nextEffect()) |_| {} const pane = try p.setTestFile("aa bb cc\n"); const ranges = [_]modal.Selection{ .{ .anchor = 0, .head = 2 }, .{ .anchor = 6, .head = 8 }, }; pane.body.setRanges(config.tab_width, pane.file.?.content, &ranges, &.{}, 0, true); p.update(.{ .key = .{ .cp = '|' } }); p.update(.{ .key = .{ .cp = 'c', .text = "cat" } }); p.update(.{ .key = .{ .cp = Key.enter } }); const id = nextPipeEffect(p) orelse return error.MissingPipeEffect; const request = p.pipe.pipeRequest(id) orelse return error.MissingPipeRequest; try std.testing.expectEqual(@as(usize, 2), request.inputs.len); try std.testing.expectEqualSlices(u8, "aa", request.inputs[0]); try std.testing.expectEqualSlices(u8, "cc", request.inputs[1]); var denied = std.testing.FailingAllocator.init(gpa, .{ .fail_index = 0 }); p.scratch.deinit(); p.scratch = .init(denied.allocator()); const outputs: []const []const u8 = &.{ "AA\n", "" }; p.update(.{ .pipe_resp = .{ .id = id, .success = true, .outputs = outputs } }); try std.testing.expectEqualSlices(u8, "AA bb \n", pane.file.?.content); try std.testing.expectEqual(@as(usize, 1), pane.file.?.history.journal.done); try std.testing.expectEqual(@as(u16, 1), pane.body.nsel); try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col); try std.testing.expectEqual(@as(i32, 6), pane.body.sels[0].col); try std.testing.expect(!denied.has_induced_failure); p.update(.{ .key = .{ .cp = 'u' } }); try std.testing.expectEqualSlices(u8, "aa bb cc\n", pane.file.?.content); } test "a pipe's output past its cap leaves the text as it was, and says so" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true }); defer p.deinit(); while (p.nextEffect()) |_| {} const pane = try p.setTestFile("aa bb cc\n"); const ranges = [_]modal.Selection{ .{ .anchor = 0, .head = 2 }, .{ .anchor = 6, .head = 8 } }; pane.body.setRanges(config.tab_width, pane.file.?.content, &ranges, &.{}, 1, true); p.update(.{ .key = .{ .cp = '|' } }); p.update(.{ .key = .{ .cp = 'c', .text = "cat" } }); p.update(.{ .key = .{ .cp = Key.enter } }); const id = nextPipeEffect(p) orelse return error.MissingPipeEffect; const big = try gpa.alloc(u8, selection_pipe.max_stdout_bytes + 1); defer gpa.free(big); @memset(big, 'x'); const outputs: []const []const u8 = &.{ "AA", big }; p.update(.{ .pipe_resp = .{ .id = id, .success = true, .outputs = outputs } }); try std.testing.expectEqualSlices(u8, "aa bb cc\n", pane.file.?.content); try std.testing.expect(std.mem.indexOf(u8, p.messages.saidBy(pane), "past") != null); } test "the four shell behaviours put their output where helix puts it" { const gpa = std.testing.allocator; const Case = struct { key: Key, outputs: []const []const u8, want: []const u8, want_effect: bool = true, }; // One selection, `bb`, in `aa bb cc\n` โ€” bytes 3..5. for ([_]Case{ // `|` replaces the selection with what the command wrote. .{ .key = .{ .cp = '|' }, .outputs = &.{"XX"}, .want = "aa XX cc\n" }, // `!` inserts BEFORE it, and the selection survives to its right. .{ .key = .{ .cp = '!' }, .outputs = &.{"XX"}, .want = "aa XXbb cc\n" }, // `A-!` appends AFTER it. .{ .key = .{ .cp = '!', .alt = true }, .outputs = &.{"XX"}, .want = "aa bbXX cc\n" }, // `A-|` runs the command and leaves the text completely alone: the // point is the side effect, not the output. .{ .key = .{ .cp = '|', .alt = true }, .outputs = &.{"XX"}, .want = "aa bb cc\n" }, }) |case| { const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 }); defer p.deinit(); while (p.nextEffect()) |_| {} const pane = try p.setTestFile("aa bb cc\n"); pane.body.setRanges(config.tab_width, pane.file.?.content, &.{.{ .anchor = 3, .head = 5 }}, &.{}, 0, true); p.update(.{ .key = case.key }); for ("cmd") |c| p.update(.{ .key = .{ .cp = c, .text = &.{c} } }); p.update(.{ .key = .{ .cp = Key.enter } }); const id = nextPipeEffect(p) orelse return error.MissingPipeEffect; p.update(.{ .pipe_resp = .{ .id = id, .success = true, .outputs = case.outputs } }); try std.testing.expectEqualSlices(u8, case.want, pane.file.?.content); } } test "a command with no stdin runs once and every cursor gets that one answer" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 }); defer p.deinit(); while (p.nextEffect()) |_| {} const pane = try p.setTestFile("aa bb cc\n"); const ranges = [_]modal.Selection{ .{ .anchor = 0, .head = 2 }, .{ .anchor = 6, .head = 8 }, }; pane.body.setRanges(config.tab_width, pane.file.?.content, &ranges, &.{}, 0, true); p.update(.{ .key = .{ .cp = '!' } }); // insert-output: no stdin for ("date") |c| p.update(.{ .key = .{ .cp = c, .text = &.{c} } }); p.update(.{ .key = .{ .cp = Key.enter } }); const id = nextPipeEffect(p) orelse return error.MissingPipeEffect; const request = p.pipe.pipeRequest(id) orelse return error.MissingPipeRequest; try std.testing.expectEqual(@as(usize, 1), request.inputs.len); try std.testing.expectEqualSlices(u8, "", request.inputs[0]); p.update(.{ .pipe_resp = .{ .id = id, .success = true, .outputs = &.{"T"} } }); try std.testing.expectEqualSlices(u8, "Taa bb Tcc\n", pane.file.?.content); try std.testing.expectEqual(@as(usize, 1), pane.file.?.history.journal.done); } test "selection pipe failure and stale completion never mutate the file" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true }); defer p.deinit(); while (p.nextEffect()) |_| {} const pane = try p.setTestFile("abc\n"); pane.body.cur_col = 2; pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; p.update(.{ .key = .{ .cp = '|' } }); p.update(.{ .key = .{ .cp = 'c', .text = "cat" } }); p.update(.{ .key = .{ .cp = Key.enter } }); const failed_id = nextPipeEffect(p) orelse return error.MissingPipeEffect; p.update(.{ .pipe_resp = .{ .id = failed_id, .success = false, .outputs = &.{} } }); try std.testing.expectEqualSlices(u8, "abc\n", pane.file.?.content); try std.testing.expectEqual(@as(usize, 0), pane.file.?.history.journal.done); p.update(.{ .key = .{ .cp = '|' } }); p.update(.{ .key = .{ .cp = 'c', .text = "cat" } }); p.update(.{ .key = .{ .cp = Key.enter } }); const stale_id = nextPipeEffect(p) orelse return error.MissingPipeEffect; panes.File.setContent(p, &pane.file.?, try gpa.dupe(u8, "changed\n")); p.update(.{ .pipe_resp = .{ .id = stale_id, .success = true, .outputs = &.{"ABC"} } }); try std.testing.expectEqualSlices(u8, "changed\n", pane.file.?.content); try std.testing.expectEqual(@as(usize, 0), pane.file.?.history.journal.done); } test "a failed filter opens an errors buffer carrying the command's own words" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 }); defer p.deinit(); while (p.nextEffect()) |_| {} const pane = try p.setTestFile("abc\n"); pane.body.cur_col = 2; pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; p.update(.{ .key = .{ .cp = '|' } }); for ("trr") |c| p.update(.{ .key = .{ .cp = c, .text = &.{c} } }); p.update(.{ .key = .{ .cp = Key.enter } }); const id = nextPipeEffect(p) orelse return error.MissingPipeEffect; // The shape a real runner brings home for `| trr`: nonzero exit, and the // shell's own sentence about it. var stderr = "sh: line 1: trr: command not found\n".*; p.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{}, .failure = .{ .kind = .exit, .code = 127, .stderr = &stderr }, } }); // The text is untouched โ€” a failed filter is not an edit... try std.testing.expectEqualSlices(u8, "abc\n", pane.file.?.content); try std.testing.expectEqual(@as(usize, 0), pane.file.?.history.journal.done); // ...and the cursor did not go anywhere, so `|` again edits the same file. try std.testing.expectEqual(@as(usize, 0), p.view().active); var found: ?[]const u8 = null; for (p.panes) |slot| { const q = slot orelse continue; const qf = q.file orelse continue; const o = qf.output orelse continue; if (std.meta.activeTag(o.from) == .errors) found = qf.content; } const report = found orelse return error.NoErrorsBuffer; try std.testing.expect(std.mem.indexOf(u8, report, "| trr") != null); try std.testing.expect(std.mem.indexOf(u8, report, "exit status 127") != null); try std.testing.expect(std.mem.indexOf(u8, report, "command not found") != null); } test "selection pipe rejects a reused pane slot and a superseded request" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true }); defer p.deinit(); while (p.nextEffect()) |_| {} var pane = try p.setTestFile("old\n"); pane.body.cur_col = 2; pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; p.update(.{ .key = .{ .cp = '|' } }); p.update(.{ .key = .{ .cp = 'c', .text = "cat" } }); p.update(.{ .key = .{ .cp = Key.enter } }); const replaced_id = nextPipeEffect(p) orelse return error.MissingPipeEffect; pane = try p.setTestFile("new\n"); // same slot, different serial p.update(.{ .pipe_resp = .{ .id = replaced_id, .success = true, .outputs = &.{"OLD"} } }); try std.testing.expectEqualSlices(u8, "new\n", pane.file.?.content); try std.testing.expectEqual(@as(usize, 0), pane.file.?.history.journal.done); pane.body.cur_col = 2; pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; p.update(.{ .key = .{ .cp = '|' } }); p.update(.{ .key = .{ .cp = 'c', .text = "cat" } }); p.update(.{ .key = .{ .cp = Key.enter } }); const first_id = nextPipeEffect(p) orelse return error.MissingPipeEffect; p.update(.{ .key = .{ .cp = '|' } }); p.update(.{ .key = .{ .cp = 'c', .text = "tr a-z A-Z" } }); p.update(.{ .key = .{ .cp = Key.enter } }); const latest_id = nextPipeEffect(p) orelse return error.MissingPipeEffect; try std.testing.expect(first_id != latest_id); p.update(.{ .pipe_resp = .{ .id = first_id, .success = true, .outputs = &.{"BAD"} } }); try std.testing.expectEqualSlices(u8, "new\n", pane.file.?.content); p.update(.{ .pipe_resp = .{ .id = latest_id, .success = true, .outputs = &.{"NEW"} } }); try std.testing.expectEqualSlices(u8, "NEW\n", pane.file.?.content); try std.testing.expectEqual(@as(usize, 1), pane.file.?.history.journal.done); } test "selection pipe binding is file-normal-only" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true }); defer p.deinit(); while (p.nextEffect()) |_| {} const pane = try p.setTestFile("x"); pane.file.?.output = .{ .from = .search }; p.update(.{ .key = .{ .cp = '|' } }); try std.testing.expect(p.view().tag_state.kind != .prompt); pane.file.?.output = null; pane.body.mode = .insert; p.update(.{ .key = .{ .cp = '|', .text = "|" } }); try std.testing.expect(p.view().tag_state.kind != .prompt); try std.testing.expectEqualSlices(u8, "|x", pane.file.?.content); }