Skip to main content

escriba_keymap/
lib.rs

1//! `escriba-keymap` — mode-aware keybinding dispatch.
2
3extern crate self as escriba_keymap;
4
5use escriba_search::{CaretMove, Direction as SearchDirection};
6use std::collections::HashMap;
7
8use escriba_core::{
9    Action, CountedAction, InsertAt, Mode, Motion, Operator, TextObject, ViewAlign,
10};
11use escriba_mode::ModalState;
12use serde::{Deserialize, Serialize};
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
15pub enum Key {
16    Char(char),
17    Esc,
18    Enter,
19    Tab,
20    Backspace,
21    Delete,
22    Left,
23    Right,
24    Up,
25    Down,
26    PageUp,
27    PageDown,
28    Home,
29    End,
30    Ctrl(char),
31    Alt(char),
32    /// A function key. Discarded at the door until now
33    /// (`escriba-input`: `KeyCode::F(_) => return None`), so `<F5>` could be
34    /// declared and never arrive.
35    F(u8),
36    /// Anything the shorthands above cannot say: more than one modifier,
37    /// `Shift` as a modifier rather than a capital letter, `Super`/`Cmd`.
38    ///
39    /// `Ctrl(char)` and `Alt(char)` fold the modifier INTO the key, so they
40    /// can carry exactly one. The translator has always computed all four
41    /// modifier flags and then thrown `shift` and `meta` away for want of
42    /// somewhere to put them; this is that somewhere.
43    ///
44    /// Carries `awase::Hotkey` directly rather than a parallel spelling —
45    /// escriba's vocabulary widens by consuming the fleet's, not by growing
46    /// a fifth one.
47    Chord(awase::Hotkey),
48}
49
50#[derive(Debug, Clone, Serialize, Deserialize)]
51pub struct Binding {
52    pub action: Action,
53    pub description: String,
54}
55
56impl Binding {
57    #[must_use]
58    pub fn new(action: Action, description: impl Into<String>) -> Self {
59        Self {
60            action,
61            description: description.into(),
62        }
63    }
64}
65
66/// A binding that will not do what its author intended.
67///
68/// Recorded at BIND time rather than discovered later, because both kinds are
69/// silent by construction: a reserved chord never receives its event, and an
70/// overwritten binding simply stops existing. Neither produces an error at
71/// the moment it happens, and both present as "that key is broken".
72#[derive(Debug, Clone, PartialEq, Eq)]
73pub enum Collision {
74    /// Something outside escriba owns this chord — the OS, the window
75    /// manager, the terminal. The binding can never fire.
76    ///
77    /// Not arbitrable: no amount of reordering inside escriba changes it.
78    Reserved {
79        mode: Mode,
80        key: String,
81        description: String,
82        /// Who took it and what for.
83        why: String,
84    },
85    /// A later binding displaced an earlier one for the same chord.
86    ///
87    /// Sometimes intended — the shipped rc deliberately overrides defaults —
88    /// which is why this is REPORTED rather than refused. But it is reported,
89    /// because "my plugin's key stopped working" has no other explanation
90    /// available to an operator.
91    Displaced {
92        mode: Mode,
93        key: String,
94        replaced: String,
95        with: String,
96    },
97}
98
99impl Collision {
100    /// One line an operator can act on.
101    #[must_use]
102    pub fn report(&self) -> String {
103        match self {
104            Self::Reserved {
105                mode,
106                key,
107                description,
108                why,
109            } => format!("{mode:?} {key} ({description}) — {why}"),
110            Self::Displaced {
111                mode,
112                key,
113                replaced,
114                with,
115            } => format!("{mode:?} {key} — \"{replaced}\" was replaced by \"{with}\""),
116        }
117    }
118
119    /// Can this binding ever fire?
120    #[must_use]
121    pub const fn is_fatal(&self) -> bool {
122        matches!(self, Self::Reserved { .. })
123    }
124}
125
126/// What `dispatch` does with a key INSTEAD of consulting the binding table.
127///
128/// Named so a reader can tell the three apart: they look alike from the
129/// dispatcher's side (all three return before `lookup`) and are completely
130/// different to an operator trying to bind the key.
131#[derive(Debug, Clone, Copy, PartialEq, Eq)]
132pub enum Preempted {
133    /// Normal mode: the key is composing a count (`5` of `5dd`).
134    Count,
135    /// Insert mode: a printable character types itself.
136    SelfInsert,
137    /// Insert mode: `<CR>` opens a line.
138    Newline,
139    /// Command mode: a printable character types into the prompt.
140    PromptInsert,
141}
142
143impl Preempted {
144    /// What `dispatch` answers. Kept beside the classification so the two
145    /// cannot drift — the whole point of hoisting this out of `dispatch`.
146    fn resolved(self, key: &Key) -> CountedAction {
147        match self {
148            Self::Count => CountedAction::once(Action::Pending),
149            Self::SelfInsert | Self::PromptInsert => match key {
150                Key::Char(c) => CountedAction::once(Action::InsertChar(*c)),
151                // Unreachable via `preemption`, which only returns these two
152                // for `Key::Char`. Answered rather than `unreachable!()`: a
153                // dispatcher that panics on an unexpected key is a worse
154                // failure than one that declines it.
155                _ => CountedAction::once(Action::Pending),
156            },
157            Self::Newline => CountedAction::once(Action::InsertChar('\n')),
158        }
159    }
160}
161
162/// WHETHER `dispatch` preempts a key, and whether it always does.
163///
164/// The distinction is load-bearing for reachability: `1`–`9` in Normal are
165/// preempted unconditionally, so a binding for one can never fire. `0` is
166/// preempted only while a count is being typed — which is exactly why `0` is
167/// bindable, and IS bound, to `Motion::LineStart`.
168#[derive(Debug, Clone, Copy, PartialEq, Eq)]
169pub enum Preemption {
170    /// The key never reaches the binding table. A declaration is dead.
171    Always(Preempted),
172    /// The key reaches the table unless a count is pending. Bindable.
173    WhenCounting(Preempted),
174}
175
176/// Does `dispatch` answer `(mode, key)` before the binding table is consulted?
177///
178/// **The single statement of the rule.** [`Keymap::dispatch`] reads it to
179/// answer keys; anything auditing whether a DECLARATION could ever fire reads
180/// it to say so. Before it existed the rule lived in three inline `if mode ==`
181/// blocks inside `dispatch`, visible to nothing else, so a binding for a bare
182/// printable character in Insert mode parsed, applied, reported as applied —
183/// and was dead on arrival with nowhere to learn that from.
184///
185/// Total over the preempting cases; everything else falls through to `None`,
186/// which is the safe direction (a key wrongly called reachable shows up as a
187/// binding that does not work, a key wrongly called dead hides a working one).
188#[must_use]
189pub fn preemption(mode: Mode, key: &Key) -> Option<Preemption> {
190    match (mode, key) {
191        (Mode::Normal, Key::Char('0')) => Some(Preemption::WhenCounting(Preempted::Count)),
192        (Mode::Normal, Key::Char(c)) if c.is_ascii_digit() => {
193            Some(Preemption::Always(Preempted::Count))
194        }
195        (Mode::Insert, Key::Char(_)) => Some(Preemption::Always(Preempted::SelfInsert)),
196        (Mode::Insert, Key::Enter) => Some(Preemption::Always(Preempted::Newline)),
197        (Mode::Command, Key::Char(_)) => Some(Preemption::Always(Preempted::PromptInsert)),
198        _ => None,
199    }
200}
201
202#[derive(Debug, Clone)]
203pub struct Keymap {
204    bindings: HashMap<(Mode, Key), Binding>,
205    /// Multi-key sequence bindings (`<leader>ff`, `gg`, `<C-w>h`).
206    /// Keyed by the full key sequence; resolved by the runtime's
207    /// pending-stroke loop ([`lookup_sequence`](Keymap::lookup_sequence)
208    /// + [`is_sequence_prefix`](Keymap::is_sequence_prefix)).
209    sequences: HashMap<(Mode, Vec<Key>), Binding>,
210    /// The prefix `<leader>` resolves to at sequence-apply time.
211    leader: Key,
212    /// Chords the world owns. Consulted on every bind, so a binding that
213    /// cannot fire is known at CONSTRUCTION rather than discovered by an
214    /// operator pressing a dead key.
215    reserved: awase::Reserved,
216    /// Every collision seen while building this keymap, in bind order.
217    collisions: Vec<Collision>,
218}
219
220impl Default for Keymap {
221    fn default() -> Self {
222        Self {
223            bindings: HashMap::new(),
224            sequences: HashMap::new(),
225            reserved: awase::Reserved::fleet_darwin(),
226            collisions: Vec::new(),
227            // blnvim's leader is comma; escriba ships blnvim-parity
228            // defaults, so the prefix users press matches muscle memory.
229            leader: Key::Char(','),
230        }
231    }
232}
233
234impl Keymap {
235    #[must_use]
236    pub fn new() -> Self {
237        Self::default()
238    }
239
240    #[must_use]
241    pub fn default_vim() -> Self {
242        let mut m = Self::new();
243        let nm = |m: &mut Keymap, k: Key, a: Action, d: &'static str| m.bind(Mode::Normal, k, a, d);
244        nm(
245            &mut m,
246            Key::Char('h'),
247            Action::Move(Motion::Left),
248            "move left",
249        );
250        nm(
251            &mut m,
252            Key::Char('l'),
253            Action::Move(Motion::Right),
254            "move right",
255        );
256        nm(
257            &mut m,
258            Key::Char('j'),
259            Action::Move(Motion::Down),
260            "move down",
261        );
262        nm(&mut m, Key::Char('k'), Action::Move(Motion::Up), "move up");
263        nm(
264            &mut m,
265            Key::Char('w'),
266            Action::Move(Motion::WordStartNext),
267            "word forward",
268        );
269        nm(
270            &mut m,
271            Key::Char('b'),
272            Action::Move(Motion::WordStartPrev),
273            "word back",
274        );
275        nm(
276            &mut m,
277            Key::Char('e'),
278            Action::Move(Motion::WordEndNext),
279            "word end",
280        );
281        nm(
282            &mut m,
283            Key::Char('0'),
284            Action::Move(Motion::LineStart),
285            "line start",
286        );
287        nm(
288            &mut m,
289            Key::Char('$'),
290            Action::Move(Motion::LineEnd),
291            "line end",
292        );
293        nm(
294            &mut m,
295            Key::Char('G'),
296            Action::Move(Motion::DocEnd),
297            "doc end",
298        );
299        // ── the rest of the vim movement suite ────────────────────────
300        //
301        // Everything below was a MOTION escriba already had a vocabulary for
302        // and no key to reach. Grouped as a table because the interesting
303        // content is the key→motion pairing, and eighteen `nm(...)` calls
304        // spelled out is eighteen places to mistype one.
305        //
306        // `f`/`F`/`t`/`T` are NOT here: their operand is the next keystroke,
307        // so the runtime claims them before the keymap is consulted (see
308        // `EditorState::consume_find_key`). `;`/`,` ARE here — they carry no
309        // operand, only a direction.
310        for (key, motion, label) in [
311            (Key::Char('W'), Motion::BigWordStartNext, "WORD forward"),
312            (Key::Char('E'), Motion::BigWordEndNext, "WORD end"),
313            (Key::Char('B'), Motion::BigWordStartPrev, "WORD back"),
314            (Key::Char('^'), Motion::LineFirstNonBlank, "first non-blank"),
315            (Key::Char('_'), Motion::LineFirstNonBlank, "first non-blank"),
316            (Key::Char('|'), Motion::Column(1), "to column"),
317            (
318                Key::Char('+'),
319                Motion::LineDownFirstNonBlank,
320                "next line, first non-blank",
321            ),
322            (
323                Key::Char('-'),
324                Motion::LineUpFirstNonBlank,
325                "previous line, first non-blank",
326            ),
327            (Key::Char('%'), Motion::MatchPair, "matching bracket"),
328            (Key::Char('}'), Motion::ParagraphNext, "next paragraph"),
329            (Key::Char('{'), Motion::ParagraphPrev, "previous paragraph"),
330            (Key::Char(')'), Motion::SentenceNext, "next sentence"),
331            (Key::Char('('), Motion::SentencePrev, "previous sentence"),
332            (Key::Char('H'), Motion::ScreenTop, "screen top"),
333            (Key::Char('M'), Motion::ScreenMiddle, "screen middle"),
334            (Key::Char('L'), Motion::ScreenBottom, "screen bottom"),
335            (
336                Key::Char(';'),
337                Motion::RepeatFind { reverse: false },
338                "repeat find",
339            ),
340            // `,` is NOT here, and the reason is a real conflict rather than
341            // an oversight: escriba's shipped leader IS `,` (blnvim parity),
342            // and this keymap's rule is that a single binding WINS over a
343            // sequence prefix — so binding `,` would silently kill all 93
344            // `<leader>…` bindings the catalog ships. The leader keeps it.
345            // Reverse-repeat is reachable as `:action "find-reverse"` for an
346            // rc that chooses a different leader, and `F`/`T` remain the
347            // direct way to search backwards.
348            (Key::Ctrl('f'), Motion::PageDown, "page down"),
349            (Key::Ctrl('b'), Motion::PageUp, "page up"),
350            (Key::Ctrl('d'), Motion::HalfPageDown, "half page down"),
351            // `<C-u>` IS free in Normal — the erase verb of the same name is
352            // bound in Insert and Command only, and a binding is per-mode.
353            // It was listed as "conflicted" once; it never was.
354            (Key::Ctrl('u'), Motion::HalfPageUp, "half page up"),
355            (Key::Enter, Motion::LineDownFirstNonBlank, "next line"),
356        ] {
357            nm(&mut m, key, Action::Move(motion), label);
358        }
359        // `zt` / `zz` / `zb` — re-frame the window, leaving the cursor put.
360        // Sequences, and `z` is bound to nothing on its own, so there is no
361        // single binding for these to lose to.
362        for (k, align, label) in [
363            (Key::Char('t'), ViewAlign::Top, "cursor line to top"),
364            (Key::Char('z'), ViewAlign::Center, "centre cursor line"),
365            (Key::Char('b'), ViewAlign::Bottom, "cursor line to bottom"),
366        ] {
367            m.bind_sequence(
368                Mode::Normal,
369                vec![Key::Char('z'), k],
370                Action::ScrollView(align),
371                label,
372            );
373        }
374        // The `g`-prefixed motions.
375        //
376        // **`gg` was never bound** (found 2026-08-13). `G` was, and the only
377        // `gg` in the repo was a test that BOUND IT ITSELF before pressing it
378        // — so the test proved the sequence machinery worked and said nothing
379        // about the default keymap, and vim's most-pressed motion did nothing
380        // in the shipped editor. A test that constructs the thing it is
381        // checking cannot fail the way the product is broken.
382        for (k, motion, label) in [
383            (Key::Char('g'), Motion::DocStart, "doc start"),
384            (Key::Char('e'), Motion::WordEndPrev, "previous word end"),
385            (Key::Char('E'), Motion::BigWordEndPrev, "previous WORD end"),
386            (Key::Char('_'), Motion::LineLastNonBlank, "last non-blank"),
387        ] {
388            m.bind_sequence(
389                Mode::Normal,
390                vec![Key::Char('g'), k],
391                Action::Move(motion),
392                label,
393            );
394        }
395        // Operators — `d`/`c`/`y` arm the operator-pending FSM; the next
396        // motion composes (e.g. `dw`, `c$`, `y0`).
397        nm(
398            &mut m,
399            Key::Char('d'),
400            Action::Operator(Operator::Delete),
401            "delete (operator)",
402        );
403        nm(
404            &mut m,
405            Key::Char('c'),
406            Action::Operator(Operator::Change),
407            "change (operator)",
408        );
409        nm(
410            &mut m,
411            Key::Char('y'),
412            Action::Operator(Operator::Yank),
413            "yank (operator)",
414        );
415        // Structural Lisp motions — Alt-prefixed like emacs paredit.
416        nm(
417            &mut m,
418            Key::Alt('f'),
419            Action::Move(Motion::ForwardSexp),
420            "forward sexp",
421        );
422        nm(
423            &mut m,
424            Key::Alt('b'),
425            Action::Move(Motion::BackwardSexp),
426            "backward sexp",
427        );
428        nm(
429            &mut m,
430            Key::Alt('u'),
431            Action::Move(Motion::UpList),
432            "up list",
433        );
434        nm(
435            &mut m,
436            Key::Alt('d'),
437            Action::Move(Motion::DownList),
438            "down list",
439        );
440        // ── Insert entry — the whole vim family, one row each ──────────
441        //
442        // Until 2026-08-12 this was ONE row: `i`. `a`, `A`, `I`, `o` and `O`
443        // were unbound, so `A` on a line resolved to `Action::Pending` and did
444        // nothing at all — no move, no mode change, no message.
445        //
446        // Binding bare `a` and `i` is safe DESPITE the text objects (`daw`,
447        // `di(`) that also begin with them, and the reason is worth stating
448        // because it is the one thing that makes this table correct: the
449        // runtime's `consume_object_key` runs BEFORE the sequence stepper and
450        // before this table, and claims `i`/`a` only while an operator is
451        // armed (`escriba-runtime`, `OpState::Awaiting`). With nothing pending
452        // they fall through to here. `escriba-keymap`'s own "single bindings
453        // win over sequence prefixes" rule would otherwise have shadowed every
454        // text object the moment `a` got a binding.
455        //
456        // Every entry is `EnterInsert`, never `ChangeMode(Insert)`: the caret
457        // placement IS the difference between the six, and a mode change
458        // cannot carry it.
459        for (key, at, label) in [
460            (Key::Char('i'), InsertAt::Caret, "insert"),
461            (Key::Char('I'), InsertAt::FirstNonBlank, "first non-blank"),
462            (Key::Char('a'), InsertAt::AfterCaret, "append"),
463            (Key::Char('A'), InsertAt::LineEnd, "append at end of line"),
464            (Key::Char('o'), InsertAt::OpenBelow, "open line below"),
465            (Key::Char('O'), InsertAt::OpenAbove, "open line above"),
466        ] {
467            nm(&mut m, key, Action::EnterInsert(at), label);
468        }
469        nm(
470            &mut m,
471            Key::Char('v'),
472            Action::ChangeMode(Mode::Visual),
473            "visual",
474        );
475        nm(
476            &mut m,
477            Key::Char('V'),
478            Action::ChangeMode(Mode::VisualLine),
479            "visual line",
480        );
481        nm(
482            &mut m,
483            Key::Char(':'),
484            Action::ChangeMode(Mode::Command),
485            "command",
486        );
487        nm(&mut m, Key::Char('u'), Action::Undo, "undo");
488        nm(
489            &mut m,
490            Key::Char('.'),
491            Action::RepeatLastChange,
492            "repeat last change",
493        );
494        nm(&mut m, Key::Ctrl('r'), Action::Redo, "redo");
495        // Insert → Normal on Esc.
496        m.bind(
497            Mode::Insert,
498            Key::Esc,
499            Action::ChangeMode(Mode::Normal),
500            "to normal",
501        );
502        // ── Insert-mode editing ───────────────────────────────────────
503        // Until 2026-08-09 `Esc` above was the ONLY Insert-mode binding, and
504        // `dispatch` short-circuits `Key::Char` + `Key::Enter` before the
505        // table is consulted — so every key below fell through to
506        // `Action::Pending` and did nothing. Insert mode could be typed into
507        // and never corrected: no erase, no caret movement. The keys were not
508        // "unimplemented", they were unbound; `Action::Backspace`'s executor
509        // had been waiting for a caller.
510        m.bind(
511            Mode::Insert,
512            Key::Backspace,
513            Action::Backspace,
514            "erase one char",
515        );
516        m.bind(
517            Mode::Insert,
518            Key::Delete,
519            Action::DeleteForward,
520            "delete char at caret",
521        );
522        // The bigger erases. `<BS>`/`<Del>` landed first and these were left
523        // behind for a day, which made Insert mode able to erase one character
524        // at a time and nothing larger — a mis-typed word had to be dismantled
525        // letter by letter. They share the erase family's routing, so the
526        // binding is the whole change: the runtime already knows whether a
527        // prompt is open.
528        m.bind(
529            Mode::Insert,
530            Key::Ctrl('w'),
531            Action::DeleteWordBefore,
532            "erase word before caret",
533        );
534        m.bind(
535            Mode::Insert,
536            Key::Ctrl('u'),
537            Action::DeleteToLineStart,
538            "erase to line start",
539        );
540        // `<C-h>` IS backspace: terminals send 0x08 for it, and vim treats the
541        // two as one key in Insert. Whether a given terminal reports the
542        // physical Backspace as `Backspace` or as `Ctrl('h')` is the
543        // terminal's business, not the operator's — binding both is what makes
544        // the answer stop mattering.
545        m.bind(
546            Mode::Insert,
547            Key::Ctrl('h'),
548            Action::Backspace,
549            "erase one char",
550        );
551        // Arrows in Insert are vi-compatible (vim's `esckeys`) and are what
552        // "edit it" means to anyone who did not grow up on hjkl. They reuse
553        // the ordinary motions, so the cursor-clamp + viewport-follow
554        // invariants come along unchanged.
555        for (key, motion, label) in [
556            (Key::Left, Motion::Left, "caret left"),
557            (Key::Right, Motion::Right, "caret right"),
558            (Key::Up, Motion::Up, "caret up"),
559            (Key::Down, Motion::Down, "caret down"),
560            (Key::Home, Motion::LineStart, "caret to line start"),
561            (Key::End, Motion::LineEnd, "caret to line end"),
562        ] {
563            m.bind(Mode::Insert, key, Action::Move(motion), label);
564        }
565        m.bind(
566            Mode::Command,
567            Key::Esc,
568            Action::ChangeMode(Mode::Normal),
569            "abort",
570        );
571        m.bind(Mode::Command, Key::Enter, Action::SubmitCommand, "submit");
572        m.bind(
573            Mode::Command,
574            Key::Up,
575            Action::PromptHistory { back: true },
576            "older search",
577        );
578        m.bind(
579            Mode::Command,
580            Key::Down,
581            Action::PromptHistory { back: false },
582            "newer search",
583        );
584        m.bind(
585            Mode::Command,
586            Key::Backspace,
587            Action::Backspace,
588            "erase one char",
589        );
590        m.bind(
591            Mode::Command,
592            Key::Delete,
593            Action::DeleteForward,
594            "delete char at caret",
595        );
596        // Caret editing inside the prompt. Without these the prompt is
597        // append-only, so a typo in the middle of a pattern can only be fixed
598        // by deleting everything back to it.
599        m.bind(
600            Mode::Command,
601            Key::Left,
602            Action::PromptCaret {
603                to: CaretMove::Left,
604            },
605            "caret left",
606        );
607        m.bind(
608            Mode::Command,
609            Key::Right,
610            Action::PromptCaret {
611                to: CaretMove::Right,
612            },
613            "caret right",
614        );
615        m.bind(
616            Mode::Command,
617            Key::Home,
618            Action::PromptCaret {
619                to: CaretMove::Start,
620            },
621            "caret to start",
622        );
623        m.bind(
624            Mode::Command,
625            Key::End,
626            Action::PromptCaret { to: CaretMove::End },
627            "caret to end",
628        );
629        m.bind(
630            Mode::Command,
631            Key::Ctrl('w'),
632            Action::DeleteWordBefore,
633            "delete word before caret",
634        );
635        // Walk the preview without committing — `/pat` then `<C-g><C-g>` is
636        // `/pat<CR>nn`, except Escape still takes you home.
637        m.bind(
638            Mode::Command,
639            Key::Ctrl('g'),
640            Action::SearchPreviewStep { forward: true },
641            "preview next match",
642        );
643        m.bind(
644            Mode::Command,
645            Key::Ctrl('t'),
646            Action::SearchPreviewStep { forward: false },
647            "preview previous match",
648        );
649        m.bind(
650            Mode::Command,
651            Key::Ctrl('u'),
652            Action::DeleteToLineStart,
653            "clear to start",
654        );
655
656        // ── search ────────────────────────────────────────────────────
657        // `/` and `?` open the prompt; `<CR>` is the existing SubmitCommand,
658        // which the runtime routes to the search when a search prompt is open.
659        // That routing is typed (Option<Prompt>), not a mode flag to forget.
660        nm(
661            &mut m,
662            Key::Char('/'),
663            Action::SearchOpen(SearchDirection::Forward),
664            "search forward",
665        );
666        nm(
667            &mut m,
668            Key::Char('?'),
669            Action::SearchOpen(SearchDirection::Backward),
670            "search backward",
671        );
672        // `n`/`N` are MOTIONS, not standalone jumps. Binding them to
673        // `Action::Move` is what makes `dn` / `yN` compose — the
674        // operator-pending machine only recognises `Action::Move` as an
675        // operand. `Action::SearchRepeat` remains a valid action (a user rc or
676        // the tatara-lisp binding table may name it) and the runtime routes it
677        // through the same executor, so there is exactly one code path.
678        nm(
679            &mut m,
680            Key::Char('n'),
681            Action::Move(Motion::SearchNext),
682            "next match",
683        );
684        nm(
685            &mut m,
686            Key::Char('N'),
687            Action::Move(Motion::SearchPrev),
688            "previous match",
689        );
690
691        // `gn` / `gN` — the match as an OBJECT, so `cgn` changes the whole
692        // match and `.` repeats that on the next one.
693        m.bind_sequence(
694            Mode::Normal,
695            vec![Key::Char('g'), Key::Char('n')],
696            Action::TextObject(TextObject::NextMatch),
697            "next match (object)",
698        );
699        m.bind_sequence(
700            Mode::Normal,
701            vec![Key::Char('g'), Key::Char('N')],
702            Action::TextObject(TextObject::PrevMatch),
703            "previous match (object)",
704        );
705
706        // ── `ff` — REMOVED 2026-08-13, and this is the deciding it was
707        // waiting for ────────────────────────────────────────────────────
708        //
709        // `ff` was blnvim's bare format binding, taken here as a SEQUENCE with
710        // a note saying it cost nothing "because `f` (find-char) is not
711        // implemented", and that when `f` landed it would need deciding.
712        // `f` has landed. It wins: `f` is the character search in every vi
713        // lineage, and it is claimed by the runtime BEFORE the sequence
714        // stepper (its operand is a keystroke, not a binding), so leaving the
715        // sequence here would not have conflicted — it would have been dead
716        // table entry nobody could reach, which is worse than a conflict.
717        //
718        // Nothing is lost: `lsp.format` is the SAME command name the catalog
719        // already binds from `<leader>lf`, `:Format` and a `BufWritePre` hook.
720        // The verb keeps three routes; only this fourth spelling is gone.
721
722        // ── jumplist ──────────────────────────────────────────────────
723        // The return ticket for every far jump above. Without it a committed
724        // search is a one-way door.
725        nm(&mut m, Key::Ctrl('o'), Action::JumpBack, "jump back");
726        nm(&mut m, Key::Ctrl('i'), Action::JumpForward, "jump forward");
727        nm(
728            &mut m,
729            Key::Char('*'),
730            Action::SearchWord { reverse: false },
731            "search word forward",
732        );
733        nm(
734            &mut m,
735            Key::Char('#'),
736            Action::SearchWord { reverse: true },
737            "search word backward",
738        );
739        m.bind(
740            Mode::Visual,
741            Key::Esc,
742            Action::ChangeMode(Mode::Normal),
743            "to normal",
744        );
745        m.bind(
746            Mode::VisualLine,
747            Key::Esc,
748            Action::ChangeMode(Mode::Normal),
749            "to normal",
750        );
751        m
752    }
753
754    pub fn bind(&mut self, mode: Mode, key: Key, action: Action, desc: impl Into<String>) {
755        let binding = Binding::new(action, desc);
756        self.note_collisions(mode, std::slice::from_ref(&key), &binding);
757        self.bindings.insert((mode, key), binding);
758    }
759
760    /// Record anything about this bind that will surprise its author.
761    ///
762    /// Called on every bind, single or sequence. Detection is DEFAULT-ON and
763    /// costs one hash lookup plus one conversion — a keymap that only tells
764    /// you about collisions when asked is a keymap nobody asks.
765    fn note_collisions(&mut self, mode: Mode, keys: &[Key], binding: &Binding) {
766        let Some(first) = keys.first() else { return };
767        let spelled = format!("{keys:?}");
768
769        // (1) Does the world own it? For a sequence this is its OPENER —
770        // a sequence whose first key never arrives can never begin.
771        if let Some(hk) = to_hotkey(first) {
772            if let Some(why) = self.reserved.refuse(&hk) {
773                self.collisions.push(Collision::Reserved {
774                    mode,
775                    key: spelled.clone(),
776                    description: binding.description.clone(),
777                    why,
778                });
779            }
780        }
781
782        // (2) Is something already here? `HashMap::insert` returns the old
783        // value and every caller dropped it, so a displaced binding left no
784        // trace at all.
785        let existing = if keys.len() == 1 {
786            self.bindings
787                .get(&(mode, first.clone()))
788                .map(|b| &b.description)
789        } else {
790            self.sequences
791                .get(&(mode, keys.to_vec()))
792                .map(|b| &b.description)
793        };
794        if let Some(replaced) = existing {
795            self.collisions.push(Collision::Displaced {
796                mode,
797                key: spelled,
798                replaced: replaced.clone(),
799                with: binding.description.clone(),
800            });
801        }
802    }
803
804    /// Every collision recorded while this keymap was built.
805    ///
806    /// Read by `--list-rc` and reported at boot. An empty slice is the
807    /// claim "every binding escriba ships can actually fire".
808    #[must_use]
809    pub fn collisions(&self) -> &[Collision] {
810        &self.collisions
811    }
812
813    /// Collisions that mean a key can NEVER fire, as opposed to one that was
814    /// deliberately overridden.
815    pub fn fatal_collisions(&self) -> impl Iterator<Item = &Collision> {
816        self.collisions.iter().filter(|c| c.is_fatal())
817    }
818
819    #[must_use]
820    pub fn lookup(&self, mode: Mode, key: &Key) -> Option<&Binding> {
821        self.bindings.get(&(mode, key.clone()))
822    }
823
824    /// The leader key — what `<leader>` resolves to when a sequence
825    /// binding is applied. Defaults to `,` (blnvim parity).
826    #[must_use]
827    pub fn leader(&self) -> &Key {
828        &self.leader
829    }
830
831    /// Override the leader key. Applied before sequence bindings so
832    /// `<leader>`-prefixed specs resolve against the chosen prefix.
833    pub fn set_leader(&mut self, key: Key) {
834        self.leader = key;
835    }
836
837    /// Bind a multi-key SEQUENCE — `<leader>ff` →
838    /// `[Char(','), Char('f'), Char('f')]`, `gg` →
839    /// `[Char('g'), Char('g')]`. A length-1 sequence delegates to
840    /// [`bind`](Keymap::bind) so callers never special-case it; an
841    /// empty sequence is a no-op.
842    pub fn bind_sequence(
843        &mut self,
844        mode: Mode,
845        keys: Vec<Key>,
846        action: Action,
847        desc: impl Into<String>,
848    ) {
849        match keys.as_slice() {
850            [] => {}
851            [single] => self.bind(mode, single.clone(), action, desc),
852            _ => {
853                let binding = Binding::new(action, desc);
854                self.note_collisions(mode, &keys, &binding);
855                self.sequences.insert((mode, keys), binding);
856            }
857        }
858    }
859
860    /// Exact-match lookup for a full key sequence.
861    #[must_use]
862    pub fn lookup_sequence(&self, mode: Mode, keys: &[Key]) -> Option<&Binding> {
863        self.sequences.get(&(mode, keys.to_vec()))
864    }
865
866    /// Does any bound sequence in `mode` STRICTLY extend `prefix`
867    /// (i.e. `prefix` is a proper prefix of a longer bound sequence)?
868    /// Drives the runtime's pending-stroke state: a partial sequence
869    /// that is still a live prefix is held pending rather than
870    /// dispatched. Linear scan — fine at fleet sequence counts; a
871    /// trie is a later optimization if profiling ever asks for it.
872    #[must_use]
873    pub fn is_sequence_prefix(&self, mode: Mode, prefix: &[Key]) -> bool {
874        self.sequences
875            .keys()
876            .any(|(m, seq)| *m == mode && seq.len() > prefix.len() && seq.starts_with(prefix))
877    }
878
879    /// Every bound sequence in `mode` that STRICTLY extends `prefix`.
880    ///
881    /// [`is_sequence_prefix`](Self::is_sequence_prefix) answers the same
882    /// question with a `bool` and throws away the matches it just found. Two
883    /// consumers need those matches:
884    ///
885    /// - a **which-key popup**, which must show what continues `<leader>`;
886    /// - a **reserved-chord audit**, which cannot check bindings it cannot
887    ///   enumerate — and `sequences` is private, so from outside this crate
888    ///   the multi-key half of the keymap was invisible.
889    ///
890    /// Same linear scan as `is_sequence_prefix`, so this costs nothing extra;
891    /// a trie is the same later optimization for both.
892    ///
893    /// Pass an empty `prefix` for every sequence in the mode.
894    #[must_use]
895    pub fn sequences_extending(&self, mode: Mode, prefix: &[Key]) -> Vec<(&[Key], &Binding)> {
896        let mut v: Vec<(&[Key], &Binding)> = self
897            .sequences
898            .iter()
899            .filter(|((m, seq), _)| {
900                *m == mode && seq.len() > prefix.len() && seq.starts_with(prefix)
901            })
902            .map(|((_, seq), b)| (seq.as_slice(), b))
903            .collect();
904        // Sorted, because a which-key popup in HashMap order is a popup that
905        // reorders itself between presses.
906        v.sort_by(|a, b| format!("{:?}", a.0).cmp(&format!("{:?}", b.0)));
907        v
908    }
909
910    /// Count of bound multi-key sequences — for `--keymap` / doctor.
911    #[must_use]
912    pub fn sequence_len(&self) -> usize {
913        self.sequences.len()
914    }
915
916    #[must_use]
917    pub fn dispatch(&self, state: &ModalState, key: &Key) -> CountedAction {
918        let mode = state.mode();
919        // The preemption rule is stated ONCE, in `preemption` below, and read
920        // twice: here, to answer the key, and by `escriba-banzuke`, to decide
921        // whether a DECLARATION for this pair could ever fire. It used to be
922        // three inline `if mode ==` blocks that only this function could see,
923        // so an rc binding a bare `j` in Insert parsed, applied, reported as
924        // applied — and was dead. Nothing could say so, because the fact that
925        // made it dead lived inside the dispatcher.
926        match preemption(mode, key) {
927            Some(Preemption::Always(p)) => return p.resolved(key),
928            Some(Preemption::WhenCounting(p)) if state.pending_count().is_some() => {
929                return p.resolved(key);
930            }
931            _ => {}
932        }
933        if let Some(b) = self.lookup(mode, key) {
934            return CountedAction::repeated(state.pending_count().unwrap_or(1), b.action.clone());
935        }
936        CountedAction::once(Action::Pending)
937    }
938
939    #[must_use]
940    pub fn len(&self) -> usize {
941        self.bindings.len()
942    }
943
944    #[must_use]
945    pub fn is_empty(&self) -> bool {
946        self.bindings.is_empty()
947    }
948
949    /// Sorted view over every binding — for `escriba --keymap` and palettes.
950    #[must_use]
951    pub fn entries_sorted(&self) -> Vec<(&Mode, &Key, &Binding)> {
952        let mut v: Vec<_> = self.bindings.iter().map(|((m, k), b)| (m, k, b)).collect();
953        v.sort_by(|a, b| {
954            (a.0.as_str(), format!("{:?}", a.1)).cmp(&(b.0.as_str(), format!("{:?}", b.1)))
955        });
956        v
957    }
958}
959
960#[cfg(test)]
961mod tests {
962    use super::*;
963
964    #[test]
965    fn default_vim_has_bindings() {
966        let k = Keymap::default_vim();
967        assert!(k.len() > 10);
968        assert!(k.lookup(Mode::Normal, &Key::Char('h')).is_some());
969        assert!(k.lookup(Mode::Insert, &Key::Esc).is_some());
970        assert!(k.lookup(Mode::Normal, &Key::Alt('f')).is_some());
971    }
972
973    #[test]
974    fn dispatch_normal_motion() {
975        let k = Keymap::default_vim();
976        let s = ModalState::new();
977        let a = k.dispatch(&s, &Key::Char('h'));
978        assert_eq!(a.count, 1);
979        assert_eq!(a.action, Action::Move(Motion::Left));
980    }
981
982    #[test]
983    fn dispatch_count_prefix_pends() {
984        let k = Keymap::default_vim();
985        let s = ModalState::new();
986        assert!(matches!(
987            k.dispatch(&s, &Key::Char('5')).action,
988            Action::Pending
989        ));
990    }
991
992    #[test]
993    fn dispatch_insert_char() {
994        let k = Keymap::default_vim();
995        let mut s = ModalState::new();
996        s.enter(Mode::Insert);
997        let a = k.dispatch(&s, &Key::Char('a'));
998        assert_eq!(a.action, Action::InsertChar('a'));
999    }
1000
1001    #[test]
1002    fn lisp_structural_motions_bound() {
1003        let k = Keymap::default_vim();
1004        assert_eq!(
1005            k.lookup(Mode::Normal, &Key::Alt('f')).unwrap().action,
1006            Action::Move(Motion::ForwardSexp)
1007        );
1008    }
1009
1010    #[test]
1011    fn default_leader_is_comma() {
1012        assert_eq!(Keymap::new().leader(), &Key::Char(','));
1013    }
1014
1015    #[test]
1016    fn bind_sequence_stores_multikey_and_resolves() {
1017        let mut k = Keymap::new();
1018        let seq = vec![Key::Char(','), Key::Char('f'), Key::Char('f')];
1019        k.bind_sequence(
1020            Mode::Normal,
1021            seq.clone(),
1022            Action::Command {
1023                name: "picker.files".into(),
1024                args: vec![],
1025            },
1026            "find files",
1027        );
1028        // Exact match resolves.
1029        let b = k.lookup_sequence(Mode::Normal, &seq).expect("seq bound");
1030        assert!(matches!(&b.action, Action::Command { name, .. } if name == "picker.files"));
1031        // Proper prefixes are live; the full sequence is NOT a prefix
1032        // of itself.
1033        assert!(k.is_sequence_prefix(Mode::Normal, &[Key::Char(',')]));
1034        assert!(k.is_sequence_prefix(Mode::Normal, &[Key::Char(','), Key::Char('f')]));
1035        assert!(!k.is_sequence_prefix(Mode::Normal, &seq));
1036        // Wrong mode → not a prefix.
1037        assert!(!k.is_sequence_prefix(Mode::Insert, &[Key::Char(',')]));
1038        assert_eq!(k.sequence_len(), 1);
1039    }
1040
1041    #[test]
1042    fn bind_sequence_length_one_delegates_to_single() {
1043        let mut k = Keymap::new();
1044        k.bind_sequence(
1045            Mode::Normal,
1046            vec![Key::Char('x')],
1047            Action::Undo,
1048            "x is undo",
1049        );
1050        // Lands in the single-key table, not the sequence table.
1051        assert_eq!(k.sequence_len(), 0);
1052        assert!(k.lookup(Mode::Normal, &Key::Char('x')).is_some());
1053    }
1054}
1055
1056/// escriba's `Key` as the fleet's chord vocabulary.
1057///
1058/// # Why a conversion rather than a migration (yet)
1059///
1060/// `escriba_keymap::Key` folds the modifier INTO the key — `Ctrl(char)`,
1061/// `Alt(char)` — over 16 variants. `awase::Hotkey` carries modifiers as a
1062/// bitflag SET over 116 key variants. The escriba shape therefore cannot
1063/// express `Ctrl+Shift+P`, cannot carry `Super`, and has no F-keys at all
1064/// (`escriba-input` discards `KeyCode::F(_)` at the door).
1065///
1066/// Migrating the whole keymap is the destination and it touches 52 call
1067/// sites. This conversion is what lets the **reserved-chord audit** run
1068/// today, before that lands: a binding escriba cannot even ask about is a
1069/// binding that silently dies when the window manager takes its chord.
1070///
1071/// Returns `None` for a key with no fleet spelling — today the shifted
1072/// digits and punctuation (`#`, `$`, `*`), which awase's `Key` does not
1073/// carry. That is the honest answer, and an audit must treat an unmappable
1074/// key as UNAUDITED rather than as available: silently counting it as clean
1075/// is how `Ctrl+Space` stayed hidden.
1076#[must_use]
1077pub fn to_hotkey(key: &Key) -> Option<awase::Hotkey> {
1078    use awase::{Hotkey, Key as AK, Modifiers as M};
1079    // `from_name` takes NAMES ("space"), not literal characters. Spelling a
1080    // space as " " returns None — which is how `Ctrl+Space` slipped past the
1081    // reserved audit while being bound in Insert mode AND owned by the OS.
1082    let named = |c: char| match c {
1083        ' ' => Some(AK::Space),
1084        c => AK::from_name(&c.to_ascii_lowercase().to_string()),
1085    };
1086    Some(match key {
1087        Key::Char(c) => Hotkey::new(M::NONE, named(*c)?),
1088        Key::Ctrl(c) => Hotkey::new(M::CTRL, named(*c)?),
1089        Key::Alt(c) => Hotkey::new(M::ALT, named(*c)?),
1090        Key::F(n) => Hotkey::new(M::NONE, AK::from_name(&format!("f{n}"))?),
1091        // Already a fleet chord — nothing to convert.
1092        Key::Chord(h) => *h,
1093        Key::Esc => Hotkey::new(M::NONE, AK::Escape),
1094        Key::Enter => Hotkey::new(M::NONE, AK::Return),
1095        Key::Tab => Hotkey::new(M::NONE, AK::Tab),
1096        Key::Backspace => Hotkey::new(M::NONE, AK::Backspace),
1097        Key::Delete => Hotkey::new(M::NONE, AK::Delete),
1098        Key::Left => Hotkey::new(M::NONE, AK::Left),
1099        Key::Right => Hotkey::new(M::NONE, AK::Right),
1100        Key::Up => Hotkey::new(M::NONE, AK::Up),
1101        Key::Down => Hotkey::new(M::NONE, AK::Down),
1102        Key::PageUp => Hotkey::new(M::NONE, AK::PageUp),
1103        Key::PageDown => Hotkey::new(M::NONE, AK::PageDown),
1104        Key::Home => Hotkey::new(M::NONE, AK::Home),
1105        Key::End => Hotkey::new(M::NONE, AK::End),
1106    })
1107}
1108
1109#[cfg(test)]
1110mod fleet_vocabulary {
1111    use super::*;
1112
1113    #[test]
1114    fn modifiers_survive_the_conversion() {
1115        let h = to_hotkey(&Key::Ctrl('w')).expect("ctrl+w maps");
1116        assert!(h.modifiers.contains(awase::Modifiers::CTRL));
1117        assert_eq!(h.key, awase::Key::W);
1118    }
1119
1120    #[test]
1121    fn named_keys_map_to_their_fleet_spelling() {
1122        // escriba says `Esc`/`Enter`; awase says `Escape`/`Return`. The
1123        // fleet atlas already warns that these two spellings diverge across
1124        // consumers, which is exactly what a shared vocabulary settles.
1125        assert_eq!(
1126            to_hotkey(&Key::Esc).map(|h| h.key),
1127            Some(awase::Key::Escape)
1128        );
1129        assert_eq!(
1130            to_hotkey(&Key::Enter).map(|h| h.key),
1131            Some(awase::Key::Return)
1132        );
1133    }
1134
1135    #[test]
1136    fn every_variant_of_escribas_key_has_a_fleet_spelling() {
1137        // If one did not, the reserved audit would have a blind spot exactly
1138        // where escriba's vocabulary is unusual — which is where a collision
1139        // is most likely.
1140        let all = [
1141            Key::Char('a'),
1142            Key::Ctrl('a'),
1143            Key::Alt('a'),
1144            Key::Esc,
1145            Key::Enter,
1146            Key::Tab,
1147            Key::Backspace,
1148            Key::Delete,
1149            Key::Left,
1150            Key::Right,
1151            Key::Up,
1152            Key::Down,
1153            Key::PageUp,
1154            Key::PageDown,
1155            Key::Home,
1156            Key::End,
1157        ];
1158        for k in all {
1159            assert!(to_hotkey(&k).is_some(), "{k:?} has no fleet spelling");
1160        }
1161    }
1162
1163    #[test]
1164    fn sequences_can_now_be_enumerated() {
1165        // `sequences` was private with no accessor, so the multi-key half of
1166        // the keymap was invisible from outside this crate — unauditable and
1167        // un-displayable.
1168        let k = Keymap::default_vim();
1169        let all = k.sequences_extending(Mode::Normal, &[]);
1170        assert!(!all.is_empty(), "the default keymap binds sequences");
1171        let g = k.sequences_extending(Mode::Normal, &[Key::Char('g')]);
1172        assert!(
1173            g.iter()
1174                .all(|(seq, _)| seq.first() == Some(&Key::Char('g'))),
1175            "a prefix query returns only its own continuations",
1176        );
1177    }
1178}
1179
1180#[cfg(test)]
1181mod collision_detection {
1182    use super::*;
1183
1184    #[test]
1185    fn a_reserved_chord_is_recorded_at_bind_time() {
1186        // Not discovered later by an audit — known the moment it is written.
1187        let mut m = Keymap::new();
1188        m.bind(Mode::Normal, Key::Alt('j'), Action::Undo, "focus down?");
1189        let c = m.collisions();
1190        assert_eq!(c.len(), 1, "{c:?}");
1191        assert!(c[0].is_fatal(), "a chord the world owns can never fire");
1192        assert!(
1193            c[0].report().contains("window manager"),
1194            "{}",
1195            c[0].report()
1196        );
1197    }
1198
1199    #[test]
1200    fn a_displaced_binding_is_recorded_but_not_fatal() {
1201        // Overriding is sometimes intended — the shipped rc deliberately
1202        // overrides defaults — so it is REPORTED, never refused. But "my
1203        // plugin's key stopped working" has no other explanation available.
1204        let mut m = Keymap::new();
1205        m.bind(Mode::Normal, Key::Char('x'), Action::Undo, "first");
1206        m.bind(Mode::Normal, Key::Char('x'), Action::Redo, "second");
1207        let c = m.collisions();
1208        assert_eq!(c.len(), 1);
1209        assert!(!c[0].is_fatal());
1210        let r = c[0].report();
1211        assert!(r.contains("first") && r.contains("second"), "{r}");
1212    }
1213
1214    #[test]
1215    // OPENER is shouted because which key is checked IS the point.
1216    #[allow(non_snake_case)]
1217    fn a_sequence_whose_OPENER_is_reserved_is_caught() {
1218        // `alt-j` then anything can never begin, because the first key never
1219        // arrives. Checking only single keys would miss the whole sequence.
1220        let mut m = Keymap::new();
1221        m.bind_sequence(
1222            Mode::Normal,
1223            vec![Key::Alt('j'), Key::Char('x')],
1224            Action::Undo,
1225            "dead sequence",
1226        );
1227        assert!(m.fatal_collisions().count() == 1, "{:?}", m.collisions(),);
1228    }
1229
1230    #[test]
1231    fn an_ordinary_keymap_records_nothing() {
1232        // The detector must be quiet when there is nothing to say, or it
1233        // becomes noise an operator learns to skip.
1234        let mut m = Keymap::new();
1235        m.bind(Mode::Normal, Key::Char('h'), Action::Undo, "left");
1236        m.bind(Mode::Normal, Key::Ctrl('w'), Action::Redo, "window prefix");
1237        assert!(m.collisions().is_empty(), "{:?}", m.collisions());
1238    }
1239
1240    #[test]
1241    fn the_shipped_default_keymap_is_clean() {
1242        let m = Keymap::default_vim();
1243        assert!(
1244            m.collisions().is_empty(),
1245            "escriba's own defaults must not collide:\n  {}",
1246            m.collisions()
1247                .iter()
1248                .map(Collision::report)
1249                .collect::<Vec<_>>()
1250                .join("\n  "),
1251        );
1252    }
1253}