summaryrefslogtreecommitdiff
path: root/src/exec.zig
blob: 963c87630a721518dcc55b77bb3ff36e5739b945 (plain) (blame)
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
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
//! Executing a word (acme's exec.c): a builtin line or a command typed into
//! a terminal, the builtin dispatch and settings, the operand a click or
//! chord hands over, the terminals commands run in, placing a document, and
//! saving a pane.
const pardes = @import("pardes.zig");
const tagline = @import("tagline.zig");
const std = @import("std");
const layout = @import("layout.zig");
const modal = @import("modal.zig");
const look = @import("look.zig");
const panes = @import("panes.zig");
const normal = @import("normal.zig");
const edit = @import("edit.zig");
const body_layer = @import("body_layer.zig");
const colors = @import("colors.zig");
const themes = colors.themes;
const builtins = @import("builtins.zig");
const config = @import("config.zig");
const grammars = @import("grammar_manifest.zig").all;
const python_lang = blk: {
    @setEvalBranchQuota(20_000);
    break :blk @import("grammar_manifest.zig").byName("python").?;
};
const pdf_enabled = panes.Pdf.enabled;
const font_picker = pardes.font_picker;
const hosted = pardes.hosted;
const fonts = pardes.fonts;
const Pane = panes.Pane;
const MAX_COLS = pardes.MAX_COLS;
const BOX_H = pardes.BOX_H;
const Builtin = pardes.Builtin;
const Key = pardes.Key;
const sel_slot = pardes.sel_slot;
const Pardes = pardes.Pardes;

pub fn takesCommandLine(p: *const Pardes, id: usize) bool {
    const pane = p.panes[id] orelse return false;
    // A command pane's child is its command, never a shell to type at.
    if (!pane.isTerminal() or pane.command != null) return false;
    // A mounted shell sits behind sudo's process supervisor. Its OSC 133
    // prompt marks identify input readiness; the launcher's executable is
    // not the shell executable used by the ordinary process heuristic.
    if (pane.v9fs_on_spawn) return panes.Terminal.promptInputReady(pane);
    return !p.hostTtyTaken(id);
}

pub fn chordEachSel(p: *Pardes, pane: *Pane, cmd: Builtin) bool {
    if (pane.body.nsel == 0) return false;
    const text = edit.flatSurface(p, &pane.body) catch return false;
    var ranges: [panes.Text.max_selections]modal.Selection = undefined;
    const got = pane.body.ranges(text, 0, &ranges);
    if (got.n < 2) return false;

    var texts: [panes.Text.max_selections][]u8 = undefined;
    var made: usize = 0;
    defer for (texts[0..made]) |t| p.gpa.free(t);
    for (ranges[0..got.n]) |range| {
        const lo = @min(range.anchor, range.head);
        const hi = @max(range.anchor, range.head);
        if (hi > text.len) break;
        texts[made] = p.gpa.dupe(u8, text[lo..hi]) catch break;
        made += 1;
    }
    // All or nothing, like the pipe: half a chord is not a chord.
    if (made != got.n) return false;

    const id = p.active;
    const serial = pane.serial;
    pane.body.vsel.active = false;
    pane.body.msel.active = false;
    pane.body.select = false;
    pane.body.nsel = 0; // the chord consumed them, exactly as it consumes one

    var primary_active: ?usize = null;
    for (texts[0..made], 0..) |txt, i| {
        // Every selection is the body's, each one sent as the first is.
        runBuiltinFrom(p, cmd, id, "", txt, true);
        if (i == got.pri) primary_active = p.active;
        const still = p.panes[id] orelse break;
        if (still.serial != serial) break;
    }
    if (primary_active) |a| if (p.panes[a] != null) {
        p.active = a;
    };
    return true;
}

pub const PointerOperand = struct {
    /// Absolute body position corresponding to the pointed screen cell.
    row: i32,
    col: i32,
    /// Exactly what a no-drag middle/right click will dispatch.
    text: ?[]const u8 = null,
    /// What hover paints. Null names the pane's live modal selection.
    preview: ?Pane.Sel = null,
    /// File words stay logical so a soft-wrapped operand is not cut into
    /// unrelated rendered fragments. Null for tags and non-file panes.
    file_word: ?look.FileWordSpan = null,
    /// A newly expanded word is installed in the gesture's button slot;
    /// an existing selection is only borrowed and must not replace it.
    expanded: ?Pane.Sel = null,
};

