summaryrefslogtreecommitdiff
path: root/src/keys.zig
blob: 5be3a110a6766017fc759b6b91ccbec7cc54ef49 (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
//! The keyboard: a key's way through the session (handleKey), the leader's
//! chords, the window and tty prefixes, a question's answer, the modes'
//! cycle and the tty toggle, as mouse.zig is the mouse.
const std = @import("std");
const pardes = @import("pardes.zig");
const config = @import("config.zig");
const panes = @import("panes.zig");
const modal = @import("modal.zig");
const normal = @import("normal.zig");
const edit = @import("edit.zig");
const exec = @import("exec.zig");
const look = @import("look.zig");
const layout = @import("layout.zig");
const tagline = @import("tagline.zig");
const mouse = @import("mouse.zig");
const builtins = @import("builtins.zig");
const ctlfs = @import("ninep/tree.zig");
const Macro = @import("Macro.zig");
const Pipe = @import("Pipe.zig");
const Registers = @import("Registers.zig");
const Pardes = pardes.Pardes;
const Pane = panes.Pane;
const Text = panes.Text;
const Key = pardes.Key;
const hit = pardes.hit;
const MAX_COLS = pardes.MAX_COLS;
const BOX_H = pardes.BOX_H;
const builtin_rows = pardes.builtin_rows;
const test_api = pardes.test_api;
const frame_ns = pardes.frame_ns;

/// Cycle only the body modes supported by this pane.
pub fn cycleMode(p: *Pardes, id: usize) void {
    const pane = p.panes[id] orelse return;
    if (pane.file == null and !pane.isTerminal()) return;
    const previous = pane.body.mode;
    p.view().active = id;
    tagline.exitHeader(p);
    pane.focus = .body;
    pane.closePrompt();
    switch (previous) {
        .tty => {
            pane.body.mode = .normal;
            pane.body.normal.clear();
        },
        .normal => edit.enterInsert(p, &pane.body, .at, 1) catch |err| p.reportError(id, "edit", err),
        .insert => {
            edit.exitInsert(p, &pane.body);
            if (pane.isTerminal()) panes.terminal.enterTty(p, id);
        },
    }
}

/// One mode transition for the terminal tag command and the Ctrl-B chord.
pub fn toggleTty(p: *Pardes, id: usize) void {
    const pane = p.panes[id] orelse return;
    if (!pane.isTerminal()) return;
    p.view().active = id;
    tagline.exitHeader(p);
    pane.focus = .body;
    pane.closePrompt();
    if (pane.body.mode == .tty) {
        pane.body.mode = .normal;
        pane.body.normal.clear();
    } else panes.terminal.enterTty(p, id);
}

/// Type `keys` again (a macro, `.`): through the modal handling as
/// typed, except that no key leaves the text for pardes's own acts --
/// Esc does not hop panes, and Enter and Tab neither look nor execute.
pub fn replayKeys(p: *Pardes, keys: []const Macro.Stored) void {
    if (p.macro.replaying >= 8) return; // a macro typing itself
    p.macro.replaying += 1;
    defer p.macro.replaying -= 1;
    for (keys) |stored| {
        var buf: [4]u8 = undefined;
        handleKey(p, stored.typed(&buf));
    }
}

/// The choices the question pane `id` asks offers, space-separated
/// (`k j`, `a b`), or null when it asks none.
pub fn questionChoices(p: *const Pardes, id: usize, buf: []u8) ?[]const u8 {
    const asked = p.panes[id] orelse return null;
    switch (asked.prompt) {
        .del_side => return "k j",
        // Any path; `-` takes it back.
        .save => return "<path>",
        .repl_choice => {
            const ask = p.repl_ask orelse return null;
            var w = std.Io.Writer.fixed(buf);
            for (ask.offered, 0..) |serial, i| if (serial != 0) {
                if (w.buffered().len > 0) w.writeByte(' ') catch break; // the letters that fit
                w.writeByte(@intCast('a' + i)) catch break; // the letters that fit
            };
            return w.buffered();
        },
        else => return null,
    }
}

/// Answers the question pane `id` asks on its notice band (logged as
/// `ask <serial> <what> <choices>`): Del's side (`k` above, `j` below)
/// or the REPL to send to (its letter). A choice it offers answers it;
/// null, or one it does not offer, takes it back. A key answers it, or
/// `answer` on the pane's ctl, and the log says which, as `answer
/// <serial> <choice|->`; false when the pane asks nothing.
pub fn answerQuestion(p: *Pardes, id: usize, choice: ?u8) bool {
    const v = p.view();
    const asked = p.panes[id] orelse return false;
    var offered: [64]u8 = undefined;
    if (questionChoices(p, id, &offered)) |choices| {
        const chosen: ?u8 = if (choice) |c| (if (std.mem.indexOfScalar(u8, choices, c) != null and c != ' ') c else null) else null;
        var rec: [32]u8 = undefined;
        ctlfs.events.notePath(p, "answer", std.fmt.bufPrint(&rec, "{d} {c}", .{ asked.serial, chosen orelse '-' }) catch unreachable); // a u32 and a letter fit 32
    }
    switch (asked.prompt) {
        .repl_choice => {
            asked.prompt = .none;
            const ask = p.repl_ask orelse return true;
            p.repl_ask = null;
            defer p.gpa.free(ask.text);
            const letter = choice orelse return true;
            if (letter < 'a' or letter > 'z') return true;
            const serial = ask.offered[letter - 'a'];
            if (serial == 0) return true;
            // The pane offered, still that REPL and still running: it
            // may have closed or been rebound while the question stood.
            if (p.paneBySerial(serial)) |to| if (p.panes[to].?.repl) |r|
                if (r.lang == ask.lang and r.letter == letter) {
                    // Offered with no program running: said so, not sent.
                    if (!exec.replLive(p, to)) {
                        _ = exec.replGone(p, id, p.panes[to].?);
                        return true;
                    }
                    exec.sendToRepl(p, id, to, ask.text);
                    return true;
                };
            p.setMessage(id, "Repl: the REPL chosen is gone; nothing sent");
        },
        .del_side => {
            asked.prompt = .none;
            if (choice == 'k') exec.runBuiltin(p, .Del, id, "", "k");
            if (choice == 'j') exec.runBuiltin(p, .Del, id, "", "j");
            // Asked from window mode (`d`): the outline goes with the rows.
            if (v.window_pick == id and p.panes[id] == null) v.window_pick = if (v.header != null) null else v.active;
        },
        else => return false,
    }
    return true;
}

pub fn handleKey(p: *Pardes, key: Key) void {
    // A double-click is two clicks with nothing between them.
    p.view().last_click = null;
    if (p.macro.recording != 0 and p.macro.replaying == 0) Macro.append(&p.macro.recorded, p.gpa, key);
    // A question waiting on a pane takes the next key, whatever mode the
    // pane or a header edit is in: that key is its answer.
    for (p.panes, 0..) |slot, id| {
        const asked = slot orelse continue;
        switch (asked.prompt) {
            // Its letter sends it there; anything else takes it back.
            .repl_choice => _ = answerQuestion(p, id, if (key.ctrl or key.alt or key.cp > 'z' or key.cp < 'a') null else @intCast(key.cp)),
            .del_side => _ = answerQuestion(p, id, if (hit(key, config.del_above)) 'k' else if (hit(key, config.del_below)) 'j' else null),
            else => continue,
        }
        return;
    }
    if (p.view().window_pick != null) return layout.windowKey(p, key);
    const pane = p.panes[p.view().active] orelse return;
    layout.noteTyped(p);
    // In a raw terminal the two Escs swap: Esc backs out, and Shift-Esc is
    // the program's, sent as a plain Esc.
    const raw_esc = key.cp == Key.escape and !key.ctrl and !key.alt and
        pane.isTerminal() and pane.body.mode == .tty and pane.focus == .body and pane.prompt == .none and
        tagline.focusedHeader(p) == null;
    if (raw_esc and key.shift) {
        p.view().prefix = .none;
        panes.terminal.followOutput(pane);
        var plain = key;
        plain.shift = false;
        return panes.terminal.forwardKey(p, p.view().active, plain);
    }
    // Shift-Esc backs out of whatever the pane is in -- a prompt, insert
    // mode, a pending count, a raw program -- to the previous pane, as
    // Esc does from normal mode. Nothing under it sees the key.
    if (raw_esc or hit(key, config.back_out)) {
        p.view().prefix = .none;
        if (pane.prompt != .none) {
            pane.closePrompt();
            pane.focus = .body;
        }
        for ([_]*Text{ &pane.body, &pane.tag }) |t| {
            if (t.mode == .insert) edit.exitInsert(p, t);
            t.normal.clear();
            t.select = false;
        }
        tagline.exitHeader(p);
        return exec.runBuiltin(p, .Last, p.view().active, "", null);
    }
    // Alt-Down and Alt-Up in a pane's tag expand and collapse it, in
    // either mode: acme's Tagdown and Tagup (plan9port text.c:776).
    if (pane.focus == .tag and key.alt and !key.ctrl and (key.cp == Key.down or key.cp == Key.up) and tagline.focusedHeader(p) == null) {
        pane.tag_expanded = key.cp == Key.down;
        return;
    }
    // An open prompt takes the keys even when it answers for a header.
    const header = if (pane.prompt != .none) null else tagline.focusedHeader(p);
    if (header == null and pane.isTerminal() and pane.body.mode == .tty and pane.focus == .body and pane.prompt == .none) {
        p.view().prefix = .none;
        if (key.ctrl and !key.alt and key.cp == p.tty_toggle)
            return toggleTty(p, p.view().active);
        panes.terminal.followOutput(pane); // typing snaps back to live output
        // Paste stays the window's, the one exception to forwarding a raw
        // tty's keys: Ctrl-V types the register at the program and
        // Ctrl-Shift-V asks the desktop for its clipboard first. Forwarded,
        // they reach an application that reads the clipboard on its own
        // account instead — a coding agent goes there hunting for an image.
        // A host that folds Shift into the letter says the same thing.
        if (key.ctrl and !key.alt and (key.cp == 'v' or key.cp == 'V')) {
            if (key.shift or key.cp == 'V') return edit.clipRequest(p, p.view().active, .after);
            // With something in the register this is a paste. With nothing
            // in it the chord is the program's -- vim's visual block,
            // readline's quoted-insert -- and swallowing it would make
            // Ctrl-V a black hole in every full-screen application.
            if (p.registers.text(p.gpa, Registers.default)) |text| return edit.typeToTty(p, p.view().active, pane, text);
        }
        return panes.terminal.forwardKey(p, p.view().active, key);
    }
    // A kind's pane that takes keys takes them all, as a raw terminal
    // does; Esc too, first, when its kind is of 2.1 (a PDF's drops its
    // search), and not taken it leaves (and Shift-Esc, above, at once).
    if (header == null and pane.focus == .body and pane.prompt == .none) if (pane.addon) |slot| if (pardes.Kind.takesKeys(p, slot)) {
        p.view().prefix = .none;
        if (pardes.Kind.key(p, p.view().active, key)) return;
        if (key.cp == Key.escape and !key.ctrl and !key.alt) return exec.runBuiltin(p, .Last, p.view().active, "", null);
    };
    if (p.view().prefix == .leader) return leaderKey(p, key);
    if (p.view().prefix == .window) {
        p.view().prefix = .none;
        for (config.window_keys) |wk| {
            if (hit(key, &.{ wk.letter, wk.arrow })) return exec.runBuiltin(p, wk.cmd, p.view().active, "", null);
        }
        return;
    }
    // insert mode owns Ctrl-w (delete word backward, helix); outside raw
    // tty mode it enters window mode, or on a header prefixes a move
    // between the headers
    const t = header orelse if (pane.focus == .tag) &pane.tag else &pane.body;
    if (hit(key, config.window_prefix) and t.mode != .insert and (header != null or pane.prompt == .none)) {
        if (header != null) {
            p.view().prefix = .window;
            return;
        }
        return exec.runBuiltin(p, .Window, p.view().active, "", null);
    }
    // global window ops (any mode): Alt-n new terminal below, Alt-c move
    // the active terminal into a fresh column
    if (hit(key, config.new_shell_below)) {
        const free = p.freeSlot() orelse return p.reportError(p.view().active, "Term", error.NoPaneSlots);
        const nt = p.newShell(free, "") catch |err| return p.reportError(p.view().active, "Term", err);
        nt.greet = true;
        // From a tag, as a 9P new is: acme's t->w == nil.
        exec.placeNew(p, p.view().active, if (p.view().header != null) null else p.view().active, free, .shell);
        return;
    }
    for (config.jump_keys) |jk| {
        if (!hit(key, &.{jk.chord})) continue;
        tagline.exitHeader(p);
        return exec.runBuiltin(p, jk.cmd, p.view().active, "", null);
    }
    if (hit(key, config.pane_to_new_column)) {
        tagline.exitHeader(p);
        const f = layout.findPane(p, p.view().active).?;
        if (p.view().ncol < MAX_COLS and p.view().cols[f.col].n > 1) {
            _ = layout.splitColumn(p, p.view().active, p.view().active, false);
        }
        return;
    }
    const tty_toggle = key.ctrl and key.cp == p.tty_toggle;
    if (pane.isTerminal() and tty_toggle) {
        return toggleTty(p, p.view().active);
    }
    if (header == null and pane.prompt == .name) {
        // Enter or the execute key commits the draft and the keyboard
        // goes back to the body. Esc while typing keeps the draft,
        // pending, as Esc keeps any edit: Enter then renames, and a
        // second Esc drops it. Pending, no other key changes it.
        if (hit(key, config.look_key) or hit(key, config.exec_key)) {
            if (tagline.commitTagName(p, pane)) pane.focus = .body;
            return;
        }
        const pending = pane.input.mode != .insert;
        if (hit(key, config.escape) and pending) {
            pane.closePrompt();
            pane.focus = .body;
            return;
        }
        if (hit(key, config.escape) or pending) {
            pane.input.mode = .normal;
            p.setMessage(p.view().active, "name drafted: Enter renames the buffer, Esc drops the draft");
            return;
        }
        edit.handleInsert(p, &pane.input, key);
        return;
    }
    if (header == null and pane.prompt != .none) {
        if (hit(key, config.search_submit) or hit(key, config.escape)) {
            const submit = hit(key, config.search_submit);
            const target = panes.promptTarget(p, pane);
            switch (pane.prompt) {
                .pipe => if (submit) Pipe.submitPipe(p, p.view().active),
                .save => if (submit) exec.submitSave(p, p.view().active),
                .search => if (submit)
                    look.submitSearch(p, p.view().active)
                else if (normal.selRegexArmed(pane)) |_| if (target) |answered|
                    normal.applySelRegex(p, pane, answered, "", .select),
                .none, .del_side, .repl_choice, .name => unreachable,
            }
            pane.closePrompt();
            if (target) |answered| {
                answered.mode = .normal;
                answered.normal.clear();
            }
            return;
        }
        edit.handleInsert(p, &pane.input, key);
        if (normal.selRegexArmed(pane)) |a| if (panes.promptTarget(p, pane)) |answered| normal.applySelRegex(p, pane, answered, a.pat, a.mode);
        return;
    }
    if (t == &pane.body and pane.jump.items.len > 0) return normal.jumpKey(p, pane, t, key);
    // A query pane's line 1 answers Enter, Esc and the stepping keys
    // itself (Query.zig).
    if (t == &pane.body and header == null and pane.query != null and panes.Query.key(p, p.view().active, key)) return;
    if (t.mode == .normal and p.macro.replaying == 0 and (hit(key, config.look_key) or hit(key, config.exec_key))) {
        // A header's words are the workspace's and column's commands, so
        // Enter runs them there, as the execute key does.
        const header_word = t.what == .column or t.what == .workspace;
        const cmd = if (hit(key, config.look_key) and !header_word) config.look_cmd else config.exec_cmd;
        if (t.what != .body) {
            // An explicit selection, else the word under the cursor in the
            // text as it is shown: a tag's prefix is part of what a word is.
            const shown = p.scratch.allocator().dupe(u8, edit.flatSurface(p, t) catch |err| return p.reportError(p.view().active, "exec", err)) catch |err| return p.reportError(p.view().active, "exec", err);
            const range = t.primaryRange(shown, 0);
            const lo = @min(range.anchor, range.head);
            const hi = @max(range.anchor, range.head);
            const span: [2]usize = if (t.vsel.active and t.vsel.explicit)
                .{ lo, hi }
            else word: {
                const b = config.wordBounds(shown, modal.selectionCursor(shown, range));
                break :word .{ b.lo, b.hi };
            };
            const txt = shown[span[0]..span[1]];
            // A column tag's command acts on that column, empty or not.
            p.exec_column = if (header != null) p.headerColumn() else null;
            defer p.exec_column = null;
            p.exec_header = header != null;
            defer p.exec_header = false;
            // Out of the tag or header FIRST: Del frees the pane, Kill
            // and Restore the whole session.
            if (header != null) tagline.exitHeader(p) else pane.focus = .body;
            if (txt.len == 0) return;
            // A pane's tag word: an event reader hears it as a click on
            // it, at its place in the tag (flatSurface is the tag's text).
            if (header == null and t.what == .tag and
                mouse.reportRange(p, p.view().active, cmd, txt, true, .{ .q0 = @intCast(span[0]), .q1 = @intCast(span[1]) }, null)) return;
            exec.runBuiltin(p, cmd, p.view().active, "", txt);
            return;
        }
        edit.pinPaneCursor(p, &pane.body);
        const explicit = (if (pane.addon) |k| k.selection.len > 0 else false) or
            (pane.body.vsel.active and pane.body.vsel.explicit);
        if (explicit) {
            if (exec.chordEachSel(p, pane, cmd)) return;
            if (edit.currentSelText(p, pane)) |txt| {
                pane.body.vsel.active = false;
                pane.body.select = false;
                // The execute key on a body: text a bound REPL may take.
                exec.runBuiltinFrom(p, cmd, p.view().active, "", txt, true);
                return;
            }
        }
        // The cursor's word as a click there takes it: one expansion
        // (exec.operandAt), a diff line's address and all, and an
        // event reader told as a click tells it.
        const operand = exec.operandAt(p, pane, look.cursorWordSel(p, pane), false, cmd == config.look_cmd);
        mouse.dispatchPointerBuiltin(p, p.view().active, cmd, operand.text, .{ .on_tag = false, .operand = operand });
        return;
    }
    if (t.what == .tag and t.mode == .insert and tagline.typedIntoName(p, pane, key)) return;
    // A tag's prefix is read-only: a key whose edit reached into it
    // changes nothing, not even where the cursor is.
    const kept = .{ t.cur_row, t.cur_col, t.vsel };
    var kept_sels: [Text.max_selections - 1]Text.SelRange = undefined;
    const kept_n = t.nsel;
    @memcpy(kept_sels[0..kept_n], t.sels[0..kept_n]);
    t.refused = false;
    defer if (t.refused) {
        t.cur_row, t.cur_col, t.vsel = kept;
        t.restoreSels(kept_sels[0..kept_n]);
    };
    const was = t.mode;
    switch (t.mode) {
        .normal => normal.handleNormal(p, t, key),
        .insert => if (hit(key, config.escape) and !t.reg_wait)
            edit.exitInsert(p, t)
        else
            edit.handleInsert(p, t, key),
        .tty => panes.terminal.forwardKey(p, p.view().active, key),
    }
    // `.`'s log: the keys of the normal command that entered insert
    // mode, then everything typed until it is left
    if (p.macro.repeating) return;
    const m = &p.macro;
    switch (was) {
        .normal => {
            Macro.append(&m.command, p.gpa, key);
            if (t.mode == .insert) {
                m.last_insert.clearRetainingCapacity();
                m.last_insert.appendSlice(p.gpa, m.command.items) catch |err| p.reportError(p.view().active, "macro", err);
                m.typed_from = m.last_insert.items.len;
                m.inserting = true;
                m.command.clearRetainingCapacity();
            } else if (std.meta.eql(t.normal, modal.Normal.State{})) m.command.clearRetainingCapacity();
        },
        .insert => if (m.inserting) {
            Macro.append(&m.last_insert, p.gpa, key);
            if (t.mode != .insert) m.inserting = false;
        },
        .tty => {},
    }
}

/// Whether a leader path `keys` is the core's, or begins one of its
/// paths or is begun by one: a kind's word may not have it (Kind.zig).
pub fn leaderTaken(keys: []const u8) bool {
    for (config.leader_args) |la| if (std.mem.startsWith(u8, la.path, keys) or std.mem.startsWith(u8, keys, la.path)) return true;
    for (builtin_rows) |row| if (row.path) |path| if (std.mem.startsWith(u8, path, keys) or std.mem.startsWith(u8, keys, path)) return true;
    return keys.len > 0 and keys[0] == config.leader_help;
}

fn leaderKey(p: *Pardes, key: Key) void {
    const v = p.view();
    v.prefix = .none; // only "still a prefix" below re-arms it
    if (key.ctrl or key.alt or key.cp < 0x20 or key.cp > 0x7e) return;
    const c: u8 = @intCast(key.cp);
    if (c == config.leader_help) {
        panes.Output.openHelp(p, v.active, v.leader_keys[0..p.view().leader_n]) catch |err|
            p.reportError(v.active, "help", err);
        return;
    }
    if (v.leader_n >= v.leader_keys.len) return;
    v.leader_keys[v.leader_n] = c;
    v.leader_n += 1;
    const pfx = v.leader_keys[0..p.view().leader_n];
    // A path that runs a builtin with its argument (the query pane's
    // sources with no word of their own).
    for (config.leader_args) |la| if (std.mem.eql(u8, la.path, pfx)) return exec.runBuiltin(p, la.cmd, v.active, "", la.arg);
    for (config.leader_args) |la| if (std.mem.startsWith(u8, la.path, pfx)) {
        v.prefix = .leader;
    };
    // a path-less builtin is a row here too (it is the same index Help
    // reads), and SPC cannot reach one — so both scans skip it; and a
    // window's own word is no path in a terminal's view
    for (builtin_rows) |row| {
        if (!builtins.registry.here(p, row.cmd)) continue;
        if (std.mem.eql(u8, row.path orelse continue, pfx)) return exec.runBuiltin(p, row.cmd, v.active, "", null);
    }
    for (builtin_rows) |row| {
        if (!builtins.registry.here(p, row.cmd)) continue;
        if (std.mem.startsWith(u8, row.path orelse continue, pfx)) {
            v.prefix = .leader;
            return;
        }
    }
    // An addon's word, after the core's (a path the core has is no addon's).
    switch (p.kinds.leader(pfx)) {
        .word => |w| exec.runWord(p, v.active, w, w.name.slice(), ""),
        .prefix => v.prefix = .leader,
        .none => {},
    }
}

test "Esc back into a tty leaves its view at the prompt" {
    const gpa = std.testing.allocator;
    const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" });
    defer p.deinit();
    p.update(.{ .resize = .{ .cols = 80, .rows = 24 } });
    p.update(.{ .key = .{ .cp = 'n', .alt = true } }); // a shell under the doc
    const shell = p.view().active;
    const sp = p.panes[shell].?;
    try std.testing.expect(sp.isTerminal());

    // A click pins the modal cursor — one of the several ordinary ways to get a
    // pin, and the pin is what a shell's rows then scroll out from under.
    const r = p.view().rects[shell];
    p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = r.x + config.GUTTER + 1, .row = r.y + BOX_H } });
    p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = r.x + config.GUTTER + 1, .row = r.y + BOX_H } });
    try std.testing.expectEqual(shell, p.view().active);

    p.update(.{ .key = .{ .cp = 'b', .ctrl = true } });
    try std.testing.expectEqual(Text.Mode.tty, sp.body.mode);

    // tty mode follows output to the bottom, so a screenful and a half of it
    // rides the view down and leaves that pin far up in the scrollback.
    for (0..60) |i| {
        var buf: [32]u8 = undefined;
        p.update(.{ .output = .{ .pane = @intCast(shell), .bytes = std.fmt.bufPrint(&buf, "line {d}\r\n", .{i}) catch unreachable } });
    }
    p.sync();
    const live = sp.terminal.?.vt.screens.active.pages.scrollbar().offset;
    try std.testing.expect(live > 0);

    p.update(.{ .key = .{ .cp = Key.escape } }); // shell-prompt heuristic: out to the doc
    try std.testing.expect(p.view().active != shell);
    p.update(.{ .key = .{ .cp = Key.escape } }); // ...and back in
    p.sync();
    try std.testing.expectEqual(shell, p.view().active);

    try std.testing.expectEqual(live, sp.terminal.?.vt.screens.active.pages.scrollbar().offset);
}

