1use crate::command::Command;
16use crate::event::{Key, KeyEvent, KeyModifiers};
17use std::collections::{HashMap, HashSet};
18use std::sync::{OnceLock, RwLock};
19
20#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
34pub struct KeyStroke {
35 pub key: Key,
36 pub ctrl: bool,
37 pub alt: bool,
38 pub shift: bool,
39}
40
41impl KeyStroke {
42 pub fn from_event(ke: KeyEvent) -> Self {
44 let KeyModifiers { shift, ctrl, alt } = ke.modifiers;
45 Self::normalize(ke.key, ctrl, alt, shift)
46 }
47
48 pub(crate) fn normalize(key: Key, ctrl: bool, alt: bool, shift: bool) -> Self {
49 match key {
50 Key::Char(c) if c.is_ascii_alphabetic() => KeyStroke {
51 key: Key::Char(c.to_ascii_lowercase()),
52 ctrl,
53 alt,
54 shift: false,
55 },
56 Key::Left
57 | Key::Right
58 | Key::Up
59 | Key::Down
60 | Key::Home
61 | Key::End
62 | Key::PageUp
63 | Key::PageDown => KeyStroke {
64 key,
65 ctrl,
66 alt,
67 shift: false,
68 },
69 _ => KeyStroke {
70 key,
71 ctrl,
72 alt,
73 shift,
74 },
75 }
76 }
77}
78
79#[derive(Clone, PartialEq, Eq, Hash, Debug)]
81pub struct Chord(pub Vec<KeyStroke>);
82
83pub fn parse_chord(s: &str) -> Result<Chord, String> {
87 let strokes: Vec<&str> = s.split_whitespace().collect();
88 if strokes.is_empty() {
89 return Err(format!("empty chord: {s:?}"));
90 }
91 let mut out = Vec::with_capacity(strokes.len());
92 for stroke in strokes {
93 out.push(parse_stroke(stroke)?);
94 }
95 Ok(Chord(out))
96}
97
98fn parse_stroke(s: &str) -> Result<KeyStroke, String> {
99 let (mut ctrl, mut alt, mut shift) = (false, false, false);
100 let mut key: Option<Key> = None;
101 for tok in s.split('+') {
102 match tok.to_ascii_lowercase().as_str() {
103 "ctrl" | "cmd" | "meta" => ctrl = true,
104 "alt" | "opt" | "option" => alt = true,
105 "shift" => shift = true,
106 other => key = Some(parse_key(other)?),
107 }
108 }
109 let key = key.ok_or_else(|| format!("no key in stroke {s:?}"))?;
110 Ok(KeyStroke::normalize(key, ctrl, alt, shift))
111}
112
113fn parse_key(name: &str) -> Result<Key, String> {
114 Ok(match name {
115 "backspace" | "bs" => Key::Backspace,
116 "delete" | "del" => Key::Delete,
117 "insert" | "ins" => Key::Insert,
118 "home" => Key::Home,
119 "end" => Key::End,
120 "pageup" | "pgup" => Key::PageUp,
121 "pagedown" | "pgdn" => Key::PageDown,
122 "left" => Key::Left,
123 "right" => Key::Right,
124 "up" => Key::Up,
125 "down" => Key::Down,
126 "enter" | "return" => Key::Enter,
127 "tab" => Key::Tab,
128 "esc" | "escape" => Key::Esc,
129 "space" => Key::Char(' '),
130 other => {
131 if let Some(Ok(n)) = other.strip_prefix('f').map(str::parse::<u8>) {
132 return Ok(Key::F(n));
133 }
134 let mut chars = other.chars();
135 if let (Some(c), None) = (chars.next(), chars.clone().next()) {
136 return Ok(Key::Char(c));
137 }
138 return Err(format!("unknown key name {other:?}"));
139 }
140 })
141}
142
143pub enum Resolve {
145 Command(Command),
147 Prefix,
149 None,
151}
152
153#[derive(Clone, Default)]
158pub struct Keymap {
159 bindings: HashMap<Chord, Command>,
160 prefixes: HashSet<KeyStroke>,
161}
162
163impl Keymap {
164 pub fn new() -> Self {
166 Keymap::default()
167 }
168
169 pub fn bind(&mut self, chord: &str, cmd: Command) -> &mut Self {
172 let c = parse_chord(chord).unwrap_or_else(|e| panic!("bad chord {chord:?}: {e}"));
173 if c.0.len() >= 2 {
174 self.prefixes.insert(c.0[0]);
175 }
176 self.bindings.insert(c, cmd);
177 self
178 }
179
180 pub fn unbind(&mut self, chord: &str) -> &mut Self {
182 if let Ok(c) = parse_chord(chord) {
183 self.bindings.remove(&c);
184 self.prefixes = self
186 .bindings
187 .keys()
188 .filter(|k| k.0.len() >= 2)
189 .map(|k| k.0[0])
190 .collect();
191 }
192 self
193 }
194
195 pub fn resolve(&self, pending: Option<KeyStroke>, stroke: KeyStroke) -> Resolve {
197 let chord = match pending {
198 Some(p) => Chord(vec![p, stroke]),
199 None => Chord(vec![stroke]),
200 };
201 if let Some(&cmd) = self.bindings.get(&chord) {
202 return Resolve::Command(cmd);
203 }
204 if pending.is_none() && self.prefixes.contains(&stroke) {
205 return Resolve::Prefix;
206 }
207 Resolve::None
208 }
209
210 pub fn word_star() -> Self {
213 let mut k = Keymap::new();
214 k.bind("ctrl+a", Command::SELECT_ALL)
216 .bind("ctrl+c", Command::PAGE_DOWN)
217 .bind("ctrl+d", Command::CHAR_RIGHT)
218 .bind("ctrl+e", Command::LINE_UP)
219 .bind("ctrl+f", Command::WORD_RIGHT)
220 .bind("ctrl+g", Command::DEL_CHAR)
221 .bind("ctrl+h", Command::BACK_SPACE)
222 .bind("ctrl+l", Command::SEARCH_AGAIN)
223 .bind("ctrl+m", Command::NEW_LINE)
224 .bind("ctrl+o", Command::INDENT_MODE)
225 .bind("ctrl+p", Command::ENCODING)
226 .bind("ctrl+r", Command::PAGE_UP)
227 .bind("ctrl+s", Command::CHAR_LEFT)
228 .bind("ctrl+t", Command::DEL_WORD)
229 .bind("ctrl+u", Command::UNDO)
230 .bind("ctrl+v", Command::INS_MODE)
231 .bind("ctrl+x", Command::LINE_DOWN)
232 .bind("ctrl+y", Command::DEL_LINE);
233 k.bind("left", Command::CHAR_LEFT)
235 .bind("right", Command::CHAR_RIGHT)
236 .bind("backspace", Command::BACK_SPACE) .bind("alt+backspace", Command::DEL_WORD_LEFT)
238 .bind("ctrl+backspace", Command::DEL_WORD_LEFT)
239 .bind("ctrl+delete", Command::DEL_WORD)
240 .bind("ctrl+left", Command::WORD_LEFT)
241 .bind("ctrl+right", Command::WORD_RIGHT)
242 .bind("home", Command::LINE_START)
243 .bind("end", Command::LINE_END)
244 .bind("up", Command::LINE_UP)
245 .bind("down", Command::LINE_DOWN)
246 .bind("pageup", Command::PAGE_UP)
247 .bind("pagedown", Command::PAGE_DOWN)
248 .bind("ctrl+home", Command::TEXT_START)
249 .bind("ctrl+end", Command::TEXT_END)
250 .bind("insert", Command::INS_MODE)
251 .bind("delete", Command::DEL_CHAR)
252 .bind("shift+insert", Command::PASTE)
253 .bind("shift+delete", Command::CUT)
254 .bind("ctrl+insert", Command::COPY)
255 .bind("enter", Command::NEW_LINE);
256 k.bind("ctrl+q a", Command::REPLACE)
258 .bind("ctrl+q c", Command::TEXT_END)
259 .bind("ctrl+q d", Command::LINE_END)
260 .bind("ctrl+q f", Command::FIND)
261 .bind("ctrl+q h", Command::DEL_START)
262 .bind("ctrl+q r", Command::TEXT_START)
263 .bind("ctrl+q s", Command::LINE_START)
264 .bind("ctrl+q y", Command::DEL_END);
265 k.bind("ctrl+k b", Command::START_SELECT)
267 .bind("ctrl+k c", Command::PASTE)
268 .bind("ctrl+k h", Command::HIDE_SELECT)
269 .bind("ctrl+k k", Command::COPY)
270 .bind("ctrl+k y", Command::CUT);
271 k
272 }
273
274 pub fn cua() -> Self {
276 let mut k = Keymap::new();
277 k.bind("ctrl+c", Command::COPY)
278 .bind("ctrl+x", Command::CUT)
279 .bind("ctrl+v", Command::PASTE)
280 .bind("ctrl+z", Command::UNDO)
281 .bind("ctrl+a", Command::SELECT_ALL)
282 .bind("ctrl+f", Command::FIND)
283 .bind("backspace", Command::BACK_SPACE)
284 .bind("delete", Command::DEL_CHAR)
285 .bind("ctrl+backspace", Command::DEL_WORD_LEFT)
286 .bind("ctrl+delete", Command::DEL_WORD)
287 .bind("left", Command::CHAR_LEFT)
288 .bind("right", Command::CHAR_RIGHT)
289 .bind("ctrl+left", Command::WORD_LEFT)
290 .bind("ctrl+right", Command::WORD_RIGHT)
291 .bind("up", Command::LINE_UP)
292 .bind("down", Command::LINE_DOWN)
293 .bind("home", Command::LINE_START)
294 .bind("end", Command::LINE_END)
295 .bind("ctrl+home", Command::TEXT_START)
296 .bind("ctrl+end", Command::TEXT_END)
297 .bind("pageup", Command::PAGE_UP)
298 .bind("pagedown", Command::PAGE_DOWN)
299 .bind("insert", Command::INS_MODE)
300 .bind("enter", Command::NEW_LINE);
301 k
302 }
303
304 pub fn emacs() -> Self {
306 let mut k = Keymap::new();
307 k.bind("ctrl+a", Command::LINE_START)
308 .bind("ctrl+e", Command::LINE_END)
309 .bind("ctrl+f", Command::CHAR_RIGHT)
310 .bind("ctrl+b", Command::CHAR_LEFT)
311 .bind("ctrl+n", Command::LINE_DOWN)
312 .bind("ctrl+p", Command::LINE_UP)
313 .bind("ctrl+d", Command::DEL_CHAR)
314 .bind("ctrl+k", Command::DEL_END)
315 .bind("ctrl+y", Command::PASTE)
316 .bind("alt+f", Command::WORD_RIGHT)
317 .bind("alt+b", Command::WORD_LEFT)
318 .bind("backspace", Command::BACK_SPACE)
319 .bind("delete", Command::DEL_CHAR)
320 .bind("left", Command::CHAR_LEFT)
321 .bind("right", Command::CHAR_RIGHT)
322 .bind("up", Command::LINE_UP)
323 .bind("down", Command::LINE_DOWN)
324 .bind("home", Command::LINE_START)
325 .bind("end", Command::LINE_END)
326 .bind("enter", Command::NEW_LINE);
327 k
328 }
329}
330
331fn global_cell() -> &'static RwLock<Keymap> {
332 static GLOBAL: OnceLock<RwLock<Keymap>> = OnceLock::new();
333 GLOBAL.get_or_init(|| RwLock::new(Keymap::word_star()))
334}
335
336pub fn set_global(km: Keymap) {
338 *global_cell().write().expect("keymap lock poisoned") = km;
339}
340
341pub fn resolve_global(pending: Option<KeyStroke>, stroke: KeyStroke) -> Resolve {
343 #[cfg(test)]
344 if let Some(r) = TEST_KEYMAP.with(|o| o.borrow().as_ref().map(|km| km.resolve(pending, stroke)))
345 {
346 return r;
347 }
348 global_cell()
349 .read()
350 .expect("keymap lock poisoned")
351 .resolve(pending, stroke)
352}
353
354#[cfg(test)]
355thread_local! {
356 static TEST_KEYMAP: std::cell::RefCell<Option<Keymap>> =
359 const { std::cell::RefCell::new(None) };
360}
361
362#[cfg(test)]
369pub(crate) struct GlobalKeymapGuard(());
370
371#[cfg(test)]
372impl GlobalKeymapGuard {
373 pub(crate) fn new(km: Keymap) -> Self {
374 TEST_KEYMAP.with(|o| *o.borrow_mut() = Some(km));
375 GlobalKeymapGuard(())
376 }
377}
378
379#[cfg(test)]
380impl Drop for GlobalKeymapGuard {
381 fn drop(&mut self) {
382 TEST_KEYMAP.with(|o| *o.borrow_mut() = None);
383 }
384}
385
386#[cfg(test)]
387mod tests {
388 use super::*;
389
390 fn ev(key: Key, ctrl: bool, alt: bool, shift: bool) -> KeyEvent {
391 KeyEvent::new(key, KeyModifiers { shift, ctrl, alt })
392 }
393
394 #[test]
395 fn letters_fold_case_and_shift() {
396 let lower = KeyStroke::from_event(ev(Key::Char('a'), true, false, false));
397 let upper = KeyStroke::from_event(ev(Key::Char('A'), true, false, true));
398 assert_eq!(lower, upper);
399 assert_eq!(lower.key, Key::Char('a'));
400 assert!(!lower.shift);
401 }
402
403 #[test]
404 fn shift_arrow_equals_arrow() {
405 let plain = KeyStroke::from_event(ev(Key::Left, false, false, false));
406 let shifted = KeyStroke::from_event(ev(Key::Left, false, false, true));
407 assert_eq!(plain, shifted);
408 }
409
410 #[test]
411 fn shift_insert_stays_distinct() {
412 let plain = KeyStroke::from_event(ev(Key::Insert, false, false, false));
413 let shifted = KeyStroke::from_event(ev(Key::Insert, false, false, true));
414 assert_ne!(plain, shifted);
415 }
416
417 #[test]
418 fn parse_single_stroke() {
419 let c = parse_chord("ctrl+c").unwrap();
420 assert_eq!(c.0.len(), 1);
421 assert_eq!(
422 c.0[0],
423 KeyStroke::normalize(Key::Char('c'), true, false, false)
424 );
425 }
426
427 #[test]
428 fn parse_named_and_modifiers() {
429 assert_eq!(
430 parse_chord("shift+insert").unwrap().0[0],
431 KeyStroke::normalize(Key::Insert, false, false, true)
432 );
433 assert_eq!(
434 parse_chord("alt+backspace").unwrap().0[0],
435 KeyStroke::normalize(Key::Backspace, false, true, false)
436 );
437 assert_eq!(
438 parse_chord("f5").unwrap().0[0],
439 KeyStroke::normalize(Key::F(5), false, false, false)
440 );
441 }
442
443 #[test]
444 fn parse_two_stroke_chord() {
445 let c = parse_chord("ctrl+k ctrl+c").unwrap();
446 assert_eq!(c.0.len(), 2);
447 }
448
449 #[test]
450 fn parse_rejects_garbage() {
451 assert!(parse_chord("ctrl+nope").is_err());
452 assert!(parse_chord("").is_err());
453 }
454
455 #[test]
456 fn resolve_single_and_prefix_and_miss() {
457 let mut km = Keymap::new();
458 km.bind("ctrl+s", Command::CHAR_LEFT);
459 km.bind("ctrl+k ctrl+c", Command::COPY);
460
461 let s = KeyStroke::from_event(ev(Key::Char('s'), true, false, false));
462 assert!(matches!(km.resolve(None, s), Resolve::Command(c) if c == Command::CHAR_LEFT));
463
464 let k = KeyStroke::from_event(ev(Key::Char('k'), true, false, false));
465 assert!(matches!(km.resolve(None, k), Resolve::Prefix));
466
467 let c = KeyStroke::from_event(ev(Key::Char('c'), true, false, false));
468 assert!(matches!(km.resolve(Some(k), c), Resolve::Command(cmd) if cmd == Command::COPY));
469
470 let z = KeyStroke::from_event(ev(Key::Char('z'), true, false, false));
472 assert!(matches!(km.resolve(Some(k), z), Resolve::None));
473 }
474
475 #[test]
476 fn global_default_is_word_star_and_settable() {
477 let local = Keymap::word_star();
481 let bs = KeyStroke::from_event(ev(Key::Backspace, false, false, false));
482 assert!(matches!(local.resolve(None, bs), Resolve::Command(c) if c == Command::BACK_SPACE));
483
484 let cc = KeyStroke::from_event(ev(Key::Char('c'), true, false, false));
487 {
488 let _g = GlobalKeymapGuard::new(Keymap::cua());
489 assert!(matches!(resolve_global(None, cc), Resolve::Command(c) if c == Command::COPY));
490 }
491 assert!(
492 !matches!(resolve_global(None, cc), Resolve::Command(c) if c == Command::COPY),
493 "the guard's map is gone after drop"
494 );
495 }
496
497 #[test]
498 fn word_star_transcribes_editor_tables_plus_backspace_fix() {
499 let km = Keymap::word_star();
500 let r = |k: Key, ctrl, alt, shift| {
501 km.resolve(None, KeyStroke::from_event(ev(k, ctrl, alt, shift)))
502 };
503 assert!(
505 matches!(r(Key::Backspace, false, false, false), Resolve::Command(c) if c == Command::BACK_SPACE)
506 );
507 assert!(
509 matches!(r(Key::Char('s'), true, false, false), Resolve::Command(c) if c == Command::CHAR_LEFT)
510 );
511 assert!(
512 matches!(r(Key::Char('a'), true, false, false), Resolve::Command(c) if c == Command::SELECT_ALL)
513 );
514 assert!(matches!(
515 r(Key::Char('q'), true, false, false),
516 Resolve::Prefix
517 ));
518 assert!(
519 matches!(r(Key::Enter, false, false, false), Resolve::Command(c) if c == Command::NEW_LINE)
520 );
521 let q = KeyStroke::from_event(ev(Key::Char('q'), true, false, false));
523 let f = KeyStroke::from_event(ev(Key::Char('f'), false, false, false));
524 assert!(matches!(km.resolve(Some(q), f), Resolve::Command(c) if c == Command::FIND));
525 }
526
527 #[test]
528 fn cua_and_emacs_core_bindings() {
529 let cua = Keymap::cua();
530 let r = |km: &Keymap, k: Key, ctrl| {
531 km.resolve(None, KeyStroke::from_event(ev(k, ctrl, false, false)))
532 };
533 assert!(matches!(r(&cua, Key::Char('c'), true), Resolve::Command(c) if c == Command::COPY));
534 assert!(
535 matches!(r(&cua, Key::Char('v'), true), Resolve::Command(c) if c == Command::PASTE)
536 );
537 assert!(matches!(r(&cua, Key::Char('z'), true), Resolve::Command(c) if c == Command::UNDO));
538
539 let em = Keymap::emacs();
540 assert!(
541 matches!(r(&em, Key::Char('a'), true), Resolve::Command(c) if c == Command::LINE_START)
542 );
543 assert!(
544 matches!(r(&em, Key::Char('e'), true), Resolve::Command(c) if c == Command::LINE_END)
545 );
546 }
547}