pub fn pointerOperand(p: *Pardes, pane: *Pane, clicked: Pane.Sel) PointerOperand {
    const visible = clicked.r0 - @as(i32, pane.tag_rows);
    const wrapped = pane.wrapAt(visible);
    const raw = pane.isTerminal() and pane.body.mode == .tty and clicked.r0 >= pane.tag_rows;
    const row = if (raw) panes.Terminal.gridOffset(pane) + visible else wrapped.line;
    const raw_line = if (raw) modal.lineSlice(body_layer.bodyText(p, p.scratch.allocator(), pane) catch "", @intCast(@max(0, visible))) else "";
    const col = if (raw)
        @as(i32, @intCast(panes.File.rawAtDisplay(raw_line, @intCast(@max(0, clicked.c0)))))
    else if (clicked.r0 >= pane.tag_rows)
        edit.paneByteAtDisplay(
            p,
            &pane.body,
            wrapped.line,
            wrapped.at,
            clicked.c0 - (if (pane.file != null) @as(i32, panes.File.gutterWidth(pane)) else 0),
        )
    else
        clicked.c0;
    var result: PointerOperand = .{ .row = row, .col = col };

    const kept = pane.sel[sel_slot];
    const inside_kept = if (pane.pointerSelection(kept)) |rows| inside: {
        if (clicked.r0 < pane.tag_rows) break :inside false;
        if (pane.file != null and clicked.c0 < panes.File.gutterWidth(pane)) break :inside false;
        const source_col: usize = @intCast(@max(0, col));
        for (rows) |span| {
            const target = if (span.raw_terminal)
                (if (raw) span.row else pane.surfRow(span.row))
            else
                (if (raw) pane.gridRow(span.row) else span.row);
            var lo = span.lo;
            var hi = span.hi;
            if (span.raw_terminal and !raw) {
                lo -|= span.prompt_bytes;
                hi -|= span.prompt_bytes;
            } else if (!span.raw_terminal and raw) {
                const prefix = panes.Terminal.promptPrefixBytes(pane, row, raw_line);
                lo += prefix;
                hi += prefix;
            }
            if (target == row and source_col >= lo and source_col < hi)
                break :inside true;
        }
        break :inside false;
    } else edit.spanHas(clicked.r0, clicked.c0, kept.r0, kept.c0, kept.r1, kept.c1);
    if (kept.state == .done and inside_kept) {
        result.text = edit.selectionText(p, pane, kept) catch null;
        result.preview = kept;
        return result;
    }
    if (pane.body.vsel.active and pane.body.vsel.explicit and
        edit.spanHas(row, col, pane.body.vsel.row, pane.body.vsel.col, pane.body.cur_row, pane.body.cur_col))
    {
        result.text = edit.currentSelText(p, pane);
        return result;
    }
    if (pane.body.msel.active and row >= @min(pane.body.msel.r0, pane.body.msel.r1) and
        row <= @max(pane.body.msel.r0, pane.body.msel.r1))
    {
        result.text = edit.currentSelText(p, pane);
        return result;
    }
    if (pane.file != null and clicked.r0 >= pane.tag_rows and clicked.r0 == clicked.r1 and clicked.c0 == clicked.c1) {
        const line = panes.File.sourceLine(pane, row);
        const source_col: usize = @intCast(@max(0, col));
        const b = look.expandedWord(line, source_col) orelse return result;
        const lo = std.math.cast(i32, b.lo) orelse return result;
        const hi = std.math.cast(i32, b.hi) orelse return result;
        result.text = line[b.lo..b.hi];
        result.file_word = .{ .row = row, .lo = lo, .hi = hi };

        var expanded = clicked;
        const first = pane.wrapRow(row, lo);
        const last = pane.wrapRow(row, hi - 1);
        if (first.row >= 0 and last.row >= 0) {
            expanded.r0 = first.row + @as(i32, pane.tag_rows);
            expanded.c0 = @as(i32, panes.File.gutterWidth(pane)) + panes.File.displayOffset(pane, row, first.at, lo);
            expanded.r1 = last.row + @as(i32, pane.tag_rows);
            expanded.c1 = @as(i32, panes.File.gutterWidth(pane)) + panes.File.displayEndOffset(pane, row, last.at, hi - 1);
        }
        result.preview = expanded;
        result.expanded = expanded;
        return result;
    }

    const expanded = look.expandedSel(p, pane, clicked) orelse return result;
    result.text = edit.selectionText(p, pane, expanded) catch null;
    if (result.text == null or result.text.?.len == 0) return result;
    result.preview = expanded;
    result.expanded = expanded;
    return result;
}

pub fn heldSelection(p: *Pardes, first: usize) ?[]const u8 {
    var k: usize = 0;
    while (k < p.panes.len + 2) : (k += 1) {
        const i = switch (k) {
            0 => first,
            1 => p.active,
            else => k - 2,
        };
        if (k > 0 and (i == first or (k > 1 and i == p.active))) continue;
        const t = p.panes[i] orelse continue;
        if (comptime pdf_enabled) if (p.native_images) if (t.pdf) |pv| {
            if (pv.selection != null and pv.selection_text.len > 0)
                return pv.selection_text;
        };
        if (t.sel[sel_slot].state == .done) {
            if (edit.selectionText(p, t, t.sel[sel_slot]) catch null) |tx| return tx;
        } else if ((t.body.vsel.active and t.body.vsel.explicit) or t.body.msel.active) {
            if (edit.currentSelText(p, t)) |tx| return tx;
        }
    }
    return null;
}

/// A clicked word and the selection held for it, as one command line.
pub fn withArg(p: *Pardes, txt: []const u8, arg: ?[]const u8) []const u8 {
    const a = std.mem.trim(u8, arg orelse return txt, " \t\r\n");
    if (a.len == 0) return txt;
    const t = std.mem.trim(u8, txt, " \t\r\n");
    // A switch (Verbose, PanelSlide, Crt) clicked with some other text
    // selected flips, as it does bare: only `on` or `off` is an argument
    // for it. What a ctl write gives it is checked strictly instead.
    if (config.Runtime.find(commandText(t))) |setting| switch (setting.action) {
        .toggle, .transition, .scene => if (!std.mem.eql(u8, a, "on") and !std.mem.eql(u8, a, "off")) return txt,
        else => {},
    };
    return std.fmt.allocPrint(p.scratch.allocator(), "{s} {s}", .{ t, a }) catch txt;
}

/// Enter on a save input: the path is everything past the marker.
pub fn submitSave(p: *Pardes, id: usize) void {
    const pane = p.panes[id] orelse return;
    if (pane.prompt != .save) return;
    const armed = pane.promptText() orelse return;
    if (!std.mem.startsWith(u8, armed, config.save_marker)) return;
    const path = std.mem.trim(u8, armed[config.save_marker.len..], " \t\r\n");
    if (path.len == 0) return;
    saveTo(p, id, path);
}

/// Write the file this pane already has: acme's Put, and the one Save that
/// needs no argument because the path was never a question.
pub fn saveFile(p: *Pardes, id: usize) void {
    const pane = p.panes[id] orelse return;
    const f = if (pane.file) |*file| file else return;
    if (f.output != null) return; // nothing behind it yet: saveTo, with a path
    p.emit(.{ .save_file = .{ .pane = @intCast(id) } });
}

