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(
258 &mut m,
259 Key::Char('n'),
260 Action::Move(Motion::SearchNext),
261 "next match",
262 );
263 nm(
264 &mut m,
265 Key::Char('N'),
266 Action::Move(Motion::SearchPrev),
267 "previous match",
268 );
269
270 nm(&mut m, Key::Ctrl('o'), Action::JumpBack, "jump back");
274 nm(&mut m, Key::Ctrl('i'), Action::JumpForward, "jump forward");
275 nm(
276 &mut m,
277 Key::Char('*'),
278 Action::SearchWord { reverse: false },
279 "search word forward",
280 );
281 nm(
282 &mut m,
283 Key::Char('#'),
284 Action::SearchWord { reverse: true },
285 "search word backward",
286 );
287 m.bind(
288 Mode::Visual,
289 Key::Esc,
290 Action::ChangeMode(Mode::Normal),
291 "to normal",
292 );
293 m.bind(
294 Mode::VisualLine,
295 Key::Esc,
296 Action::ChangeMode(Mode::Normal),
297 "to normal",
298 );
299 m
300 }
301
302 pub fn bind(&mut self, mode: Mode, key: Key, action: Action, desc: impl Into<String>) {
303 self.bindings
304 .insert((mode, key), Binding::new(action, desc));
305 }
306
307 #[must_use]
308 pub fn lookup(&self, mode: Mode, key: &Key) -> Option<&Binding> {
309 self.bindings.get(&(mode, key.clone()))
310 }
311
312 #[must_use]
315 pub fn leader(&self) -> &Key {
316 &self.leader
317 }
318
319 pub fn set_leader(&mut self, key: Key) {
322 self.leader = key;
323 }
324
325 pub fn bind_sequence(
331 &mut self,
332 mode: Mode,
333 keys: Vec<Key>,
334 action: Action,
335 desc: impl Into<String>,
336 ) {
337 match keys.as_slice() {
338 [] => {}
339 [single] => self.bind(mode, single.clone(), action, desc),
340 _ => {
341 self.sequences
342 .insert((mode, keys), Binding::new(action, desc));
343 }
344 }
345 }
346
347 #[must_use]
349 pub fn lookup_sequence(&self, mode: Mode, keys: &[Key]) -> Option<&Binding> {
350 self.sequences.get(&(mode, keys.to_vec()))
351 }
352
353 #[must_use]
360 pub fn is_sequence_prefix(&self, mode: Mode, prefix: &[Key]) -> bool {
361 self.sequences
362 .keys()
363 .any(|(m, seq)| *m == mode && seq.len() > prefix.len() && seq.starts_with(prefix))
364 }
365
366 #[must_use]
368 pub fn sequence_len(&self) -> usize {
369 self.sequences.len()
370 }
371
372 #[must_use]
373 pub fn dispatch(&self, state: &ModalState, key: &Key) -> CountedAction {
374 let mode = state.mode();
375 if mode == Mode::Normal {
376 if let Key::Char(c) = key {
377 if c.is_ascii_digit() && *c != '0' {
378 return CountedAction::once(Action::Pending);
379 }
380 if *c == '0' && state.pending_count().is_some() {
381 return CountedAction::once(Action::Pending);
382 }
383 }
384 }
385 if mode == Mode::Insert {
386 if let Key::Char(c) = key {
387 return CountedAction::once(Action::InsertChar(*c));
388 }
389 if matches!(key, Key::Enter) {
390 return CountedAction::once(Action::InsertChar('\n'));
391 }
392 }
393 if mode == Mode::Command {
394 if let Key::Char(c) = key {
395 return CountedAction::once(Action::InsertChar(*c));
396 }
397 }
398 if let Some(b) = self.lookup(mode, key) {
399 return CountedAction::repeated(state.pending_count().unwrap_or(1), b.action.clone());
400 }
401 CountedAction::once(Action::Pending)
402 }
403
404 #[must_use]
405 pub fn len(&self) -> usize {
406 self.bindings.len()
407 }
408
409 #[must_use]
410 pub fn is_empty(&self) -> bool {
411 self.bindings.is_empty()
412 }
413
414 #[must_use]
416 pub fn entries_sorted(&self) -> Vec<(&Mode, &Key, &Binding)> {
417 let mut v: Vec<_> = self.bindings.iter().map(|((m, k), b)| (m, k, b)).collect();
418 v.sort_by(|a, b| {
419 (a.0.as_str(), format!("{:?}", a.1)).cmp(&(b.0.as_str(), format!("{:?}", b.1)))
420 });
421 v
422 }
423}
424
425#[cfg(test)]
426mod tests {
427 use super::*;
428
429 #[test]
430 fn default_vim_has_bindings() {
431 let k = Keymap::default_vim();
432 assert!(k.len() > 10);
433 assert!(k.lookup(Mode::Normal, &Key::Char('h')).is_some());
434 assert!(k.lookup(Mode::Insert, &Key::Esc).is_some());
435 assert!(k.lookup(Mode::Normal, &Key::Alt('f')).is_some());
436 }
437
438 #[test]
439 fn dispatch_normal_motion() {
440 let k = Keymap::default_vim();
441 let s = ModalState::new();
442 let a = k.dispatch(&s, &Key::Char('h'));
443 assert_eq!(a.count, 1);
444 assert_eq!(a.action, Action::Move(Motion::Left));
445 }
446
447 #[test]
448 fn dispatch_count_prefix_pends() {
449 let k = Keymap::default_vim();
450 let s = ModalState::new();
451 assert!(matches!(
452 k.dispatch(&s, &Key::Char('5')).action,
453 Action::Pending
454 ));
455 }
456
457 #[test]
458 fn dispatch_insert_char() {
459 let k = Keymap::default_vim();
460 let mut s = ModalState::new();
461 s.enter(Mode::Insert);
462 let a = k.dispatch(&s, &Key::Char('a'));
463 assert_eq!(a.action, Action::InsertChar('a'));
464 }
465
466 #[test]
467 fn lisp_structural_motions_bound() {
468 let k = Keymap::default_vim();
469 assert_eq!(
470 k.lookup(Mode::Normal, &Key::Alt('f')).unwrap().action,
471 Action::Move(Motion::ForwardSexp)
472 );
473 }
474
475 #[test]
476 fn default_leader_is_comma() {
477 assert_eq!(Keymap::new().leader(), &Key::Char(','));
478 }
479
480 #[test]
481 fn bind_sequence_stores_multikey_and_resolves() {
482 let mut k = Keymap::new();
483 let seq = vec![Key::Char(','), Key::Char('f'), Key::Char('f')];
484 k.bind_sequence(
485 Mode::Normal,
486 seq.clone(),
487 Action::Command {
488 name: "picker.files".into(),
489 args: vec![],
490 },
491 "find files",
492 );
493 let b = k.lookup_sequence(Mode::Normal, &seq).expect("seq bound");
495 assert!(matches!(&b.action, Action::Command { name, .. } if name == "picker.files"));
496 assert!(k.is_sequence_prefix(Mode::Normal, &[Key::Char(',')]));
499 assert!(k.is_sequence_prefix(Mode::Normal, &[Key::Char(','), Key::Char('f')]));
500 assert!(!k.is_sequence_prefix(Mode::Normal, &seq));
501 assert!(!k.is_sequence_prefix(Mode::Insert, &[Key::Char(',')]));
503 assert_eq!(k.sequence_len(), 1);
504 }
505
506 #[test]
507 fn bind_sequence_length_one_delegates_to_single() {
508 let mut k = Keymap::new();
509 k.bind_sequence(
510 Mode::Normal,
511 vec![Key::Char('x')],
512 Action::Undo,
513 "x is undo",
514 );
515 assert_eq!(k.sequence_len(), 0);
517 assert!(k.lookup(Mode::Normal, &Key::Char('x')).is_some());
518 }
519}