test "Del from a key asks which neighbour takes the rows; nothing else asks" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 40 });
    defer p.deinit();
    var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer frame.deinit();
    const top = p.view().active;
    p.newScratchBelow(top);
    const mid = p.view().active;
    p.newScratchBelow(mid);
    const low = p.view().active;
    p.sync();
    var h = [_]u16{ p.view().rects[top].h, p.view().rects[mid].h, p.view().rects[low].h };

    // SPC d on the middle pane asks on its notice band, and closes nothing yet.
    p.view().active = mid;
    p.update(.{ .key = .{ .cp = ' ' } });
    p.update(.{ .key = .{ .cp = 'd' } });
    try std.testing.expect(p.panes[mid] != null);
    try std.testing.expectEqual(Pane.Prompt.del_side, p.panes[mid].?.prompt);
    p.clock.now_ns = p.panes[mid].?.question_due_ns; // shown once its delay is up
    _ = try p.render(frame.allocator());
    try std.testing.expectEqual(Pane.Notices.Kind.prompt, p.panes[mid].?.notices.kinds[p.panes[mid].?.notices.len - 1]);
    try std.testing.expectEqualStrings(config.del_question, p.panes[mid].?.promptText().?);
    // j: the pane below takes every row, the one above keeps its own.
    p.update(.{ .key = .{ .cp = 'j' } });
    try std.testing.expect(p.panes[mid] == null);
    try std.testing.expectEqual(h[0], p.view().rects[top].h);
    try std.testing.expectEqual(h[1] + h[2], p.view().rects[low].h);
    try std.testing.expectEqual(low, p.view().active); // focus follows the rows

    // Esc takes the question back and the pane stays; so does any other key,
    // and so does a click. A New goes to the column's foot, under low, which
    // is between two again.
    p.newScratchBelow(low);
    const foot = p.view().active;
    const again = low;
    p.view().active = again;
    p.sync();
    h = .{ p.view().rects[top].h, p.view().rects[again].h, p.view().rects[foot].h };
    try std.testing.expect(p.executeBuiltinLine(again, "Msg keep"));
    for ([_]Key{ .{ .cp = Key.escape }, .{ .cp = 'x' } }) |answer| {
        p.update(.{ .key = .{ .cp = ' ' } });
        p.update(.{ .key = .{ .cp = 'd' } });
        try std.testing.expectEqual(Pane.Prompt.del_side, p.panes[again].?.prompt);
        p.update(.{ .key = answer });
        try std.testing.expect(p.panes[again] != null);
        try std.testing.expectEqual(Pane.Prompt.none, p.panes[again].?.prompt);
    }
    p.update(.{ .key = .{ .cp = ' ' } });
    p.update(.{ .key = .{ .cp = 'd' } });
    const r = p.view().rects[again];
    p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = r.x + 5, .row = r.y + 3 } });
    p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = r.x + 5, .row = r.y + 3 } });
    try std.testing.expect(p.panes[again] != null);
    try std.testing.expectEqual(Pane.Prompt.none, p.panes[again].?.prompt);
    try std.testing.expectEqual(h[1], p.view().rects[again].h);

    // A word that is not a side closes nothing.
    try std.testing.expect(p.executeBuiltinLine(again, "Del x"));
    try std.testing.expectEqualStrings("Del: takes k, j or nothing", p.panes[again].?.msg[0..p.panes[again].?.msg_len]);
    try std.testing.expect(p.panes[again] != null);
    // DelAbove is Del k, and a line that is not a key never asks.
    try std.testing.expect(p.executeBuiltinLine(again, "DelAbove"));
    p.sync();
    try std.testing.expect(p.panes[again] == null);
    try std.testing.expectEqual(h[0] + h[1], p.view().rects[top].h);
    try std.testing.expectEqual(top, p.view().active);
    try std.testing.expectEqual(h[2], p.view().rects[foot].h);

    // A script answers the question on the pane's ctl, as the log's `ask`
    // names it: `answer -` takes it back, a side closes the pane toward it.
    p.newScratchBelow(foot);
    const tail = p.view().active;
    {
        const th = @import("ninep/testing.zig");
        const asked = foot;
        p.view().active = asked;
        p.sync();
        const serial = p.panes[asked].?.serial;
        const ctl = ctlfs.Node.of(serial, .ctl);
        try std.testing.expectEqual(ctlfs.E.INVAL, th.wr(p, ctl, "answer k\n").errno());
        p.update(.{ .key = .{ .cp = ' ' } });
        p.update(.{ .key = .{ .cp = 'd' } });
        var want: [32]u8 = undefined;
        try std.testing.expect(th.logHas(p, try std.fmt.bufPrint(&want, "ask {d} del k j\n", .{serial})));
        try std.testing.expectEqual(ctlfs.E.INVAL, th.wr(p, ctl, "answer x\n").errno());
        try std.testing.expectEqual(Pane.Prompt.del_side, p.panes[asked].?.prompt);
        try std.testing.expectEqual(ctlfs.Status.ok, th.wr(p, ctl, "answer -\n").reply.status);
        try std.testing.expect(p.panes[asked] != null and p.panes[asked].?.prompt == .none);
        try std.testing.expect(th.logHas(p, try std.fmt.bufPrint(&want, "answer {d} -\n", .{serial})));
        p.update(.{ .key = .{ .cp = ' ' } });
        p.update(.{ .key = .{ .cp = 'd' } });
        try std.testing.expectEqual(ctlfs.Status.ok, th.wr(p, ctl, "answer k\n").reply.status);
        try std.testing.expect(p.paneBySerial(serial) == null);
        try std.testing.expect(th.logHas(p, try std.fmt.bufPrint(&want, "answer {d} k\n", .{serial})));
    }

    // Bare Del from anything but a key closes at once and gives the rows up,
    // as it always has.
    p.newScratchBelow(tail);
    const last = p.view().active;
    const third = tail;
    p.sync();
    h = .{ p.view().rects[top].h, p.view().rects[third].h, p.view().rects[last].h };
    try std.testing.expect(p.executeBuiltinLine(third, "Del"));
    p.sync();
    try std.testing.expect(p.panes[third] == null);
    try std.testing.expectEqual(h[0] + h[1], p.view().rects[top].h);

    // With nothing open below, there is nothing to ask: SPC d closes at once.
    p.view().active = last;
    p.update(.{ .key = .{ .cp = ' ' } });
    p.update(.{ .key = .{ .cp = 'd' } });
    try std.testing.expect(p.panes[last] == null);
}