pub fn saveTo(p: *Pardes, id: usize, path: []const u8) void {
    const pane = p.panes[id] orelse return;
    if (path.len == 0 or path[path.len - 1] == '/' or
        std.mem.indexOfScalar(u8, path, '\n') != null)
        return p.reportError(id, "save", error.NoFilename);
    const full = std.fs.path.resolvePosix(
        p.scratch.allocator(),
        &.{ Pardes.paneDir(pane), path },
    ) catch return;
    if (!std.fs.path.isAbsolute(full)) return p.reportError(id, "save", error.NoDirectory);
    if (full.len > Pardes.SavePath.cap) return p.reportError(id, "save", error.PathTooLong);
    const f = if (pane.file) |*file| file else {
        // a terminal writes its scrollback; an image and a PDF have nothing
        // of their own that is unwritten, so they have nothing to write
        if (pane.isTerminal()) askWrite(p, id, pane.serial, full);
        return;
    };
    if (f.output != null and panes.Output.fileTraits(f.output).saves) {
        const owned = p.gpa.dupe(u8, full) catch return;
        p.gpa.free(f.path);
        f.path = owned;
        f.output = null; // an ordinary file pane from here on
        f.watch_after_save = true;
        pane.clearCwd();
        // re-derive the tag as a plain file's
        if (pane.tag.own) |own| p.gpa.free(own);
        pane.tag.own = null;
        p.emit(.{ .save_file = .{ .pane = @intCast(id) } });
        return;
    }
    // its own path, spelled out: the in-place write, so the pane comes clean
    if (f.output == null and std.mem.eql(u8, f.path, full)) return saveFile(p, id);
    askWrite(p, id, pane.serial, full);
}

fn askWrite(p: *Pardes, id: usize, serial: u32, path: []const u8) void {
    p.emit(.{ .save_text = .{
        .pane = @intCast(id),
        .serial = serial,
        .path = Pardes.SavePath.from(path),
    } });
}

/// Tty: a shell in the caller's directory, raw from the first frame,
/// stacked below the caller like Alt-n's new shell.
pub fn spawnTty(p: *Pardes, from: usize) ?*Pane {
    return spawnTtyWithMount(p, from, false);
}

pub fn spawnV9fsTty(p: *Pardes, from: usize) void {
    if (comptime !hosted or @import("builtin").os.tag != .linux)
        return p.reportError(from, "Tty9p", error.LinuxRequired);
    if (p.fs.socket_path.len == 0)
        return p.reportError(from, "Tty9p", error.SessionSocketRequired);
    _ = spawnTtyWithMount(p, from, true);
}

fn spawnTtyWithMount(p: *Pardes, from: usize, v9fs: bool) ?*Pane {
    if (p.panes[from] == null) return null;
    const free = p.freeSlot() orelse {
        p.reportError(from, "Tty", error.NoPaneSlots);
        return null;
    };
    const nt = p.newShell(free, p.execDir(from)) catch |err| {
        p.reportError(from, "Tty", err);
        return null;
    };
    nt.greet = !v9fs;
    nt.v9fs_on_spawn = v9fs;
    nt.body.mode = .tty;
    placeNew(p, from, from, free, .shell);
    return nt;
}

/// With `BootShell replace`, a doc landing in `col` closes a lone pristine
/// shell there, the boot's placeholder, and absorbVWeight hands its space to
/// the doc. With `keep`, the default, the shell stays like any other pane.
pub fn evictLonePristineTty(p: *Pardes, col: usize, keep_id: usize) void {
    if (p.settings.boot_shell == .keep) return;
    var n_tty: usize = 0;
    var tty_id: usize = 0;
    for (0..p.col_n[col]) |k| {
        const cid = p.col_panes[col][k];
        if (p.panes[cid]) |ct| if (ct.isTerminal()) {
            n_tty += 1;
            tty_id = cid;
        };
    }
    if (n_tty != 1) return;
    const tt = p.panes[tty_id] orelse return;
    // No typing, cursor on the first prompt line, no scrollback: this is
    // the throwaway boot placeholder a document may replace.
    if (tt.ovl != null or panes.Terminal.gridCursor(tt).y != 0 or
        panes.Terminal.scrollbar(tt).total > tt.rows) return;
    p.deinitPane(tt) catch |err| return p.reportError(tty_id, "close", err);
    layout.compute(p); // a just-stacked doc has no rect yet; absorb snaps to rows
    _ = layout.absorbVWeight(p, tty_id, null);
    layout.removePane(p, tty_id);
    p.panes[tty_id] = null;
    if (p.active == tty_id) p.active = keep_id;
}

// ---- REPLs ----
//
// A terminal is bound as a language's REPL by `Repl python` (builtins.zig).
// An exec made by a gesture on the body of a file in that language -- or on
// the REPL's own body -- is sent to it as input rather than run: all of it,
// a word like `ls` too. The tag's words, `Exec` by name and a command word
// `@`...`` still run as commands.

/// A file pane's language, as grammar_manifest names it, by its index.
pub fn langOf(pane: *const Pane) ?u8 {
    const f = pane.file orelse return null;
    return @intCast(@import("grammar_manifest.zig").byPath(f.path) orelse return null);
}

/// A bound REPL whose program is there to take input: a command pane's
/// while its command runs; an interactive terminal's while a program, not
/// the shell, has its tty (the host's `tty_taken`) -- a python3 left with
/// Ctrl-D leaves the shell, which would run `import os` as ImageMagick's.
pub fn replLive(p: *const Pardes, id: usize) bool {
    const pane = p.panes[id] orelse return false;
    if (pane.repl == null) return false;
    if (pane.command != null) return !pane.command_done;
    return p.hostTtyTaken(id);
}

/// `python-a`.
pub fn replId(buf: []u8, pane: *const Pane) []const u8 {
    const r = pane.repl orelse return "";
    return std.fmt.bufPrint(buf, "{s}-{c}", .{ grammars[r.lang].name, r.letter }) catch "";
}

const Routed = union(enum) { none, sent: usize, asked };

/// The REPL bound here has no program running to take the text: said,
/// and nothing sent or run.
fn replGone(p: *Pardes, from: usize, repl: *const Pane) Routed {
    var idbuf: [48]u8 = undefined;
    var said: [128]u8 = undefined;
    p.setMessage(from, std.fmt.bufPrint(&said, "Repl: {s} has no program running; nothing sent", .{replId(&idbuf, repl)}) catch "Repl: no program running");
    return .asked;
}

