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::{Action, CountedAction, Mode, Motion, Operator, TextObject};
9use escriba_mode::ModalState;
10use serde::{Deserialize, Serialize};
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
13pub enum Key {
14    Char(char),
15    Esc,
16    Enter,
17    Tab,
18    Backspace,
19    Left,
20    Right,
21    Up,
22    Down,
23    PageUp,
24    PageDown,
25    Home,
26    End,
27    Ctrl(char),
28    Alt(char),
29}
30
31#[derive(Debug, Clone, Serialize, Deserialize)]
32pub struct Binding {
33    pub action: Action,
34    pub description: String,
35}
36
37impl Binding {
38    #[must_use]
39    pub fn new(action: Action, description: impl Into<String>) -> Self {
40        Self {
41            action,
42            description: description.into(),
43        }
44    }
45}
46
47#[derive(Debug, Clone)]
48pub struct Keymap {
49    bindings: HashMap<(Mode, Key), Binding>,
50    /// Multi-key sequence bindings (`<leader>ff`, `gg`, `<C-w>h`).
51    /// Keyed by the full key sequence; resolved by the runtime's
52    /// pending-stroke loop ([`lookup_sequence`](Keymap::lookup_sequence)
53    /// + [`is_sequence_prefix`](Keymap::is_sequence_prefix)).
54    sequences: HashMap<(Mode, Vec<Key>), Binding>,
55    /// The prefix `<leader>` resolves to at sequence-apply time.
56    leader: Key,
57}
58
59impl Default for Keymap {
60    fn default() -> Self {
61        Self {
62            bindings: HashMap::new(),
63            sequences: HashMap::new(),
64            // blnvim's leader is comma; escriba ships blnvim-parity
65            // defaults, so the prefix users press matches muscle memory.
66            leader: Key::Char(','),
67        }
68    }
69}
70
71impl Keymap {
72    #[must_use]
73    pub fn new() -> Self {
74        Self::default()
75    }
76
77    #[must_use]
78    pub fn default_vim() -> Self {
79        let mut m = Self::new();
80        let nm = |m: &mut Keymap, k: Key, a: Action, d: &'static str| m.bind(Mode::Normal, k, a, d);
81        nm(
82            &mut m,
83            Key::Char('h'),
84            Action::Move(Motion::Left),
85            "move left",
86        );
87        nm(
88            &mut m,
89            Key::Char('l'),
90            Action::Move(Motion::Right),
91            "move right",
92        );
93        nm(
94            &mut m,
95            Key::Char('j'),
96            Action::Move(Motion::Down),
97            "move down",
98        );
99        nm(&mut m, Key::Char('k'), Action::Move(Motion::Up), "move up");
100        nm(
101            &mut m,
102            Key::Char('w'),
103            Action::Move(Motion::WordStartNext),
104            "word forward",
105        );
106        nm(
107            &mut m,
108            Key::Char('b'),
109            Action::Move(Motion::WordStartPrev),
110            "word back",
111        );
112        nm(
113            &mut m,
114            Key::Char('0'),
115            Action::Move(Motion::LineStart),
116            "line start",
117        );
118        nm(
119            &mut m,
120            Key::Char('$'),
121            Action::Move(Motion::LineEnd),
122            "line end",
123        );
124        nm(
125            &mut m,
126            Key::Char('G'),
127            Action::Move(Motion::DocEnd),
128            "doc end",
129        );
130        // Operators — `d`/`c`/`y` arm the operator-pending FSM; the next
131        // motion composes (e.g. `dw`, `c$`, `y0`).
132        nm(
133            &mut m,
134            Key::Char('d'),
135            Action::Operator(Operator::Delete),
136            "delete (operator)",
137        );
138        nm(
139            &mut m,
140            Key::Char('c'),
141            Action::Operator(Operator::Change),
142            "change (operator)",
143        );
144        nm(
145            &mut m,
146            Key::Char('y'),
147            Action::Operator(Operator::Yank),
148            "yank (operator)",
149        );
150        // Structural Lisp motions — Alt-prefixed like emacs paredit.
151        nm(
152            &mut m,
153            Key::Alt('f'),
154            Action::Move(Motion::ForwardSexp),
155            "forward sexp",
156        );
157        nm(
158            &mut m,
159            Key::Alt('b'),
160            Action::Move(Motion::BackwardSexp),
161            "backward sexp",
162        );
163        nm(
164            &mut m,
165            Key::Alt('u'),
166            Action::Move(Motion::UpList),
167            "up list",
168        );
169        nm(
170            &mut m,
171            Key::Alt('d'),
172            Action::Move(Motion::DownList),
173            "down list",
174        );
175        // Mode changes.
176        nm(
177            &mut m,
178            Key::Char('i'),
179            Action::ChangeMode(Mode::Insert),
180            "insert",
181        );
182        nm(
183            &mut m,
184            Key::Char('v'),
185            Action::ChangeMode(Mode::Visual),
186            "visual",
187        );
188        nm(
189            &mut m,
190            Key::Char('V'),
191            Action::ChangeMode(Mode::VisualLine),
192            "visual line",
193        );
194        nm(
195            &mut m,
196            Key::Char(':'),
197            Action::ChangeMode(Mode::Command),
198            "command",
199        );
200        nm(&mut m, Key::Char('u'), Action::Undo, "undo");
201        nm(
202            &mut m,
203            Key::Char('.'),
204            Action::RepeatLastChange,
205            "repeat last change",
206        );
207        nm(&mut m, Key::Ctrl('r'), Action::Redo, "redo");
208        // Insert → Normal on Esc.
209        m.bind(
210            Mode::Insert,
211            Key::Esc,
212            Action::ChangeMode(Mode::Normal),
213            "to normal",
214        );
215        m.bind(
216            Mode::Command,
217            Key::Esc,
218            Action::ChangeMode(Mode::Normal),
219            "abort",
220        );
221        m.bind(Mode::Command, Key::Enter, Action::SubmitCommand, "submit");
222        m.bind(
223            Mode::Command,
224            Key::Up,
225            Action::PromptHistory { back: true },
226            "older search",
227        );
228        m.bind(
229            Mode::Command,
230            Key::Down,
231            Action::PromptHistory { back: false },
232            "newer search",
233        );
234        m.bind(
235            Mode::Command,
236            Key::Backspace,
237            Action::PromptBackspace,
238            "erase one char",
239        );
240        // Caret editing inside the prompt. Without these the prompt is
241        // append-only, so a typo in the middle of a pattern can only be fixed
242        // by deleting everything back to it.
243        m.bind(
244            Mode::Command,
245            Key::Left,
246            Action::PromptCaret {
247                to: CaretMove::Left,
248            },
249            "caret left",
250        );
251        m.bind(
252            Mode::Command,
253            Key::Right,
254            Action::PromptCaret {
255                to: CaretMove::Right,
256            },
257            "caret right",
258        );
259        m.bind(
260            Mode::Command,
261            Key::Home,
262            Action::PromptCaret {
263                to: CaretMove::Start,
264            },
265            "caret to start",
266        );
267        m.bind(
268            Mode::Command,
269            Key::End,
270            Action::PromptCaret { to: CaretMove::End },
271            "caret to end",
272        );
273        m.bind(
274            Mode::Command,
275            Key::Ctrl('w'),
276            Action::PromptDeleteWord,
277            "delete word before caret",
278        );
279        m.bind(
280            Mode::Command,
281            Key::Ctrl('u'),
282            Action::PromptClearToStart,
283            "clear to start",
284        );
285
286        // ── search ────────────────────────────────────────────────────
287        // `/` and `?` open the prompt; `<CR>` is the existing SubmitCommand,
288        // which the runtime routes to the search when a search prompt is open.
289        // That routing is typed (Option<Prompt>), not a mode flag to forget.
290        nm(
291            &mut m,
292            Key::Char('/'),
293            Action::SearchOpen(SearchDirection::Forward),
294            "search forward",
295        );
296        nm(
297            &mut m,
298            Key::Char('?'),
299            Action::SearchOpen(SearchDirection::Backward),
300            "search backward",
301        );
302        // `n`/`N` are MOTIONS, not standalone jumps. Binding them to
303        // `Action::Move` is what makes `dn` / `yN` compose — the
304        // operator-pending machine only recognises `Action::Move` as an
305        // operand. `Action::SearchRepeat` remains a valid action (a user rc or
306        // the tatara-lisp binding table may name it) and the runtime routes it
307        // through the same executor, so there is exactly one code path.
308        nm(
309            &mut m,
310            Key::Char('n'),
311            Action::Move(Motion::SearchNext),
312            "next match",
313        );
314        nm(
315            &mut m,
316            Key::Char('N'),
317            Action::Move(Motion::SearchPrev),
318            "previous match",
319        );
320
321        // `gn` / `gN` — the match as an OBJECT, so `cgn` changes the whole
322        // match and `.` repeats that on the next one.
323        m.bind_sequence(
324            Mode::Normal,
325            vec![Key::Char('g'), Key::Char('n')],
326            Action::TextObject(TextObject::NextMatch),
327            "next match (object)",
328        );
329        m.bind_sequence(
330            Mode::Normal,
331            vec![Key::Char('g'), Key::Char('N')],
332            Action::TextObject(TextObject::PrevMatch),
333            "previous match (object)",
334        );
335
336        // ── jumplist ──────────────────────────────────────────────────
337        // The return ticket for every far jump above. Without it a committed
338        // search is a one-way door.
339        nm(&mut m, Key::Ctrl('o'), Action::JumpBack, "jump back");
340        nm(&mut m, Key::Ctrl('i'), Action::JumpForward, "jump forward");
341        nm(
342            &mut m,
343            Key::Char('*'),
344            Action::SearchWord { reverse: false },
345            "search word forward",
346        );
347        nm(
348            &mut m,
349            Key::Char('#'),
350            Action::SearchWord { reverse: true },
351            "search word backward",
352        );
353        m.bind(
354            Mode::Visual,
355            Key::Esc,
356            Action::ChangeMode(Mode::Normal),
357            "to normal",
358        );
359        m.bind(
360            Mode::VisualLine,
361            Key::Esc,
362            Action::ChangeMode(Mode::Normal),
363            "to normal",
364        );
365        m
366    }
367
368    pub fn bind(&mut self, mode: Mode, key: Key, action: Action, desc: impl Into<String>) {
369        self.bindings
370            .insert((mode, key), Binding::new(action, desc));
371    }
372
373    #[must_use]
374    pub fn lookup(&self, mode: Mode, key: &Key) -> Option<&Binding> {
375        self.bindings.get(&(mode, key.clone()))
376    }
377
378    /// The leader key — what `<leader>` resolves to when a sequence
379    /// binding is applied. Defaults to `,` (blnvim parity).
380    #[must_use]
381    pub fn leader(&self) -> &Key {
382        &self.leader
383    }
384
385    /// Override the leader key. Applied before sequence bindings so
386    /// `<leader>`-prefixed specs resolve against the chosen prefix.
387    pub fn set_leader(&mut self, key: Key) {
388        self.leader = key;
389    }
390
391    /// Bind a multi-key SEQUENCE — `<leader>ff` →
392    /// `[Char(','), Char('f'), Char('f')]`, `gg` →
393    /// `[Char('g'), Char('g')]`. A length-1 sequence delegates to
394    /// [`bind`](Keymap::bind) so callers never special-case it; an
395    /// empty sequence is a no-op.
396    pub fn bind_sequence(
397        &mut self,
398        mode: Mode,
399        keys: Vec<Key>,
400        action: Action,
401        desc: impl Into<String>,
402    ) {
403        match keys.as_slice() {
404            [] => {}
405            [single] => self.bind(mode, single.clone(), action, desc),
406            _ => {
407                self.sequences
408                    .insert((mode, keys), Binding::new(action, desc));
409            }
410        }
411    }
412
413    /// Exact-match lookup for a full key sequence.
414    #[must_use]
415    pub fn lookup_sequence(&self, mode: Mode, keys: &[Key]) -> Option<&Binding> {
416        self.sequences.get(&(mode, keys.to_vec()))
417    }
418
419    /// Does any bound sequence in `mode` STRICTLY extend `prefix`
420    /// (i.e. `prefix` is a proper prefix of a longer bound sequence)?
421    /// Drives the runtime's pending-stroke state: a partial sequence
422    /// that is still a live prefix is held pending rather than
423    /// dispatched. Linear scan — fine at fleet sequence counts; a
424    /// trie is a later optimization if profiling ever asks for it.
425    #[must_use]
426    pub fn is_sequence_prefix(&self, mode: Mode, prefix: &[Key]) -> bool {
427        self.sequences
428            .keys()
429            .any(|(m, seq)| *m == mode && seq.len() > prefix.len() && seq.starts_with(prefix))
430    }
431
432    /// Count of bound multi-key sequences — for `--keymap` / doctor.
433    #[must_use]
434    pub fn sequence_len(&self) -> usize {
435        self.sequences.len()
436    }
437
438    #[must_use]
439    pub fn dispatch(&self, state: &ModalState, key: &Key) -> CountedAction {
440        let mode = state.mode();
441        if mode == Mode::Normal {
442            if let Key::Char(c) = key {
443                if c.is_ascii_digit() && *c != '0' {
444                    return CountedAction::once(Action::Pending);
445                }
446                if *c == '0' && state.pending_count().is_some() {
447                    return CountedAction::once(Action::Pending);
448                }
449            }
450        }
451        if mode == Mode::Insert {
452            if let Key::Char(c) = key {
453                return CountedAction::once(Action::InsertChar(*c));
454            }
455            if matches!(key, Key::Enter) {
456                return CountedAction::once(Action::InsertChar('\n'));
457            }
458        }
459        if mode == Mode::Command {
460            if let Key::Char(c) = key {
461                return CountedAction::once(Action::InsertChar(*c));
462            }
463        }
464        if let Some(b) = self.lookup(mode, key) {
465            return CountedAction::repeated(state.pending_count().unwrap_or(1), b.action.clone());
466        }
467        CountedAction::once(Action::Pending)
468    }
469
470    #[must_use]
471    pub fn len(&self) -> usize {
472        self.bindings.len()
473    }
474
475    #[must_use]
476    pub fn is_empty(&self) -> bool {
477        self.bindings.is_empty()
478    }
479
480    /// Sorted view over every binding — for `escriba --keymap` and palettes.
481    #[must_use]
482    pub fn entries_sorted(&self) -> Vec<(&Mode, &Key, &Binding)> {
483        let mut v: Vec<_> = self.bindings.iter().map(|((m, k), b)| (m, k, b)).collect();
484        v.sort_by(|a, b| {
485            (a.0.as_str(), format!("{:?}", a.1)).cmp(&(b.0.as_str(), format!("{:?}", b.1)))
486        });
487        v
488    }
489}
490
491#[cfg(test)]
492mod tests {
493    use super::*;
494
495    #[test]
496    fn default_vim_has_bindings() {
497        let k = Keymap::default_vim();
498        assert!(k.len() > 10);
499        assert!(k.lookup(Mode::Normal, &Key::Char('h')).is_some());
500        assert!(k.lookup(Mode::Insert, &Key::Esc).is_some());
501        assert!(k.lookup(Mode::Normal, &Key::Alt('f')).is_some());
502    }
503
504    #[test]
505    fn dispatch_normal_motion() {
506        let k = Keymap::default_vim();
507        let s = ModalState::new();
508        let a = k.dispatch(&s, &Key::Char('h'));
509        assert_eq!(a.count, 1);
510        assert_eq!(a.action, Action::Move(Motion::Left));
511    }
512
513    #[test]
514    fn dispatch_count_prefix_pends() {
515        let k = Keymap::default_vim();
516        let s = ModalState::new();
517        assert!(matches!(
518            k.dispatch(&s, &Key::Char('5')).action,
519            Action::Pending
520        ));
521    }
522
523    #[test]
524    fn dispatch_insert_char() {
525        let k = Keymap::default_vim();
526        let mut s = ModalState::new();
527        s.enter(Mode::Insert);
528        let a = k.dispatch(&s, &Key::Char('a'));
529        assert_eq!(a.action, Action::InsertChar('a'));
530    }
531
532    #[test]
533    fn lisp_structural_motions_bound() {
534        let k = Keymap::default_vim();
535        assert_eq!(
536            k.lookup(Mode::Normal, &Key::Alt('f')).unwrap().action,
537            Action::Move(Motion::ForwardSexp)
538        );
539    }
540
541    #[test]
542    fn default_leader_is_comma() {
543        assert_eq!(Keymap::new().leader(), &Key::Char(','));
544    }
545
546    #[test]
547    fn bind_sequence_stores_multikey_and_resolves() {
548        let mut k = Keymap::new();
549        let seq = vec![Key::Char(','), Key::Char('f'), Key::Char('f')];
550        k.bind_sequence(
551            Mode::Normal,
552            seq.clone(),
553            Action::Command {
554                name: "picker.files".into(),
555                args: vec![],
556            },
557            "find files",
558        );
559        // Exact match resolves.
560        let b = k.lookup_sequence(Mode::Normal, &seq).expect("seq bound");
561        assert!(matches!(&b.action, Action::Command { name, .. } if name == "picker.files"));
562        // Proper prefixes are live; the full sequence is NOT a prefix
563        // of itself.
564        assert!(k.is_sequence_prefix(Mode::Normal, &[Key::Char(',')]));
565        assert!(k.is_sequence_prefix(Mode::Normal, &[Key::Char(','), Key::Char('f')]));
566        assert!(!k.is_sequence_prefix(Mode::Normal, &seq));
567        // Wrong mode → not a prefix.
568        assert!(!k.is_sequence_prefix(Mode::Insert, &[Key::Char(',')]));
569        assert_eq!(k.sequence_len(), 1);
570    }
571
572    #[test]
573    fn bind_sequence_length_one_delegates_to_single() {
574        let mut k = Keymap::new();
575        k.bind_sequence(
576            Mode::Normal,
577            vec![Key::Char('x')],
578            Action::Undo,
579            "x is undo",
580        );
581        // Lands in the single-key table, not the sequence table.
582        assert_eq!(k.sequence_len(), 0);
583        assert!(k.lookup(Mode::Normal, &Key::Char('x')).is_some());
584    }
585}