test "raw tty Esc backs out and Shift-Esc is the program's Esc" {
    const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24, .file = "mise.toml" });
    defer p.deinit();
    _ = exec.spawnTty(p, 0);
    const shell = p.view().active;
    const pane = p.panes[shell].?;
    var buf: [256]u8 = undefined;
    _ = test_api.ptyBytes(p, null, &buf);

    p.update(.{ .key = .{ .cp = 'x', .text = "x" } });
    _ = test_api.ptyBytes(p, null, &buf);
    p.update(.{ .key = .{ .cp = Key.escape } }); // past typed text too
    try std.testing.expectEqual(@as(usize, 0), p.view().active);
    try std.testing.expectEqualStrings("", test_api.ptyBytes(p, null, &buf));
    try std.testing.expectEqual(Text.Mode.tty, pane.body.mode);

    p.update(.{ .key = .{ .cp = Key.escape } }); // back into the shell
    try std.testing.expectEqual(shell, p.view().active);
    _ = test_api.ptyBytes(p, null, &buf);
    p.update(.{ .key = .{ .cp = Key.escape, .shift = true } });
    try std.testing.expectEqual(shell, p.view().active);
    try std.testing.expectEqualStrings("\x1b", test_api.ptyBytes(p, null, &buf));
}

test "the Del question shows only once its delay is up: a quick SPC d j never sees it" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 40 });
    defer p.deinit();
    var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer frame.deinit();
    const top = p.view().active;
    p.newScratchBelow(top);
    const mid = p.view().active;
    p.newScratchBelow(mid);
    p.sync();
    p.view().active = mid;
    p.clock.now_ns = 5 * std.time.ns_per_s;
    p.clock.stepped_ns = p.clock.now_ns;
    const asked_at = p.clock.now_ns;
    p.update(.{ .key = .{ .cp = ' ' } });
    p.update(.{ .key = .{ .cp = 'd' } });
    const pane = p.panes[mid].?;
    try std.testing.expectEqual(Pane.Prompt.del_side, pane.prompt);
    try std.testing.expectEqual(asked_at + config.del_question_delay_ns, pane.question_due_ns);
    // Asked, and nothing on the band yet.
    _ = try p.render(frame.allocator());
    for (pane.notices.kinds[0..pane.notices.len]) |kind| try std.testing.expect(kind != .prompt);
    // The loop wakes for it, at the end of the delay and not before.
    const wake = p.nextWake().?;
    try std.testing.expect(wake >= pane.question_due_ns and wake < pane.question_due_ns + frame_ns);
    p.clock.now_ns = pane.question_due_ns - 1;
    _ = try p.render(frame.allocator());
    for (pane.notices.kinds[0..pane.notices.len]) |kind| try std.testing.expect(kind != .prompt);
    // Its time come, it is the band's last line; stepped past it, nothing
    // more to wake for.
    p.clock.now_ns = wake;
    p.clock.stepped_ns = wake;
    _ = try p.render(frame.allocator());
    try std.testing.expectEqual(Pane.Notices.Kind.prompt, pane.notices.kinds[pane.notices.len - 1]);
    try std.testing.expect(p.nextWake() == null);
    // A key answers it either way, shown or not: Esc keeps the pane.
    p.update(.{ .key = .{ .cp = Key.escape } });
    try std.testing.expectEqual(Pane.Prompt.none, pane.prompt);
    try std.testing.expect(p.nextWake() == null);
    // A fast SPC d j: closed before the band ever showed the question.
    p.update(.{ .key = .{ .cp = ' ' } });
    p.update(.{ .key = .{ .cp = 'd' } });
    _ = try p.render(frame.allocator());
    for (pane.notices.kinds[0..pane.notices.len]) |kind| try std.testing.expect(kind != .prompt);
    p.update(.{ .key = .{ .cp = 'j' } });
    try std.testing.expect(p.panes[mid] == null);
}