/// Where an exec from `from`'s body goes when a REPL is bound for it: the
/// one there is, or a question when there are several.
fn routeToRepl(p: *Pardes, from: usize, text: []const u8) Routed {
    const src = p.panes[from] orelse return .none;
    if (src.repl != null) {
        if (!replLive(p, from)) return replGone(p, from, src);
        sendToRepl(p, from, from, text);
        return .{ .sent = from };
    }
    const lang = langOf(src) orelse return .none;
    var bound: [26]usize = undefined;
    var n: usize = 0;
    var gone: ?usize = null;
    for (p.panes, 0..) |slot, i| if (slot) |pane| if (pane.repl) |r| if (r.lang == lang and n < bound.len) {
        if (!replLive(p, i)) {
            gone = i;
            continue;
        }
        bound[n] = i;
        n += 1;
    };
    if (n == 0) return if (gone) |i| replGone(p, from, p.panes[i].?) else .none;
    if (n == 1) {
        sendToRepl(p, from, bound[0], text);
        return .{ .sent = bound[0] };
    }
    // Several: asked on the pane's notice band, as Del asks, one key
    // answering; nothing is remembered of the answer.
    const owned = p.gpa.dupe(u8, text) catch return .none;
    if (p.repl_ask) |old| p.gpa.free(old.text);
    p.repl_ask = .{ .from = src.serial, .lang = lang, .text = owned };
    for (bound[0..n]) |i| p.repl_ask.?.offered[p.panes[i].?.repl.?.letter - 'a'] = p.panes[i].?.serial;
    var w = std.Io.Writer.fixed(&src.question);
    w.print("send to {s}:", .{grammars[lang].name}) catch {};
    for (bound[0..n]) |i| w.print("  {c}", .{p.panes[i].?.repl.?.letter}) catch {};
    w.writeAll("  (Esc: none)") catch {};
    src.question_len = @intCast(w.buffered().len);
    src.prompt = .repl_choice;
    p.active = from;
    var rec: [96]u8 = undefined;
    var rw = std.Io.Writer.fixed(&rec);
    rw.print("{d} repl", .{src.serial}) catch {};
    for (bound[0..n]) |i| rw.print(" {c}", .{p.panes[i].?.repl.?.letter}) catch {};
    pardes.ctlfs.events.notePath(p, "ask", rw.buffered());
    return .asked;
}

const repl_enter_wait_ns: u64 = 250 * std.time.ns_per_ms;

/// Sends the Enters a paste into pane `id`'s REPL is owed: when the REPL
/// has answered it (`answered`), or once the wait is up.
pub fn flushReplEnter(p: *Pardes, id: usize, answered: bool) void {
    const pane = p.panes[id] orelse return;
    if (pane.repl_enter == 0) return;
    if (!answered and p.now_ns < pane.repl_enter_due_ns) return;
    for (0..pane.repl_enter) |_| p.emitWrite(id, "\r");
    pane.repl_enter = 0;
}

fn pythonBlockOpen(text: []const u8) bool {
    const trimmed = std.mem.trimEnd(u8, text, " \t\n");
    const start = if (std.mem.lastIndexOfScalar(u8, trimmed, '\n')) |nl| nl + 1 else 0;
    const last = trimmed[start..];
    return last.len > 0 and (last[0] == ' ' or last[0] == '\t' or last[last.len - 1] == ':');
}

/// Types `text` into the REPL in `to`, bracketed if its program asked for
/// that, then Enter; says so on `from`'s message row and in the log.
pub fn sendToRepl(p: *Pardes, from: usize, to: usize, text: []const u8) void {
    const dst = p.panes[to] orelse return;
    const src = p.panes[from] orelse return;
    var idbuf: [48]u8 = undefined;
    const id = replId(&idbuf, dst);
    // Lines end in \n alone (a \r\n would give Python a blank line that
    // ends its block), and no ESC or other control byte but a tab goes: an
    // ESC[201~ in the text would end a bracketed paste early.
    const clean = p.scratch.allocator().alloc(u8, text.len) catch return;
    var n: usize = 0;
    for (text, 0..) |c, i| {
        if (c == '\r') {
            if (i + 1 < text.len and text[i + 1] == '\n') continue;
            clean[n] = '\n';
        } else if (c < ' ' and c != '\t' and c != '\n' or c == 0x7f) continue else clean[n] = c;
        n += 1;
    }
    // Sent whole or not at all: a send cut short would leave the REPL in a
    // paste, or with half a block.
    if (n + 16 > p.writeRoom(to)) {
        var said: [128]u8 = undefined;
        return p.setMessage(from, std.fmt.bufPrint(&said, "Repl: {d} bytes is more than can be sent at once; send less", .{n}) catch "Repl: too long to send");
    }
    const pasted = panes.Terminal.bracketedPaste(dst);
    edit.typeToTty(p, to, dst, clean[0..n]);
    // A Python block whose last line is indented, or a bare header, is not
    // over at one Enter, pasted into 3.13's REPL or typed into the old one:
    // the blank line a second Enter gives ends it.
    const enters: u8 = if ((if (dst.repl) |r| r.lang == python_lang else false) and pythonBlockOpen(clean[0..n])) 2 else 1;
    if (pasted) {
        // An Enter read with the paste is part of it: 3.13's REPL takes it
        // as a newline in the pasted text, even a one-line one, and waits.
        // It goes once the REPL has answered the paste (its next output),
        // or after a moment if nothing comes.
        dst.repl_enter = enters;
        // From the clock now, not core time: idle (a detached session
        // nobody watches), `stepped_ns` and `now_ns` are as old as the last
        // frame, and a wait counted from there would be over already, the
        // Enter going out with the paste.
        const now = if (p.host.vtable.now) |clock| clock(p.host.ctx) else p.now_ns;
        dst.repl_enter_due_ns = now + repl_enter_wait_ns;
    } else for (0..enters) |_| p.emitWrite(to, "\r");
    // Line by line, a blank line inside a Python block ends the block.
    if (!panes.Terminal.bracketedPaste(dst) and !dst.repl_warned and (if (dst.repl) |r| r.lang == python_lang else false) and
        std.mem.indexOfScalar(u8, text, '\n') != null)
    {
        dst.repl_warned = true;
        var warn: [128]u8 = undefined;
        p.setMessage(from, std.fmt.bufPrint(&warn, "Repl: {s} takes no bracketed paste; a blank line in a block ends it", .{id}) catch "Repl: no bracketed paste");
    }
    var said: [64]u8 = undefined;
    p.setMessage(from, std.fmt.bufPrint(&said, "\u{2192} {s}", .{id}) catch "sent");
    src.msg_sent = true;
    var rec: [96]u8 = undefined;
    pardes.ctlfs.events.notePath(p, "send", std.fmt.bufPrint(&rec, "{d} {d} {s}", .{ src.serial, dst.serial, id }) catch return);
}

