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::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::Backspace,
219            Action::PromptBackspace,
220            "erase one char",
221        );
222
223        // ── search ────────────────────────────────────────────────────
224        // `/` and `?` open the prompt; `<CR>` is the existing SubmitCommand,
225        // which the runtime routes to the search when a search prompt is open.
226        // That routing is typed (Option<Prompt>), not a mode flag to forget.
227        nm(
228            &mut m,
229            Key::Char('/'),
230            Action::SearchOpen(SearchDirection::Forward),
231            "search forward",
232        );
233        nm(
234            &mut m,
235            Key::Char('?'),
236            Action::SearchOpen(SearchDirection::Backward),
237            "search backward",
238        );
239        nm(&mut m, Key::Char('n'), Action::SearchRepeat { reverse: false }, "next match");
240        nm(&mut m, Key::Char('N'), Action::SearchRepeat { reverse: true }, "previous match");
241        nm(&mut m, Key::Char('*'), Action::SearchWord { reverse: false }, "search word forward");
242        nm(&mut m, Key::Char('#'), Action::SearchWord { reverse: true }, "search word backward");
243        m.bind(
244            Mode::Visual,
245            Key::Esc,
246            Action::ChangeMode(Mode::Normal),
247            "to normal",
248        );
249        m.bind(
250            Mode::VisualLine,
251            Key::Esc,
252            Action::ChangeMode(Mode::Normal),
253            "to normal",
254        );
255        m
256    }
257
258    pub fn bind(&mut self, mode: Mode, key: Key, action: Action, desc: impl Into<String>) {
259        self.bindings
260            .insert((mode, key), Binding::new(action, desc));
261    }
262
263    #[must_use]
264    pub fn lookup(&self, mode: Mode, key: &Key) -> Option<&Binding> {
265        self.bindings.get(&(mode, key.clone()))
266    }
267
268    /// The leader key — what `<leader>` resolves to when a sequence
269    /// binding is applied. Defaults to `,` (blnvim parity).
270    #[must_use]
271    pub fn leader(&self) -> &Key {
272        &self.leader
273    }
274
275    /// Override the leader key. Applied before sequence bindings so
276    /// `<leader>`-prefixed specs resolve against the chosen prefix.
277    pub fn set_leader(&mut self, key: Key) {
278        self.leader = key;
279    }
280
281    /// Bind a multi-key SEQUENCE — `<leader>ff` →
282    /// `[Char(','), Char('f'), Char('f')]`, `gg` →
283    /// `[Char('g'), Char('g')]`. A length-1 sequence delegates to
284    /// [`bind`](Keymap::bind) so callers never special-case it; an
285    /// empty sequence is a no-op.
286    pub fn bind_sequence(
287        &mut self,
288        mode: Mode,
289        keys: Vec<Key>,
290        action: Action,
291        desc: impl Into<String>,
292    ) {
293        match keys.as_slice() {
294            [] => {}
295            [single] => self.bind(mode, single.clone(), action, desc),
296            _ => {
297                self.sequences
298                    .insert((mode, keys), Binding::new(action, desc));
299            }
300        }
301    }
302
303    /// Exact-match lookup for a full key sequence.
304    #[must_use]
305    pub fn lookup_sequence(&self, mode: Mode, keys: &[Key]) -> Option<&Binding> {
306        self.sequences.get(&(mode, keys.to_vec()))
307    }
308
309    /// Does any bound sequence in `mode` STRICTLY extend `prefix`
310    /// (i.e. `prefix` is a proper prefix of a longer bound sequence)?
311    /// Drives the runtime's pending-stroke state: a partial sequence
312    /// that is still a live prefix is held pending rather than
313    /// dispatched. Linear scan — fine at fleet sequence counts; a
314    /// trie is a later optimization if profiling ever asks for it.
315    #[must_use]
316    pub fn is_sequence_prefix(&self, mode: Mode, prefix: &[Key]) -> bool {
317        self.sequences
318            .keys()
319            .any(|(m, seq)| *m == mode && seq.len() > prefix.len() && seq.starts_with(prefix))
320    }
321
322    /// Count of bound multi-key sequences — for `--keymap` / doctor.
323    #[must_use]
324    pub fn sequence_len(&self) -> usize {
325        self.sequences.len()
326    }
327
328    #[must_use]
329    pub fn dispatch(&self, state: &ModalState, key: &Key) -> CountedAction {
330        let mode = state.mode();
331        if mode == Mode::Normal {
332            if let Key::Char(c) = key {
333                if c.is_ascii_digit() && *c != '0' {
334                    return CountedAction::once(Action::Pending);
335                }
336                if *c == '0' && state.pending_count().is_some() {
337                    return CountedAction::once(Action::Pending);
338                }
339            }
340        }
341        if mode == Mode::Insert {
342            if let Key::Char(c) = key {
343                return CountedAction::once(Action::InsertChar(*c));
344            }
345            if matches!(key, Key::Enter) {
346                return CountedAction::once(Action::InsertChar('\n'));
347            }
348        }
349        if mode == Mode::Command {
350            if let Key::Char(c) = key {
351                return CountedAction::once(Action::InsertChar(*c));
352            }
353        }
354        if let Some(b) = self.lookup(mode, key) {
355            return CountedAction::repeated(state.pending_count().unwrap_or(1), b.action.clone());
356        }
357        CountedAction::once(Action::Pending)
358    }
359
360    #[must_use]
361    pub fn len(&self) -> usize {
362        self.bindings.len()
363    }
364
365    #[must_use]
366    pub fn is_empty(&self) -> bool {
367        self.bindings.is_empty()
368    }
369
370    /// Sorted view over every binding — for `escriba --keymap` and palettes.
371    #[must_use]
372    pub fn entries_sorted(&self) -> Vec<(&Mode, &Key, &Binding)> {
373        let mut v: Vec<_> = self.bindings.iter().map(|((m, k), b)| (m, k, b)).collect();
374        v.sort_by(|a, b| {
375            (a.0.as_str(), format!("{:?}", a.1)).cmp(&(b.0.as_str(), format!("{:?}", b.1)))
376        });
377        v
378    }
379}
380
381#[cfg(test)]
382mod tests {
383    use super::*;
384
385    #[test]
386    fn default_vim_has_bindings() {
387        let k = Keymap::default_vim();
388        assert!(k.len() > 10);
389        assert!(k.lookup(Mode::Normal, &Key::Char('h')).is_some());
390        assert!(k.lookup(Mode::Insert, &Key::Esc).is_some());
391        assert!(k.lookup(Mode::Normal, &Key::Alt('f')).is_some());
392    }
393
394    #[test]
395    fn dispatch_normal_motion() {
396        let k = Keymap::default_vim();
397        let s = ModalState::new();
398        let a = k.dispatch(&s, &Key::Char('h'));
399        assert_eq!(a.count, 1);
400        assert_eq!(a.action, Action::Move(Motion::Left));
401    }
402
403    #[test]
404    fn dispatch_count_prefix_pends() {
405        let k = Keymap::default_vim();
406        let s = ModalState::new();
407        assert!(matches!(
408            k.dispatch(&s, &Key::Char('5')).action,
409            Action::Pending
410        ));
411    }
412
413    #[test]
414    fn dispatch_insert_char() {
415        let k = Keymap::default_vim();
416        let mut s = ModalState::new();
417        s.enter(Mode::Insert);
418        let a = k.dispatch(&s, &Key::Char('a'));
419        assert_eq!(a.action, Action::InsertChar('a'));
420    }
421
422    #[test]
423    fn lisp_structural_motions_bound() {
424        let k = Keymap::default_vim();
425        assert_eq!(
426            k.lookup(Mode::Normal, &Key::Alt('f')).unwrap().action,
427            Action::Move(Motion::ForwardSexp)
428        );
429    }
430
431    #[test]
432    fn default_leader_is_comma() {
433        assert_eq!(Keymap::new().leader(), &Key::Char(','));
434    }
435
436    #[test]
437    fn bind_sequence_stores_multikey_and_resolves() {
438        let mut k = Keymap::new();
439        let seq = vec![Key::Char(','), Key::Char('f'), Key::Char('f')];
440        k.bind_sequence(
441            Mode::Normal,
442            seq.clone(),
443            Action::Command {
444                name: "picker.files".into(),
445                args: vec![],
446            },
447            "find files",
448        );
449        // Exact match resolves.
450        let b = k.lookup_sequence(Mode::Normal, &seq).expect("seq bound");
451        assert!(matches!(&b.action, Action::Command { name, .. } if name == "picker.files"));
452        // Proper prefixes are live; the full sequence is NOT a prefix
453        // of itself.
454        assert!(k.is_sequence_prefix(Mode::Normal, &[Key::Char(',')]));
455        assert!(k.is_sequence_prefix(Mode::Normal, &[Key::Char(','), Key::Char('f')]));
456        assert!(!k.is_sequence_prefix(Mode::Normal, &seq));
457        // Wrong mode → not a prefix.
458        assert!(!k.is_sequence_prefix(Mode::Insert, &[Key::Char(',')]));
459        assert_eq!(k.sequence_len(), 1);
460    }
461
462    #[test]
463    fn bind_sequence_length_one_delegates_to_single() {
464        let mut k = Keymap::new();
465        k.bind_sequence(
466            Mode::Normal,
467            vec![Key::Char('x')],
468            Action::Undo,
469            "x is undo",
470        );
471        // Lands in the single-key table, not the sequence table.
472        assert_eq!(k.sequence_len(), 0);
473        assert!(k.lookup(Mode::Normal, &Key::Char('x')).is_some());
474    }
475}