test "raw tty Ctrl-B switches to editor mode without sending child input" {
    const p = try Pardes.init(std.testing.allocator, .{ .file = "mise.toml" });
    defer p.deinit();
    _ = exec.spawnTty(p, 0);
    const shell = p.view().active;
    p.sync();
    var buf: [256]u8 = undefined;
    _ = test_api.ptyBytes(p, null, &buf);
    p.update(.{ .key = .{ .cp = 'b', .ctrl = true } });
    try std.testing.expectEqual(shell, p.view().active);
    try std.testing.expectEqual(Text.Mode.normal, p.panes[shell].?.body.mode);
    try std.testing.expectEqualStrings("", test_api.ptyBytes(p, null, &buf));
}

test "raw tty forwards Ctrl letters and former global shortcuts to the child" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
    defer p.deinit();
    var buf: [256]u8 = undefined;
    _ = test_api.ptyBytes(p, null, &buf);
    try edit.setYank(p, "register text");
    for ('a'..'z' + 1) |letter| {
        if (letter == p.tty_toggle) continue; // editor/TTY mode shortcut
        if (letter == 'v') continue; // the window's paste, asserted just below
        p.update(.{ .key = .{ .cp = @intCast(letter), .ctrl = true } });
        const expected = [_]u8{@intCast(letter - 'a' + 1)};
        // The terminal encoder distinguishes Ctrl-I/M from Tab/Return.
        const encoded: []const u8 = switch (letter) {
            'i' => "\x1b[105;5u",
            'm' => "\x1b[109;5u",
            else => &expected,
        };
        try std.testing.expectEqualStrings(encoded, test_api.ptyBytes(p, null, &buf));
        try std.testing.expectEqual(@as(usize, 0), p.view().active);
        try std.testing.expectEqual(Text.Mode.tty, p.panes[0].?.body.mode);
        try std.testing.expect(p.view().prefix != .window and p.view().clip_pending == null);
    }
    // ...and the two paste chords are the exception: Ctrl-V types the register
    // at the program, Ctrl-Shift-V asks the desktop first and types nothing yet.
    p.update(.{ .key = .{ .cp = 'v', .ctrl = true } });
    try std.testing.expectEqualStrings("register text", test_api.ptyBytes(p, null, &buf));
    try std.testing.expect(p.view().clip_pending == null);
    p.update(.{ .key = .{ .cp = 'v', .ctrl = true, .shift = true } });
    try std.testing.expectEqualStrings("", test_api.ptyBytes(p, null, &buf));
    try std.testing.expect(p.view().clip_pending != null);
    const unopened = p.freeSlot(); // whatever the boot layout already used
    for ([_]u8{ 'n', 'c' }) |letter| {
        p.update(.{ .key = .{ .cp = letter, .alt = true } });
        const expected = [_]u8{ 0x1b, letter };
        try std.testing.expectEqualStrings(&expected, test_api.ptyBytes(p, null, &buf));
        try std.testing.expectEqual(@as(usize, 0), p.view().active);
        try std.testing.expectEqual(unopened, p.freeSlot());
    }
    p.update(.{ .key = .{ .cp = Key.up } });
    try std.testing.expectEqualStrings("\x1b[A", test_api.ptyBytes(p, null, &buf));
    p.panes[0].?.terminal.?.vt.modes.set(.cursor_keys, true);
    p.update(.{ .key = .{ .cp = Key.up } });
    try std.testing.expectEqualStrings("\x1bOA", test_api.ptyBytes(p, null, &buf));
    p.update(.{ .key = .{ .cp = Key.left, .ctrl = true } });
    try std.testing.expectEqualStrings("\x1b[1;5D", test_api.ptyBytes(p, null, &buf));
}

test "s in a header selects in the header's own text" {
    const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 12, .tty_only = true });
    defer p.deinit();
    const pane = try p.setTestFile("body col\n");
    tagline.enterHeader(p, null);
    p.update(.{ .key = .{ .cp = 'x' } });
    p.update(.{ .key = .{ .cp = 's' } });
    try std.testing.expect(pane.prompt == .search and pane.prompt_for == .workspace);
    // the prompt takes the keys while the header keeps the keyboard
    p.update(.{ .key = .{ .cp = 'c', .text = "col" } });
    p.update(.{ .key = .{ .cp = Key.enter } });
    try std.testing.expect(p.view().header != null and pane.prompt == .none);
    var ranges: [Text.max_selections]modal.Selection = undefined;
    const text = try edit.flatSurface(p, &p.global_tag);
    const got = p.global_tag.ranges(text, 0, &ranges);
    try std.testing.expectEqual(@as(usize, 2), got.n); // Newcol, Joincol
    try std.testing.expectEqual(@as(u16, 0), pane.body.nsel);
}