/// The longest line a command pane runs.
pub const command_max = 1024;

const max_exec_depth = 8;

/// A word no builtin knows (acme's exec.c run()). Clicked in an interactive
/// terminal, it is typed into that shell, whose state the click can see;
/// from anywhere else it runs as its own command pane, a terminal whose
/// child is `$SHELL -c` the line, which shows its output and `exit N` when
/// done, and which Kill signals. Answers the pane it went to.
pub fn execute(p: *Pardes, id: usize, txt: []const u8) ?usize {
    return executeFrom(p, id, txt, false);
}

/// `execute` for text a gesture took from `id`'s body when `from_body`:
/// such text may be a bound REPL's. Run by name (`Exec ...`, whose line
/// comes back through `execute`) or written as a command word, never.
pub fn executeFrom(p: *Pardes, id: usize, txt: []const u8, from_body: bool) ?usize {
    const pane = p.panes[id] orelse return null;
    const gesture = from_body and config.commandWord(std.mem.trim(u8, txt, " \t\r\n")) == null;
    const cmd = commandText(txt);
    if (cmd.len == 0) return null;
    if (p.exec_depth == 0) p.noteHaptic(.exec);
    if (executeBuiltinLine(p, id, cmd)) return null;
    if (p.exec_depth >= max_exec_depth) return null;
    p.exec_depth += 1;
    defer p.exec_depth -= 1;
    if (gesture) switch (routeToRepl(p, id, cmd)) {
        .none => {},
        .sent => |to| return to,
        .asked => return null,
    };
    if (!takesCommandLine(p, id)) return runCommand(p, id, cmd);
    panes.Terminal.padOutputBelowEdits(p, id);
    panes.Terminal.noteCommand(pane, cmd);
    if (panes.Terminal.queuePendingCommand(pane, cmd) catch |err| {
        p.reportError(id, "queue command", err);
        return id;
    }) return id;
    p.emitWrite(id, cmd);
    p.emitWrite(id, "\r");
    return id;
}

/// Runs `line` in a command pane for `from`'s directory: `from` itself if
/// it is one whose command is done, else the directory's command pane that
/// is done, else a new one, placed as placeNew places a command pane.
/// A pane reused keeps what it showed: the new command runs below a line
/// naming it, as acme appends to +Errors and never clears it (util.c:213).
fn runCommand(p: *Pardes, from: usize, line: []const u8) ?usize {
    // The board and the web page start no processes: a command pane there
    // would say running for ever, and fill the slots.
    if (comptime !hosted) {
        p.reportFailure(from, "exec: not a builtin, and this build runs no commands");
        return null;
    }
    if (line.len > command_max) {
        p.reportFailure(from, "exec: a command line is at most 1024 bytes");
        return null;
    }
    const src = p.panes[from] orelse return null;
    const dir = p.execDir(from);
    // Not one whose pty a job it left behind still prints to: reusing it
    // would hang that job up.
    const reuse: ?usize = if (src.command != null and src.command_done and !src.command_pty) from else for (p.panes, 0..) |slot, i| {
        const other = slot orelse continue;
        if (other.command != null and other.command_done and !other.command_pty and std.mem.eql(u8, other.cwdSlice(), dir)) break i;
    } else null;
    if (reuse) |id| {
        const pane = p.panes[id].?;
        const owned = p.gpa.dupe(u8, line) catch |err| {
            p.reportError(from, "exec", err);
            return null;
        };
        p.gpa.free(pane.command.?);
        pane.command = owned;
        pane.command_done = false;
        pane.command_status = null;
        pane.command_pty = true;
        pane.body.mode = .tty;
        // What the last program left the emulator in goes first: the
        // alternate screen left (only if it is there: leaving restores a
        // saved cursor), mouse reports and bracketed paste off, the cursor
        // shown, colours reset. (Not DECSTR: ghostty's stream does not
        // implement it.)
        if (panes.Terminal.onAlternateScreen(pane)) panes.Terminal.feedOutput(p, pane, "\x1b[?1049l");
        panes.Terminal.feedOutput(p, pane, "\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?2004l\x1b[?25h\x1b[0m");
        echoCommand(p, pane, line);
        p.emit(.{ .spawn = .{ .pane = @intCast(id), .serial = pane.serial, .cwd = .from(pane.cwdSlice()) } });
        noteRun(p, pane, "run", line);
        return id;
    }
    const free = p.freeSlot() orelse {
        p.reportError(from, "exec", error.NoPaneSlots);
        return null;
    };
    const pane = p.newCommand(free, dir, line) catch |err| {
        p.reportError(from, "exec", err);
        return null;
    };
    echoCommand(p, pane, line);
    placeNew(p, from, from, free, .command);
    noteRun(p, pane, "run", line);
    return free;
}

/// `% line` above a command's output, every command, as a shell echoes
/// what it was given; its newlines the terminal's, so a multi-line command
/// does not staircase.
fn echoCommand(p: *Pardes, pane: *Pane, line: []const u8) void {
    var buf: [2 * command_max + 8]u8 = undefined;
    var w = std.Io.Writer.fixed(&buf);
    w.writeAll(if (panes.Terminal.gridCursor(pane).x != 0) "\r\n% " else "% ") catch {};
    for (line) |c| (if (c == '\n') w.writeAll("\r\n") else w.writeByte(c)) catch {};
    w.writeAll("\r\n") catch {};
    panes.Terminal.feedOutput(p, pane, w.buffered());
}

