//! 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("root.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 bindings = @import("bindings.zig"); const TagState = @import("TagState.zig"); const Prompt = @import("Prompt.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.editor(), &pane.body, .at, 1) catch |err| p.reportError(.at(id), "edit", err), .insert => { edit.exitInsert(p.editor(), &pane.body); if (pane.isTerminal()) enterTty(p, id); }, } } /// Raw tty mode, the keys the program's: the shell's cursor first moved to /// where the edit cursor was on its prompt line (cursor keys, as a click /// there would), unless the pointer holds a selection to keep. pub fn enterTty(p: *Pardes, id: usize) void { const pane = p.panes[id] orelse return; const selected = pane.rawPointerText(pane.sel[@backingInt(config.select_button)]) != null; if (!selected and pane.body.cur_pinned) if (pane.terminal) |state| { if (panes.Term.promptMoves(state, pane.gridRow(pane.body.cur_row), pane.body.cur_col)) |moves| { for (0..moves.left) |_| p.emitWrite(id, "\x1b[D"); for (0..moves.right) |_| p.emitWrite(id, "\x1b[C"); } }; pane.body.mode = .tty; pane.followOutput(); // entering raw mode is a request for the live shell pane.body.vsel.active = false; pane.body.nsel = 0; // The raw renderer follows the live cursor. A captured mouse selection // keeps its modal endpoint for the next return to editor mode. pane.body.cur_pinned = selected; pane.body.select = false; pane.body.restore_cursor = false; pane.body.sticky_col = -1; pane.body.normal.clear(); } /// One key for the program that owns a raw terminal, its pty write queued. pub fn forwardKey(p: *Pardes, id: usize, key: Key) void { const pane = p.panes[id] orelse return; const state = pane.terminal orelse return; // A key's text has no bound of its own (an input method's commit, a // paste as one key): past the stack's room the encoding grows on the // heap, and emitWrite cuts it into writes. var room: [256]u8 = undefined; var first: std.heap.BufferFirstAllocator = .init(&room, p.gpa); var out: std.Io.Writer.Allocating = .init(first.allocator()); defer out.deinit(); panes.Term.key(state, key, &out.writer) catch |err| return p.reportError(.at(id), "key", err); if (out.written().len > 0) p.emitWrite(id, out.written()); } /// 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 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 "", .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 `): 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 /// `; 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(.at(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 root this key strikes starts its which-key delay; one it ends // takes its level away (TagState). defer TagState.follow(p); // 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) catch |err| p.reportError(.at(p.view().active), "macro", err); // 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; } // A background question SPC e gave the keyboard: one of its answers' // keys answers it (Diff leaves it asking), Esc leaves it waiting, and // nothing else gets past it (pick-ui SPEC §10.4). if (p.view().answering != 0) answering: { const v = p.view(); const at = p.paneBySerial(v.answering) orelse break :answering; const i = p.messages.waiting(p.panes[at].?) orelse break :answering; if (key.cp == Key.escape and !key.ctrl and !key.alt) { v.answering = 0; p.needs_frame = true; return; } if (key.ctrl or key.alt or key.cp > 0x7f) return; if (pardes.Messages.answer(p, i, @intCast(key.cp)) and key.cp != 'd') v.answering = 0; return; } p.view().answering = 0; // A tag in a typing state takes every key (TagState: Help, describe-key). if (p.view().tag_state.kind != .rest) return tagStateKey(p, key); Prompt.keyAtRest(p, key); @import("Pick.zig").keyAtRest(p, key); // Esc takes a hover's ghost lines away (SPEC §3.5) before anything else // it does. if (p.lsp_ask.hover != null and hit(key, config.escape)) { p.lsp_ask.hover = null; 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; pane.followOutput(); var plain = key; plain.shift = false; return 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.editor(), 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); pane.followOutput(); // 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 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(.at(p.view().active), "Term", error.NoPaneSlots); const nt = p.newShell(free, "") catch |err| return p.reportError(.at(p.view().active), "Term", err); nt.greet = true; // From a tag, as a 9P new is: acme's t->w == nil. layout.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(.at(p.view().active), "name drafted: Enter renames the buffer, Esc drops the draft"); return; } edit.handleInsert(p.editor(), &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.editor(), &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 (header == null) if (TagState.current(p, p.view())) |cur| if (cur.root != .leader and cur.root != .window) { if (prefixKey(p, t, cur, key)) 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.editor(), t) catch |err| return p.reportError(.at(p.view().active), "exec", err)) catch |err| return p.reportError(.at(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]]; // On a word of the pane's walk, the step's Look or Exec, as a // click there (SPEC §6.3). if (header == null and t.what == .tag) if (tagline.trailAt(p, pane, modal.selectionCursor(shown, range))) |step| { pane.focus = .body; if (cmd == config.look_cmd) pardes.Trail.lookStep(p, p.view().active, step) else pardes.Trail.execStep(p, p.view().active, step); return; }; // 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.editor(), &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, .insert => _ = normal.textKey(p.editor(), t, key), .tty => 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) catch |err| p.reportError(.at(p.view().active), "macro", err); if (t.mode == .insert) { m.last_insert.clearRetainingCapacity(); m.last_insert.appendSlice(p.gpa, m.command.items) catch |err| p.reportError(.at(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) catch |err| p.reportError(.at(p.view().active), "macro", err); 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; } /// A key in SPC's level: which-key's own (levelKey), else the child it /// names. A group goes down a level; a leaf runs and remembers it ran /// (TagState.used); a key the level has no child for is struck and the /// level stays; any other key (Esc) leaves it. fn leaderKey(p: *Pardes, key: Key) void { const v = p.view(); switch (levelKey(p, .leader, v.leader_keys[0..v.leader_n], key)) { .taken => return, .up => { if (v.leader_n == 0) v.prefix = .none else v.leader_n -= 1; v.tag_state.hi = 0; v.tag_state.miss = 0; }, .take => |c| leaderTake(p, c), .pass => { if (key.ctrl or key.alt or key.cp < 0x20 or key.cp > 0x7e) { v.prefix = .none; return; } leaderTake(p, @intCast(key.cp)); }, } } fn leaderTake(p: *Pardes, c: u8) void { const v = p.view(); const s = &v.tag_state; v.prefix = .none; // only "still a level" below re-arms it // `SPC ?`: Help over every root's leaves; `?` down a level, Help for // that level's (SPEC §4.5). if (c == config.leader_help) return TagState.openHelp(p, if (v.leader_n == 0) null else .leader, v.leader_keys[0..v.leader_n]); const path = v.leader_keys[0..v.leader_n]; var children: [bindings.max_children]bindings.Child = undefined; const child = for (bindings.level(p, .leader, path, &children)) |child| { if (child.key == c) break child; } else { v.prefix = .leader; s.miss = c; return; }; s.miss = 0; if (child.group) { v.prefix = .leader; if (v.leader_n == v.leader_keys.len) return; v.leader_keys[v.leader_n] = c; v.leader_n += 1; s.hi = 0; return; } TagState.ran(v, .leader, path, c); if (child.word) |w| return exec.runWord(p, v.active, w, w.name.slice(), ""); switch (child.node.?.leaf.?) { .builtin => |b| exec.runBuiltin(p, b, v.active, "", null), .arg => |a| exec.runBuiltin(p, config.leader_args[a].cmd, v.active, "", config.leader_args[a].arg), .role => unreachable, // SPC's leaves are words } } /// A key in a tag's typing state: Esc back to rest; Enter runs the row, /// typed as its keys; the rows' cursor; the field; Backspace on an empty /// field back to the level `?` was struck from. fn tagStateKey(p: *Pardes, key: Key) void { const v = p.view(); const s = &v.tag_state; if (s.kind == .prompt) return Prompt.key(p, key); if (s.kind == .pick and hit(key, config.escape) and @import("Pick.zig").closeHistory(p)) return; if (TagState.hostOf(p) == null or hit(key, config.escape)) return TagState.toRest(p); switch (s.kind) { .rest, .prompt => unreachable, .describe => { const plain = !key.ctrl and !key.alt; if (plain and key.cp == Key.enter and s.found) { var out: [16]Key = undefined; var path: [8]u8 = undefined; const n = s.scope_n; @memcpy(path[0..n], s.scope[0..n]); const typed = bindings.keysOf(s.scope_root.?, path[0..n], &out); TagState.toRest(p); for (typed) |k| handleKey(p, k); return; } if (plain and key.cp == Key.backspace) { if (s.scope_n > 0 and s.scope_root != null) { s.scope_n -= 1; } else s.scope_root = null; if (s.scope_root == null) s.scope_n = 0; s.found = false; s.missed = false; return; } TagState.describeKey(p, key); }, .pick => return @import("Pick.zig").key(p, key), .rename => return @import("lsp/Ask.zig").renameKey(p, key), .help => { const plain = !key.ctrl and !key.alt; if (plain and key.cp == Key.enter) { if (s.nhits == 0) return; var buf: [TagState.row_max]u8 = undefined; const leaf = TagState.helpLeaf(p, s.hits[s.rows.at], &buf); var out: [16]Key = undefined; const typed = bindings.keysOf(leaf.root, leaf.path, &out); TagState.toRest(p); for (typed) |k| handleKey(p, k); return; } if (plain and key.cp == Key.backspace and s.field.len == 0) return helpBack(p); if (s.rows.key(key, s.nhits)) return; if (s.field.key(key)) TagState.filter(p); }, } } /// Help left by Backspace on its empty field: the level it was struck /// from, unrolled, as `?` found it; rest from `SPC ?`. fn helpBack(p: *Pardes) void { const v = p.view(); const s = &v.tag_state; const root = s.scope_root orelse .leader; var path: [4]u8 = undefined; const n = s.scope_n; @memcpy(path[0..n], s.scope[0..n]); TagState.toRest(p); const pane = p.panes[v.active] orelse return; switch (root) { .leader => { v.prefix = .leader; @memcpy(v.leader_keys[0..n], path[0..n]); v.leader_n = n; }, .goto, .match, .view, .view_sticky, .next, .prev => { const t = if (pane.focus == .tag) &pane.tag else &pane.body; t.normal.prefix = switch (root) { .goto => .goto_prefix, .match => .match_prefix, .view, .view_sticky => .view_prefix, .next => .next_prefix, .prev => .prev_prefix, else => unreachable, }; t.normal.sticky = root == .view_sticky; }, .window, .register => return, } s.root = root; s.unrolled = true; } /// What a key does to a which-key level before its root reads it: `up` a /// level (Backspace, and Left or Alt-h unrolled), `take` a child (Enter: /// the cursor's, or rolled the leaf the group ran last; Right or Alt-l /// unrolled: the cursor's group), `taken` (Down unrolls, then moves the /// cursor; Up moves it, and on the first row rolls up), or `pass`: the /// root's own key. A key a root binds is its own (helix's z Down scrolls). const LevelStep = union(enum) { pass, taken, up, take: u8 }; fn levelKey(p: *Pardes, root: bindings.Root, path: []const u8, key: Key) LevelStep { const s = &p.view().tag_state; var buf: [bindings.max_children]bindings.Child = undefined; const children = bindings.level(p, root, path, &buf); if (children.len == 0) return .pass; const node = bindings.nodeAt(root, path); const used = if (node) |n| s.used[n.group] else 0; const plain = !key.ctrl and !key.alt; const down = (plain and key.cp == Key.down) or (key.ctrl and !key.alt and key.cp == 'j'); const up = (plain and key.cp == Key.up) or (key.ctrl and !key.alt and key.cp == 'k'); const right = (plain and key.cp == Key.right) or (key.alt and !key.ctrl and key.cp == 'l'); const left = (plain and key.cp == Key.left) or (key.alt and !key.ctrl and key.cp == 'h'); if ((root == .view or root == .view_sticky) and plain and (key.cp == Key.down or key.cp == Key.up)) return .pass; if (plain and key.cp == Key.backspace) return .up; // The cursor: its child, else the leaf the group ran last, else the first. var at: usize = 0; for (children, 0..) |c, i| if (c.key == (if (s.hi != 0) s.hi else used)) { at = i; }; if (down) { if (!s.unrolled) { s.unrolled = true; } else at = (at + 1) % children.len; s.hi = children[at].key; return .taken; } if (up) { if (s.unrolled and at == 0) s.unrolled = false else if (s.unrolled) s.hi = children[at - 1].key; return .taken; } if (s.unrolled and right) return if (children[at].group) .{ .take = children[at].key } else .taken; if (s.unrolled and left) return .up; if (plain and key.cp == Key.enter) { if (s.unrolled) return .{ .take = children[at].key }; return if (used != 0) .{ .take = used } else .taken; } return .pass; } /// A key while a helix prefix waits in text `t` (g m z Z [ ]): which-key's /// own, else the prefix's, the leaf it runs remembered. True when taken here. fn prefixKey(p: *Pardes, t: *Text, cur: TagState.Current, key: Key) bool { const root = cur.root; if (root != .register and key.cp == config.leader_help and !key.ctrl and !key.alt) { TagState.openHelp(p, root, ""); return true; } // `"` and a register's verbs: Esc goes to rest (normal mode's would // name the register, or leave the pane). if (root == .register and hit(key, config.escape)) { t.normal.clear(); return true; } switch (levelKey(p, root, cur.path, key)) { .taken => return true, .up => { t.normal = .{}; // A register's verbs go back up to the registers (SPEC §9). if (root == .register and cur.path.len > 0) { t.normal.prefix = .register_prefix; p.view().tag_state.hi = 0; } return true; }, .take => |c| { handleKey(p, .{ .cp = c }); return true; }, .pass => { if (!key.ctrl and !key.alt and key.cp >= 0x20 and key.cp < 0x7f) { const k: u8 = @intCast(key.cp); var buf: [2]u8 = .{ 0, k }; if (cur.path.len > 0) buf[0] = cur.path[0]; const here = if (cur.path.len > 0) buf[0..2] else buf[1..2]; if (bindings.nodeAt(root, here) != null) TagState.ran(p.view(), root, cur.path, k); // A register named: its verbs, rolled, the cursor afresh. if (root == .register) { p.view().tag_state.hi = 0; p.view().tag_state.unrolled = false; } } return false; }, } } test "Esc back into a tty leaves its view at the prompt" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell, opened by a key 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 = .at(shell), .bytes = std.fmt.bufPrint(&buf, "line {d}\r\n", .{i}) catch unreachable } }); } p.sync(); const live = sp.termTop(); 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.termTop()); } 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.messages.saidBy(p.panes[again].?)); 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/harness.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" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell, opened by a key 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); // Its time is the next advance's (the host's clock, in its pump). try std.testing.expectEqual(Pane.question_asked, pane.question_due_ns); p.advance(asked_at); 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" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell 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.editor(), "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)); _ = pardes.Term.feed(&p.outside, p.panes[0].?.terminal.?, "\x1b[?1h", &.{}, &.{}, &.{}, &.{}); // DECCKM 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 = 'i', .text = "i" } }); 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.editor(), &p.global_tag); const got = p.global_tag.ranges(text, 0, &ranges); try std.testing.expectEqual(@as(usize, 2), got.n); // Find, Exit try std.testing.expectEqual(@as(u16, 0), pane.body.nsel); }