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};
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(&mut m, Key::Ctrl('r'), Action::Redo, "redo");
202        // Insert → Normal on Esc.
203        m.bind(
204            Mode::Insert,
205            Key::Esc,
206            Action::ChangeMode(Mode::Normal),
207            "to normal",
208        );
209        m.bind(
210            Mode::Command,
211            Key::Esc,
212            Action::ChangeMode(Mode::Normal),
213            "abort",
214        );
215        m.bind(Mode::Command, Key::Enter, Action::SubmitCommand, "submit");
216        m.bind(
217            Mode::Command,
218            Key::Up,
219            Action::PromptHistory { back: true },
220            "older search",
221        );
222        m.bind(
223            Mode::Command,
224            Key::Down,
225            Action::PromptHistory { back: false },
226            "newer search",
227        );
228        m.bind(
229            Mode::Command,
230            Key::Backspace,
231            Action::PromptBackspace,
232            "erase one char",
233        );
234        // Caret editing inside the prompt. Without these the prompt is
235        // append-only, so a typo in the middle of a pattern can only be fixed
236        // by deleting everything back to it.
237        m.bind(
238            Mode::Command,
239            Key::Left,
240            Action::PromptCaret {
241                to: CaretMove::Left,
242            },
243            "caret left",
244        );
245        m.bind(
246            Mode::Command,
247            Key::Right,
248            Action::PromptCaret {
249                to: CaretMove::Right,
250            },
251            "caret right",
252        );
253        m.bind(
254            Mode::Command,
255            Key::Home,
256            Action::PromptCaret {
257                to: CaretMove::Start,
258            },
259            "caret to start",
260        );
261        m.bind(
262            Mode::Command,
263            Key::End,
264            Action::PromptCaret { to: CaretMove::End },
265            "caret to end",
266        );
267        m.bind(
268            Mode::Command,
269            Key::Ctrl('w'),
270            Action::PromptDeleteWord,
271            "delete word before caret",
272        );
273        m.bind(
274            Mode::Command,
275            Key::Ctrl('u'),
276            Action::PromptClearToStart,
277            "clear to start",
278        );
279
280        // ── search ────────────────────────────────────────────────────
281        // `/` and `?` open the prompt; `<CR>` is the existing SubmitCommand,
282        // which the runtime routes to the search when a search prompt is open.
283        // That routing is typed (Option<Prompt>), not a mode flag to forget.
284        nm(
285            &mut m,
286            Key::Char('/'),
287            Action::SearchOpen(SearchDirection::Forward),
288            "search forward",
289        );
290        nm(
291            &mut m,
292            Key::Char('?'),
293            Action::SearchOpen(SearchDirection::Backward),
294            "search backward",
295        );
296        // `n`/`N` are MOTIONS, not standalone jumps. Binding them to
297        // `Action::Move` is what makes `dn` / `yN` compose — the
298        // operator-pending machine only recognises `Action::Move` as an
299        // operand. `Action::SearchRepeat` remains a valid action (a user rc or
300        // the tatara-lisp binding table may name it) and the runtime routes it
301        // through the same executor, so there is exactly one code path.
302        nm(
303            &mut m,
304            Key::Char('n'),
305            Action::Move(Motion::SearchNext),
306            "next match",
307        );
308        nm(
309            &mut m,
310            Key::Char('N'),
311            Action::Move(Motion::SearchPrev),
312            "previous match",
313        );
314
315        // ── jumplist ──────────────────────────────────────────────────
316        // The return ticket for every far jump above. Without it a committed
317        // search is a one-way door.
318        nm(&mut m, Key::Ctrl('o'), Action::JumpBack, "jump back");
319        nm(&mut m, Key::Ctrl('i'), Action::JumpForward, "jump forward");
320        nm(
321            &mut m,
322            Key::Char('*'),
323            Action::SearchWord { reverse: false },
324            "search word forward",
325        );
326        nm(
327            &mut m,
328            Key::Char('#'),
329            Action::SearchWord { reverse: true },
330            "search word backward",
331        );
332        m.bind(
333            Mode::Visual,
334            Key::Esc,
335            Action::ChangeMode(Mode::Normal),
336            "to normal",
337        );
338        m.bind(
339            Mode::VisualLine,
340            Key::Esc,
341            Action::ChangeMode(Mode::Normal),
342            "to normal",
343        );
344        m
345    }
346
347    pub fn bind(&mut self, mode: Mode, key: Key, action: Action, desc: impl Into<String>) {
348        self.bindings
349            .insert((mode, key), Binding::new(action, desc));
350    }
351
352    #[must_use]
353    pub fn lookup(&self, mode: Mode, key: &Key) -> Option<&Binding> {
354        self.bindings.get(&(mode, key.clone()))
355    }
356
357    /// The leader key — what `<leader>` resolves to when a sequence
358    /// binding is applied. Defaults to `,` (blnvim parity).
359    #[must_use]
360    pub fn leader(&self) -> &Key {
361        &self.leader
362    }
363
364    /// Override the leader key. Applied before sequence bindings so
365    /// `<leader>`-prefixed specs resolve against the chosen prefix.
366    pub fn set_leader(&mut self, key: Key) {
367        self.leader = key;
368    }
369
370    /// Bind a multi-key SEQUENCE — `<leader>ff` →
371    /// `[Char(','), Char('f'), Char('f')]`, `gg` →
372    /// `[Char('g'), Char('g')]`. A length-1 sequence delegates to
373    /// [`bind`](Keymap::bind) so callers never special-case it; an
374    /// empty sequence is a no-op.
375    pub fn bind_sequence(
376        &mut self,
377        mode: Mode,
378        keys: Vec<Key>,
379        action: Action,
380        desc: impl Into<String>,
381    ) {
382        match keys.as_slice() {
383            [] => {}
384            [single] => self.bind(mode, single.clone(), action, desc),
385            _ => {
386                self.sequences
387                    .insert((mode, keys), Binding::new(action, desc));
388            }
389        }
390    }
391
392    /// Exact-match lookup for a full key sequence.
393    #[must_use]
394    pub fn lookup_sequence(&self, mode: Mode, keys: &[Key]) -> Option<&Binding> {
395        self.sequences.get(&(mode, keys.to_vec()))
396    }
397
398    /// Does any bound sequence in `mode` STRICTLY extend `prefix`
399    /// (i.e. `prefix` is a proper prefix of a longer bound sequence)?
400    /// Drives the runtime's pending-stroke state: a partial sequence
401    /// that is still a live prefix is held pending rather than
402    /// dispatched. Linear scan — fine at fleet sequence counts; a
403    /// trie is a later optimization if profiling ever asks for it.
404    #[must_use]
405    pub fn is_sequence_prefix(&self, mode: Mode, prefix: &[Key]) -> bool {
406        self.sequences
407            .keys()
408            .any(|(m, seq)| *m == mode && seq.len() > prefix.len() && seq.starts_with(prefix))
409    }
410
411    /// Count of bound multi-key sequences — for `--keymap` / doctor.
412    #[must_use]
413    pub fn sequence_len(&self) -> usize {
414        self.sequences.len()
415    }
416
417    #[must_use]
418    pub fn dispatch(&self, state: &ModalState, key: &Key) -> CountedAction {
419        let mode = state.mode();
420        if mode == Mode::Normal {
421            if let Key::Char(c) = key {
422                if c.is_ascii_digit() && *c != '0' {
423                    return CountedAction::once(Action::Pending);
424                }
425                if *c == '0' && state.pending_count().is_some() {
426                    return CountedAction::once(Action::Pending);
427                }
428            }
429        }
430        if mode == Mode::Insert {
431            if let Key::Char(c) = key {
432                return CountedAction::once(Action::InsertChar(*c));
433            }
434            if matches!(key, Key::Enter) {
435                return CountedAction::once(Action::InsertChar('\n'));
436            }
437        }
438        if mode == Mode::Command {
439            if let Key::Char(c) = key {
440                return CountedAction::once(Action::InsertChar(*c));
441            }
442        }
443        if let Some(b) = self.lookup(mode, key) {
444            return CountedAction::repeated(state.pending_count().unwrap_or(1), b.action.clone());
445        }
446        CountedAction::once(Action::Pending)
447    }
448
449    #[must_use]
450    pub fn len(&self) -> usize {
451        self.bindings.len()
452    }
453
454    #[must_use]
455    pub fn is_empty(&self) -> bool {
456        self.bindings.is_empty()
457    }
458
459    /// Sorted view over every binding — for `escriba --keymap` and palettes.
460    #[must_use]
461    pub fn entries_sorted(&self) -> Vec<(&Mode, &Key, &Binding)> {
462        let mut v: Vec<_> = self.bindings.iter().map(|((m, k), b)| (m, k, b)).collect();
463        v.sort_by(|a, b| {
464            (a.0.as_str(), format!("{:?}", a.1)).cmp(&(b.0.as_str(), format!("{:?}", b.1)))
465        });
466        v
467    }
468}
469
470#[cfg(test)]
471mod tests {
472    use super::*;
473
474    #[test]
475    fn default_vim_has_bindings() {
476        let k = Keymap::default_vim();
477        assert!(k.len() > 10);
478        assert!(k.lookup(Mode::Normal, &Key::Char('h')).is_some());
479        assert!(k.lookup(Mode::Insert, &Key::Esc).is_some());
480        assert!(k.lookup(Mode::Normal, &Key::Alt('f')).is_some());
481    }
482
483    #[test]
484    fn dispatch_normal_motion() {
485        let k = Keymap::default_vim();
486        let s = ModalState::new();
487        let a = k.dispatch(&s, &Key::Char('h'));
488        assert_eq!(a.count, 1);
489        assert_eq!(a.action, Action::Move(Motion::Left));
490    }
491
492    #[test]
493    fn dispatch_count_prefix_pends() {
494        let k = Keymap::default_vim();
495        let s = ModalState::new();
496        assert!(matches!(
497            k.dispatch(&s, &Key::Char('5')).action,
498            Action::Pending
499        ));
500    }
501
502    #[test]
503    fn dispatch_insert_char() {
504        let k = Keymap::default_vim();
505        let mut s = ModalState::new();
506        s.enter(Mode::Insert);
507        let a = k.dispatch(&s, &Key::Char('a'));
508        assert_eq!(a.action, Action::InsertChar('a'));
509    }
510
511    #[test]
512    fn lisp_structural_motions_bound() {
513        let k = Keymap::default_vim();
514        assert_eq!(
515            k.lookup(Mode::Normal, &Key::Alt('f')).unwrap().action,
516            Action::Move(Motion::ForwardSexp)
517        );
518    }
519
520    #[test]
521    fn default_leader_is_comma() {
522        assert_eq!(Keymap::new().leader(), &Key::Char(','));
523    }
524
525    #[test]
526    fn bind_sequence_stores_multikey_and_resolves() {
527        let mut k = Keymap::new();
528        let seq = vec![Key::Char(','), Key::Char('f'), Key::Char('f')];
529        k.bind_sequence(
530            Mode::Normal,
531            seq.clone(),
532            Action::Command {
533                name: "picker.files".into(),
534                args: vec![],
535            },
536            "find files",
537        );
538        // Exact match resolves.
539        let b = k.lookup_sequence(Mode::Normal, &seq).expect("seq bound");
540        assert!(matches!(&b.action, Action::Command { name, .. } if name == "picker.files"));
541        // Proper prefixes are live; the full sequence is NOT a prefix
542        // of itself.
543        assert!(k.is_sequence_prefix(Mode::Normal, &[Key::Char(',')]));
544        assert!(k.is_sequence_prefix(Mode::Normal, &[Key::Char(','), Key::Char('f')]));
545        assert!(!k.is_sequence_prefix(Mode::Normal, &seq));
546        // Wrong mode → not a prefix.
547        assert!(!k.is_sequence_prefix(Mode::Insert, &[Key::Char(',')]));
548        assert_eq!(k.sequence_len(), 1);
549    }
550
551    #[test]
552    fn bind_sequence_length_one_delegates_to_single() {
553        let mut k = Keymap::new();
554        k.bind_sequence(
555            Mode::Normal,
556            vec![Key::Char('x')],
557            Action::Undo,
558            "x is undo",
559        );
560        // Lands in the single-key table, not the sequence table.
561        assert_eq!(k.sequence_len(), 0);
562        assert!(k.lookup(Mode::Normal, &Key::Char('x')).is_some());
563    }
564}