/// `run <serial> <word>` or `exit <serial> <N|?>` in the log.
/// The whole line, one record as `msg` carries its text: its control
/// characters, a newline too, become spaces (events.pushLog). A new pane is
/// announced first, so `new` comes before the `run` in it.
pub fn noteRun(p: *Pardes, pane: *Pane, what: []const u8, said: []const u8) void {
    pardes.ctlfs.events.announce(p);
    var buf: [command_max + 16]u8 = undefined;
    pardes.ctlfs.events.notePath(p, what, std.fmt.bufPrint(&buf, "{d} {s}", .{ pane.serial, std.mem.trim(u8, said, " \t\r\n") }) catch return);
}

/// A command pane's child is gone: the pane stays, showing what it said
/// and how it ended, and is the next command's for its directory.
pub fn commandDone(p: *Pardes, id: usize, status: ?u8) void {
    const pane = p.panes[id] orelse return;
    pane.command_done = true;
    // A REPL it was is gone with its command; the pane's next is not one.
    pane.repl = null;
    pane.command_status = status;
    pane.body.mode = .normal;
    var buf: [16]u8 = undefined;
    const code = if (status) |n| std.fmt.bufPrint(&buf, "{d}", .{n}) catch "?" else "?";
    var said: [32]u8 = undefined;
    const lead = if (panes.Terminal.gridCursor(pane).x != 0) "\r\n" else "";
    panes.Terminal.feedOutput(p, pane, std.fmt.bufPrint(&said, "{s}exit {s}\r\n", .{ lead, code }) catch "exit ?\r\n");
    noteRun(p, pane, "exit", code);
    p.needs_frame = true;
}

/// Trim and unwrap clickable command-word notation once for every command
/// consumer, so startup lines and interactive Exec speak the same syntax.
pub fn commandText(txt: []const u8) []const u8 {
    var cmd = std.mem.trim(u8, txt, " \t\r\n");
    while (config.commandWord(cmd)) |inner| cmd = std.mem.trim(u8, inner, " \t\r\n");
    return cmd;
}

pub fn executeBuiltinLine(p: *Pardes, id: usize, txt: []const u8) bool {
    const cmd = commandText(txt);
    if (cmd.len == 0 or p.exec_depth >= max_exec_depth) return false;
    // `Word arg`, or for a word that says so, `Word+arg` (`Tty+fish`).
    const plus = std.mem.indexOfScalar(u8, cmd, '+');
    var sp = std.mem.indexOfAny(u8, cmd, " \t");
    if (sp == null) if (plus) |at| if (std.meta.stringToEnum(Builtin, cmd[0..at])) |head| {
        if (builtins.registry.plusArg(head)) sp = at;
    };
    const bi: ?Builtin = std.meta.stringToEnum(Builtin, cmd) orelse blk: {
        const head = std.meta.stringToEnum(Builtin, cmd[0 .. sp orelse break :blk null]) orelse break :blk null;
        break :blk if (builtins.registry.takesArg(head)) head else null;
    };
    const b = bi orelse return false;
    p.exec_depth += 1;
    defer p.exec_depth -= 1;
    const typed = if (sp) |s| std.mem.trim(u8, cmd[s + 1 ..], " \t") else "";
    runBuiltin(p, b, id, cmd, if (typed.len > 0) typed else null);
    return true;
}

pub fn applyStartupConfig(p: *Pardes) void {
    p.announce = false;
    defer p.announce = true;
    var lines = std.mem.splitScalar(u8, p.opts.startup_config orelse return, '\n');
    while (lines.next()) |line| {
        if (executeBuiltinLine(p, p.active, line)) continue;
        // A setting pardes no longer has is said, once, and changes nothing.
        const word = commandText(line);
        if (std.mem.eql(u8, word[0 .. std.mem.indexOfAny(u8, word, " \t") orelse word.len], "ColumnTags"))
            p.setMessage(p.active, "ColumnTags: column tags are always shown now; the init line is ignored");
    }
}

test "an init file's retired ColumnTags line is said and ignored" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 });
    defer p.deinit();
    p.opts.startup_config = "ColumnTags\nWrap off\n";
    applyStartupConfig(p);
    try std.testing.expect(!p.settings.wrap);
    try std.testing.expect(p.columnBarHeight() > 0);
    const pane = p.panes[p.active].?;
    try std.testing.expectEqualStrings("ColumnTags: column tags are always shown now; the init line is ignored", pane.msg[0..pane.msg_len]);
}

pub fn runBuiltin(p: *Pardes, b: Builtin, id: usize, txt: []const u8, arg: ?[]const u8) void {
    runBuiltinFrom(p, b, id, txt, arg, false);
}

/// `runBuiltin` saying whether a gesture on the pane's body made it.
pub fn runBuiltinFrom(p: *Pardes, b: Builtin, id: usize, txt: []const u8, arg: ?[]const u8, from_body: bool) void {
    if (!normal.multiOnce(p)) return; // a builtin is per-keystroke, never per-cursor
    const pane = p.panes[id] orelse return;
    // A builtin says its own name before it runs, so a tagline click is
    // legible even when what it did is invisible. Whatever the builtin
    // then says for itself replaces the announcement.
    if (p.announce and p.settings.verbose and builtins.registry.announces(b)) {
        p.setMessage(id, @tagName(b));
        pane.msg_announcement = true;
    }
    const c: builtins.Ctx = .{ .p = p, .pane = pane, .id = id, .txt = txt, .arg = arg, .from_body = from_body };
    builtins.registry.dispatch(b, c);
}

