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