1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
|
//! 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("pardes.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 Pane = panes.Pane;
const Text = panes.Text;
const Key = pardes.Key;
const Pardes = pardes.Pardes;
const Pipe = @This();
/// 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,
/// 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(gpa);
if (pipe.edit_run) |pending| pending.deinit(gpa);
for (pipe.writes.items) |*w| w.deinit(gpa);
pipe.writes.deinit(gpa);
}
fn nextPipeEffect(p: *Pardes) ?u32 {
while (p.nextEffect()) |effect| switch (effect) {
.pipe => |request| return request.id,
else => {},
};
return null;
}
/// 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 {
id: u32,
pane: usize,
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,
command: []u8,
cwd: []u8,
inputs: []selection_pipe.Input,
ranges: [panes.Text.max_selections]modal.Selection,
primary: u16,
explicit: bool,
how: modal.Normal.PipeBehavior,
nranges: u16,
pub fn deinit(wait: *PendingPipe, gpa: std.mem.Allocator) void {
gpa.free(wait.command);
gpa.free(wait.cwd);
for (wait.inputs) |input| gpa.free(@constCast(input.bytes));
gpa.free(wait.inputs);
wait.* = undefined;
}
fn request(wait: *const PendingPipe) selection_pipe.Request {
return .{
.id = wait.id,
.command = wait.command,
.cwd = wait.cwd,
.inputs = wait.inputs,
};
}
};
pub fn submitPipe(p: *Pardes, id: usize) void {
const pane = p.panes[id] orelse return;
const t = p.promptTarget(pane) orelse return;
if (t.what == .body) {
const f = pane.file orelse return;
if (!panes.Output.fileTraits(f.output).saves) return;
}
const content = edit.flatSurface(p, t) catch 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;
const command = armed[marker.len..];
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;
const inputs = p.gpa.alloc(selection_pipe.Input, ninputs) catch return;
var made: usize = 0;
for (ranges[0..ninputs], 0..) |range, i| {
const bytes = if (how.pipes()) bytes: {
const lo = @min(range.anchor, range.head);
const hi = @max(range.anchor, range.head);
if (hi > content.len) break;
break :bytes content[lo..hi];
} else "";
const copy = p.gpa.dupe(u8, bytes) catch break;
inputs[i] = .{ .bytes = copy };
made += 1;
}
if (made != ninputs) {
for (inputs[0..made]) |input| p.gpa.free(@constCast(input.bytes));
p.gpa.free(inputs);
return;
}
// `$` 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)
std.fmt.allocPrint(p.gpa, "(\n{s}\n) >/dev/null; echo $?", .{command})
else
p.gpa.dupe(u8, command)) catch {
for (inputs) |input| p.gpa.free(@constCast(input.bytes));
p.gpa.free(inputs);
return;
};
const cwd_copy = p.gpa.dupe(u8, Pardes.paneDir(pane)) catch {
p.gpa.free(command_copy);
for (inputs) |input| p.gpa.free(@constCast(input.bytes));
p.gpa.free(inputs);
return;
};
p.pipe.seq +%= 1;
if (p.pipe.wait) |*old| old.deinit(p.gpa);
p.pipe.wait = .{
.id = p.pipe.seq,
.pane = id,
.serial = pane.serial,
.what = t.what,
.column = p.header_column orelse 0,
.revision = if (pane.file) |f| f.revision else 0,
.sum = std.hash.Wyhash.hash(0, content),
.command = command_copy,
.cwd = cwd_copy,
.inputs = inputs,
.ranges = ranges,
.primary = @intCast(got.pri),
.explicit = (t.vsel.active and t.vsel.explicit) or t.msel.active,
.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.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 return;
if (wait.inputs.len > 1) if (failure) |fail|
w.print("selection {d} of {d}: ", .{ fail.index + 1, wait.inputs.len }) catch return;
writeFailure(w, failure) catch return;
const content = out.toOwnedSlice() catch return;
const was = p.active;
panes.Output.openErrors(p, wait.pane, 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.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) !void {
const fail = failure orelse {
// No diagnosis at all: nobody ran it. The detached daemon, the
// browser and the board all leave `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);
// 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(p.gpa);
if (!success or outputs.len != wait.inputs.len) return pipeFailed(p, &wait, failure);
const pane = p.panes[wait.pane] 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.ncol) &p.col_tags[wait.column] else return,
.workspace => &p.global_tag,
.input => return,
};
const content = edit.flatSurface(p, t) catch return;
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| {
if (!std.mem.eql(u8, std.mem.trim(u8, outputs[i], " \n"), "0")) continue;
if (i == wait.primary) pri = m;
kept[m] = wait.ranges[i];
m += 1;
}
if (m == 0) return;
return t.setRanges(content, kept[0..m], &.{}, pri orelse m - 1, wait.explicit);
}
const n = wait.nranges;
var total_output: usize = 0;
var removed: usize = 0;
var previous_end: usize = 0;
for (0..n) |i| {
const cut = pipeCut(&wait, content, i) orelse return;
const output = pipeOutput(&wait, outputs, content, i);
if (output.len > selection_pipe.max_stdout_bytes) return;
total_output = std.math.add(usize, total_output, output.len) catch return;
if (total_output > selection_pipe.max_total_stdout_bytes) return;
if (cut.lo < previous_end) return;
removed = std.math.add(usize, removed, cut.hi - cut.lo) catch return;
previous_end = cut.hi;
}
const kept = content.len - removed;
const final_len = std.math.add(usize, kept, total_output) catch return;
const replacement = p.gpa.alloc(u8, final_len) catch return;
var new_ranges: [panes.Text.max_selections]modal.Selection = undefined;
var read_at: usize = 0;
var write_at: usize = 0;
for (0..n) |i| {
const range = wait.ranges[i];
const cut = pipeCut(&wait, content, i).?;
const output = pipeOutput(&wait, outputs, content, i);
@memcpy(replacement[write_at .. write_at + (cut.lo - read_at)], content[read_at..cut.lo]);
write_at += cut.lo - read_at;
const out_start = write_at;
@memcpy(replacement[write_at .. write_at + output.len], output);
write_at += output.len;
const out_end = write_at;
new_ranges[i] = if (range.anchor > range.head)
.{ .anchor = out_end, .head = out_start }
else
.{ .anchor = out_start, .head = out_end };
read_at = cut.hi;
}
@memcpy(replacement[write_at..], content[read_at..]);
// One async request is one history transaction, even at 64 cursors.
edit.pushUndo(p, t);
edit.setEditText(p, t, replacement);
t.setRanges(edit.flatSurface(p, t) catch return, new_ranges[0..n], &.{}, wait.primary, wait.explicit);
t.select = false;
t.show();
}
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 pane.prompt == .pipe);
try std.testing.expectEqualStrings(config.pipe_marker, pane.promptText().?);
try std.testing.expect(nextPipeEffect(p) == null);
p.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } });
p.update(.{ .key = .{ .cp = Key.enter } });
try std.testing.expect(pane.focus == .body and pane.prompt != .pipe and pane.input.own == null);
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].bytes);
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 pane.prompt != .pipe);
try std.testing.expectEqualSlices(u8, before, pane.file.?.content);
try std.testing.expect(nextPipeEffect(p) == 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");
p.update(.{ .key = .{ .cp = ':' } }); // the tag, on Save
p.update(.{ .key = .{ .cp = 'e' } }); // Save 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, "Save", request.inputs[0].bytes);
const outputs: []const []const u8 = &.{"SAVE"};
p.update(.{ .pipe_resp = .{ .id = id, .success = true, .outputs = outputs } });
try std.testing.expect(std.mem.startsWith(u8, pardes.tagline.curTail(pane), " SAVE "));
try std.testing.expectEqualStrings("body\n", pane.file.?.content);
p.update(.{ .key = .{ .cp = 'u' } });
try std.testing.expect(std.mem.startsWith(u8, pardes.tagline.curTail(pane), " Save "));
}
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(pane.file.?.content, &ranges, &.{}, 1, true);
p.update(.{ .key = .{ .cp = '$' } });
try std.testing.expectEqualStrings(config.pipe_marker_keep, pane.promptText().?);
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(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].bytes);
try std.testing.expectEqualSlices(u8, "cc", request.inputs[1].bytes);
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.undo_len);
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 "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(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(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].bytes);
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.undo_len);
}
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.undo_len);
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.undo_len);
}
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.undo_len);
// ...and the cursor did not go anywhere, so `|` again edits the same file.
try std.testing.expectEqual(@as(usize, 0), p.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.undo_len);
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.undo_len);
}
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(pane.prompt != .pipe);
pane.file.?.output = null;
pane.body.mode = .insert;
p.update(.{ .key = .{ .cp = '|', .text = "|" } });
try std.testing.expect(pane.prompt != .pipe);
try std.testing.expectEqualSlices(u8, "|x", pane.file.?.content);
}
|