pub fn applySettingBuiltin(p: *Pardes, setting: config.Runtime.Setting, arg: ?[]const u8) void {
    const previous_colors = p.settings.colors;
    const previous_context_style = p.settings.tree_context_tag_style;
    const previous_transition = p.settings.panel_transition;
    const previous_tagline_percent = p.settings.font.tagline_percent;
    switch (setting.action) {
        .theme => {
            const want = std.mem.trim(u8, arg orelse return, " \t\r\n");
            for (themes, 0..) |t, i| if (std.mem.eql(u8, t.name, want)) {
                colors.setThemeIndex(p, i);
                return;
            };
            // A config line is not answered on screen (applyStartupConfig
            // runs with announce off); a click or a ctl write is.
            if (!p.announce) return;
            var near: [96]u8 = undefined;
            var text: [200]u8 = undefined;
            return p.reportFailure(p.active, std.fmt.bufPrint(&text, "Theme: no theme \"{s}\"; like it: {s}; ThemeSel lists all", .{ want[0..@min(want.len, 40)], colors.themesNear(&near, want) }) catch "Theme: no such theme");
        },
        .font => {
            if (comptime !font_picker) return;
            const spec = config.Runtime.FontSpec.parse(arg orelse return) orelse return;
            const matches = fonts.list(p.scratch.allocator(), spec.name);
            if (matches.len == 0) return;
            if (!p.settings.requestFont(matches[0].path, matches[0].name, spec.size_hundredths)) return;
            p.font_request_taken = false;
        },
        // A shell that is no executable is refused, not taken and quietly
        // replaced at the next spawn; bare, it goes back to the default.
        .shell => {
            const want = std.mem.trim(u8, arg orelse "", " \t\r\n");
            if (want.len == 0) {
                p.settings.shell.requested.clear();
                p.settings.shell.pending = true;
                return;
            }
            if (comptime pardes.hosted) {
                var buf: [std.fs.max_path_bytes]u8 = undefined;
                if (@import("host_io.zig").Shell.find(want, &buf) == null) {
                    var text: [320]u8 = undefined;
                    return p.reportFailure(p.active, std.fmt.bufPrint(&text, "Shell: {s}: no executable by that name", .{want[0..@min(want.len, 255)]}) catch "Shell: no such executable");
                }
            }
            if (!p.settings.apply(setting, want) and p.announce) p.reportFailure(p.active, "Shell: does not take that value");
        },
        else => if (!p.settings.apply(setting, arg) and p.announce) {
            var text: [96]u8 = undefined;
            const takes = if (setting.action == .toggle) "takes on or off" else "does not take that value";
            p.reportFailure(p.active, std.fmt.bufPrint(&text, "{s}: {s}", .{ setting.word, takes }) catch takes);
        },
    }
    if (p.settings.colors != previous_colors) {
        for (p.panes) |slot| {
            const pane = slot orelse continue;
            if (pane.file) |*file| file.syntax_dirty = true;
        }
    }
    if (p.settings.tree_context_tag_style != previous_context_style) {
        for (p.panes, 0..) |slot, id| {
            p.surface.body_layers[id].rows = 0;
            const pane = slot orelse continue;
            pane.body_rows = 0;
            pane.body_visible_rows = 0;
            pane.context_row_limit = null;
            pane.wrap_n = 0;
        }
        p.abandonPanelAnimations();
    }
    const transition_changed = setting.action == .transition and
        p.settings.panel_transition != previous_transition;
    const tagline_metrics_changed = setting.action == .tagline_size and
        p.settings.font.tagline_percent != previous_tagline_percent;
    // Idle frames keep no frozen grid while transitions are off; the one
    // just drawn is the baseline the first transition starts from.
    if (transition_changed and previous_transition == .off)
        p.presentation.capturePrevious(p.gpa, &p.surface);
    if (transition_changed or tagline_metrics_changed) {
        p.abandonPanelAnimations();
    }
}

/// What a new pane is, and who asked: each rule places them differently.
/// `scratch` is New's, `fs` 9P's pane/new, `errors` a +Errors pane.
pub const NewPane = enum { scratch, fs, shell, doc, command, errors };

/// Put new pane `id` in the layout: every new pane comes through here, by
/// the `Placement` setting, and every one but a command pane takes the
/// keyboard. `from` is the pane that asked, `origin` the text it asked
/// from: null when a column tag, the workspace tag or 9P asked (acme's
/// t->w == nil).
pub fn placeNew(p: *Pardes, from: usize, origin: ?usize, id: usize, kind: NewPane) void {
    const asked = if (p.exec_column != null) null else origin;
    layout.compute(p);
    const before = p.rects;
    switch (p.settings.placement) {
        .acme => switch (kind) {
            // New: the bottom half of the last pane in its own column
            // (look.c:921-923, et->col).
            .scratch => layout.acmePlace(p, p.exec_column orelse columnOf(p, from), null, id),
            // +Errors, a command's output: the last column (util.c:94-98).
            .command, .errors => layout.acmePlace(p, p.ncol - 1, null, id),
            // makenewwindow(nil) for 9P's new (acme.c:877), else (t).
            .fs => layout.acmePlace(p, acmeColumn(p, from), null, id),
            .shell, .doc => layout.acmePlace(p, acmeColumn(p, from), asked, id),
        },
        .pardes => pardesPlace(p, from, id, kind),
    }
    // No pane is made shorter than its tag and two rows: where the place
    // chosen has not the room, the column's tallest pane gives it, and
    // where none can, the pane is refused, and closed at the step's end
    // (Pardes.unplaced) once whatever made it is done with it.
    if (!layout.placedRoomy(p, id, &before)) if (layout.findPane(p, id)) |f| {
        layout.removePane(p, id);
        for (p.col_panes[f.col][0..p.col_n[f.col]]) |k| p.rects[k] = before[k];
        layout.snapColWeights(p, f.col);
        if (!layout.splitTallest(p, f.col, id) or !layout.placedRoomy(p, id, &before)) {
            if (layout.findPane(p, id) == null) layout.insert(p, f.col, p.col_n[f.col], id);
            // +Errors goes wherever there is room, last column first; with
            // none, its maker says the text some other way (appendErrors).
            if (kind == .errors) {
                layout.removePane(p, id);
                var c = p.ncol;
                while (c > 0) {
                    c -= 1;
                    if (c == f.col) continue;
                    for (p.col_panes[c][0..p.col_n[c]]) |k| p.rects[k] = before[k];
                    layout.snapColWeights(p, c);
                    if (p.col_n[c] == 0) {
                        layout.insert(p, c, 0, id);
                        break;
                    }
                    if (layout.splitTallest(p, c, id) and layout.placedRoomy(p, id, &before)) break;
                    if (layout.findPane(p, id) != null) layout.removePane(p, id);
                } else {
                    layout.insert(p, f.col, p.col_n[f.col], id);
                    p.unplaced.set(id);
                    return;
                }
            } else {
                p.unplaced.set(id);
                p.reportError(from, "placement", error.NoPaneRoom);
                return;
            }
        }
    };
    if (kind == .command) return;
    tagline.exitHeader(p);
    p.active = id;
    if (layout.findPane(p, id)) |f| p.setActiveColumn(f.col);
}

