1extern 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 sequences: HashMap<(Mode, Vec<Key>), Binding>,
55 leader: Key,
57}
58
59impl Default for Keymap {
60 fn default() -> Self {
61 Self {
62 bindings: HashMap::new(),
63 sequences: HashMap::new(),
64 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 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 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 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 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
235 nm(
240 &mut m,
241 Key::Char('/'),
242 Action::SearchOpen(SearchDirection::Forward),
243 "search forward",
244 );
245 nm(
246 &mut m,
247 Key::Char('?'),
248 Action::SearchOpen(SearchDirection::Backward),
249 "search backward",
250 );
251 nm(&mut m, Key::Char('n'), Action::SearchRepeat { reverse: false }, "next match");
252 nm(&mut m, Key::Char('N'), Action::SearchRepeat { reverse: true }, "previous match");
253 nm(&mut m, Key::Char('*'), Action::SearchWord { reverse: false }, "search word forward");
254 nm(&mut m, Key::Char('#'), Action::SearchWord { reverse: true }, "search word backward");
255 m.bind(
256 Mode::Visual,
257 Key::Esc,
258 Action::ChangeMode(Mode::Normal),
259 "to normal",
260 );
261 m.bind(
262 Mode::VisualLine,
263 Key::Esc,
264 Action::ChangeMode(Mode::Normal),
265 "to normal",
266 );
267 m
268 }
269
270 pub fn bind(&mut self, mode: Mode, key: Key, action: Action, desc: impl Into<String>) {
271 self.bindings
272 .insert((mode, key), Binding::new(action, desc));
273 }
274
275 #[must_use]
276 pub fn lookup(&self, mode: Mode, key: &Key) -> Option<&Binding> {
277 self.bindings.get(&(mode, key.clone()))
278 }
279
280 #[must_use]
283 pub fn leader(&self) -> &Key {
284 &self.leader
285 }
286
287 pub fn set_leader(&mut self, key: Key) {
290 self.leader = key;
291 }
292
293 pub fn bind_sequence(
299 &mut self,
300 mode: Mode,
301 keys: Vec<Key>,
302 action: Action,
303 desc: impl Into<String>,
304 ) {
305 match keys.as_slice() {
306 [] => {}
307 [single] => self.bind(mode, single.clone(), action, desc),
308 _ => {
309 self.sequences
310 .insert((mode, keys), Binding::new(action, desc));
311 }
312 }
313 }
314
315 #[must_use]
317 pub fn lookup_sequence(&self, mode: Mode, keys: &[Key]) -> Option<&Binding> {
318 self.sequences.get(&(mode, keys.to_vec()))
319 }
320
321 #[must_use]
328 pub fn is_sequence_prefix(&self, mode: Mode, prefix: &[Key]) -> bool {
329 self.sequences
330 .keys()
331 .any(|(m, seq)| *m == mode && seq.len() > prefix.len() && seq.starts_with(prefix))
332 }
333
334 #[must_use]
336 pub fn sequence_len(&self) -> usize {
337 self.sequences.len()
338 }
339
340 #[must_use]
341 pub fn dispatch(&self, state: &ModalState, key: &Key) -> CountedAction {
342 let mode = state.mode();
343 if mode == Mode::Normal {
344 if let Key::Char(c) = key {
345 if c.is_ascii_digit() && *c != '0' {
346 return CountedAction::once(Action::Pending);
347 }
348 if *c == '0' && state.pending_count().is_some() {
349 return CountedAction::once(Action::Pending);
350 }
351 }
352 }
353 if mode == Mode::Insert {
354 if let Key::Char(c) = key {
355 return CountedAction::once(Action::InsertChar(*c));
356 }
357 if matches!(key, Key::Enter) {
358 return CountedAction::once(Action::InsertChar('\n'));
359 }
360 }
361 if mode == Mode::Command {
362 if let Key::Char(c) = key {
363 return CountedAction::once(Action::InsertChar(*c));
364 }
365 }
366 if let Some(b) = self.lookup(mode, key) {
367 return CountedAction::repeated(state.pending_count().unwrap_or(1), b.action.clone());
368 }
369 CountedAction::once(Action::Pending)
370 }
371
372 #[must_use]
373 pub fn len(&self) -> usize {
374 self.bindings.len()
375 }
376
377 #[must_use]
378 pub fn is_empty(&self) -> bool {
379 self.bindings.is_empty()
380 }
381
382 #[must_use]
384 pub fn entries_sorted(&self) -> Vec<(&Mode, &Key, &Binding)> {
385 let mut v: Vec<_> = self.bindings.iter().map(|((m, k), b)| (m, k, b)).collect();
386 v.sort_by(|a, b| {
387 (a.0.as_str(), format!("{:?}", a.1)).cmp(&(b.0.as_str(), format!("{:?}", b.1)))
388 });
389 v
390 }
391}
392
393#[cfg(test)]
394mod tests {
395 use super::*;
396
397 #[test]
398 fn default_vim_has_bindings() {
399 let k = Keymap::default_vim();
400 assert!(k.len() > 10);
401 assert!(k.lookup(Mode::Normal, &Key::Char('h')).is_some());
402 assert!(k.lookup(Mode::Insert, &Key::Esc).is_some());
403 assert!(k.lookup(Mode::Normal, &Key::Alt('f')).is_some());
404 }
405
406 #[test]
407 fn dispatch_normal_motion() {
408 let k = Keymap::default_vim();
409 let s = ModalState::new();
410 let a = k.dispatch(&s, &Key::Char('h'));
411 assert_eq!(a.count, 1);
412 assert_eq!(a.action, Action::Move(Motion::Left));
413 }
414
415 #[test]
416 fn dispatch_count_prefix_pends() {
417 let k = Keymap::default_vim();
418 let s = ModalState::new();
419 assert!(matches!(
420 k.dispatch(&s, &Key::Char('5')).action,
421 Action::Pending
422 ));
423 }
424
425 #[test]
426 fn dispatch_insert_char() {
427 let k = Keymap::default_vim();
428 let mut s = ModalState::new();
429 s.enter(Mode::Insert);
430 let a = k.dispatch(&s, &Key::Char('a'));
431 assert_eq!(a.action, Action::InsertChar('a'));
432 }
433
434 #[test]
435 fn lisp_structural_motions_bound() {
436 let k = Keymap::default_vim();
437 assert_eq!(
438 k.lookup(Mode::Normal, &Key::Alt('f')).unwrap().action,
439 Action::Move(Motion::ForwardSexp)
440 );
441 }
442
443 #[test]
444 fn default_leader_is_comma() {
445 assert_eq!(Keymap::new().leader(), &Key::Char(','));
446 }
447
448 #[test]
449 fn bind_sequence_stores_multikey_and_resolves() {
450 let mut k = Keymap::new();
451 let seq = vec![Key::Char(','), Key::Char('f'), Key::Char('f')];
452 k.bind_sequence(
453 Mode::Normal,
454 seq.clone(),
455 Action::Command {
456 name: "picker.files".into(),
457 args: vec![],
458 },
459 "find files",
460 );
461 let b = k.lookup_sequence(Mode::Normal, &seq).expect("seq bound");
463 assert!(matches!(&b.action, Action::Command { name, .. } if name == "picker.files"));
464 assert!(k.is_sequence_prefix(Mode::Normal, &[Key::Char(',')]));
467 assert!(k.is_sequence_prefix(Mode::Normal, &[Key::Char(','), Key::Char('f')]));
468 assert!(!k.is_sequence_prefix(Mode::Normal, &seq));
469 assert!(!k.is_sequence_prefix(Mode::Insert, &[Key::Char(',')]));
471 assert_eq!(k.sequence_len(), 1);
472 }
473
474 #[test]
475 fn bind_sequence_length_one_delegates_to_single() {
476 let mut k = Keymap::new();
477 k.bind_sequence(
478 Mode::Normal,
479 vec![Key::Char('x')],
480 Action::Undo,
481 "x is undo",
482 );
483 assert_eq!(k.sequence_len(), 0);
485 assert!(k.lookup(Mode::Normal, &Key::Char('x')).is_some());
486 }
487}