/// acme's makenewwindow column (util.c:456-467): the column a command came
/// from (its tag's), else the active column, else the keyboard's pane's,
/// else the asking pane's.
fn acmeColumn(p: *Pardes, from: usize) usize {
    if (p.exec_column) |c| return c;
    if (p.activeColumn()) |c| return c;
    if (layout.findPane(p, p.active)) |f| return f.col;
    return columnOf(p, from);
}

fn columnOf(p: *Pardes, id: usize) usize {
    return if (layout.findPane(p, id)) |f| f.col else p.ncol - 1;
}

/// The placements pardes had before it took acme's: an empty column whose
/// tag asked, or has the keyboard, is filled; a scratch goes under the
/// asking pane, a shell under it or the nearest pane with room, a document
/// beside the last one read or in a column of its own, and a command pane
/// at the foot of the last column.
fn pardesPlace(p: *Pardes, from: usize, id: usize, kind: NewPane) void {
    const empty = if (p.exec_column orelse if (p.header_focus) p.header_column else null) |c|
        (if (c < p.ncol and p.col_n[c] == 0) c else null)
    else
        null;
    if (empty) |c| {
        layout.insert(p, c, 0, id);
        p.panes[id].?.vweight = 1;
        return;
    }
    const nt = p.panes[id].?;
    switch (kind) {
        .scratch, .fs => if (layout.findPane(p, from)) |sf| {
            layout.insert(p, sf.col, sf.idx + 1, id);
            layout.splitBelow(p, from, nt);
        },
        .shell => belowParent(p, from, id),
        .doc, .errors => pardesDoc(p, from, id),
        .command => {
            const rc = p.ncol - 1;
            if (p.col_n[rc] > 0) belowParent(p, p.col_panes[rc][p.col_n[rc] - 1], id) else layout.insert(p, rc, 0, id);
        },
    }
}

fn belowParent(p: *Pardes, from: usize, id: usize) void {
    const parent = layout.splitParent(p, from);
    const f = layout.findPane(p, parent).?;
    layout.insert(p, f.col, f.idx + 1, id);
    layout.splitBelow(p, parent, p.panes[id].?);
}

fn pardesDoc(p: *Pardes, from_id: usize, free: usize) void {
    const nt = p.panes[free].?;
    const doc = if (nt.file) |f| panes.Output.fileTraits(f.output).doc else true; // an image is a doc
    var src_id: ?usize = null;
    if (p.panes[from_id]) |src| if (if (src.file) |f| panes.Output.fileTraits(f.output).doc else src.image != null or src.hasPdf()) {
        src_id = from_id;
    };
    if (doc and src_id == null) {
        var n = p.njumps;
        while (n > 0) : (n -= 1) {
            const j = p.jumps[n - 1];
            const pp = p.panes[j.pane] orelse continue;
            if (pp.serial != j.serial) continue;
            if (if (pp.file) |f| panes.Output.fileTraits(f.output).doc else pp.image != null or pp.hasPdf()) {
                src_id = j.pane;
                break;
            }
        }
    }
    if (doc and src_id == null) for (p.panes, 0..) |sl, i| {
        if (sl) |pp| if (i != free and (if (pp.file) |f| panes.Output.fileTraits(f.output).doc else pp.image != null or pp.hasPdf())) {
            src_id = i;
            break;
        };
    };
    if (!doc) if (layout.findPane(p, from_id)) |sf| {
        layout.insert(p, sf.col, sf.idx + 1, free);
        layout.splitBelow(p, from_id, nt); // NOT splitParent: no bystander pays
        return;
    };
    if (src_id == null and doc and p.ncol < MAX_COLS and
        layout.columnFitsHalves(p, from_id, 100) and layout.splitColumn(p, from_id, free, true))
        return;
    // Without room for a first-document column, split the Look origin
    // just like Tty. Never displace (or evict) a top-left bystander.
    belowParent(p, src_id orelse from_id, free);
}

test "the acme chords act once per selection, not once on the primary" {
    const gpa = std.testing.allocator;
    const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 });
    defer p.deinit();
    while (p.nextEffect()) |_| {}
    // Two selections, each naming a DIFFERENT builtin, so what ran is visible
    // in the layout rather than in a shell nobody can read from a test.
    const pane = try p.setTestFile("Newcol\nNewcol\n");
    const ranges = [_]modal.Selection{
        .{ .anchor = 0, .head = 6 },
        .{ .anchor = 7, .head = 13 },
    };
    pane.body.setRanges(pane.file.?.content, &ranges, &.{}, 0, true);
    try std.testing.expectEqual(@as(u16, 1), pane.body.nsel);

    const before = p.ncol;
    p.update(.{ .key = .{ .cp = Key.tab } }); // config.exec_key: Exec
    // BOTH ran. Before this the chord read the primary range and dropped the
    // other cursor, so one keystroke over two cursors made one column.
    try std.testing.expectEqual(before + 2, p.ncol);
    // ...and the chord consumed the selection exactly as it does with one.
    try std.testing.expectEqual(@as(u16, 0), p.panes[0].?.body.nsel);
}

test "a switch clicked with a selection held flips unless the selection says on or off" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 });
    defer p.deinit();
    while (p.nextEffect()) |_| {}
    const before = p.settings.verbose;
    _ = execute(p, p.active, withArg(p, "Verbose", "some selected text"));
    try std.testing.expectEqual(!before, p.settings.verbose);
    _ = execute(p, p.active, withArg(p, "Verbose", "on"));
    try std.testing.expect(p.settings.verbose);
    _ = execute(p, p.active, withArg(p, "Verbose", " off\n"));
    try std.testing.expect(!p.settings.verbose);
    // A word that takes any argument still gets the selection.
    try std.testing.expectEqualStrings("Msg some text", withArg(p, "Msg", "some text"));
}