1mod binding;
4mod context;
5mod file;
7
8pub use binding::*;
9pub use context::*;
10pub use file::load_keymap_json;
11
12use crate::collections::{HashSet, TypeIdHashMap};
13use crate::{Action, AsKeystroke, Keystroke, Unbind, is_no_action, is_unbind};
14use smallvec::SmallVec;
15
16#[derive(Copy, Clone, Eq, PartialEq, Default)]
19pub struct KeymapVersion(usize);
20
21#[derive(Default)]
23pub struct Keymap {
24 bindings: Vec<KeyBinding>,
25 binding_indices_by_action_id: TypeIdHashMap<SmallVec<[usize; 3]>>,
26 disabled_binding_indices: Vec<usize>,
27 version: KeymapVersion,
28}
29
30#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
32pub struct BindingIndex(usize);
33
34fn disabled_binding_matches_context(disabled_binding: &KeyBinding, binding: &KeyBinding) -> bool {
35 match (
36 &disabled_binding.context_predicate,
37 &binding.context_predicate,
38 ) {
39 (None, _) => true,
40 (Some(_), None) => false,
41 (Some(disabled_predicate), Some(predicate)) => disabled_predicate.is_superset(predicate),
42 }
43}
44
45fn binding_is_unbound(disabled_binding: &KeyBinding, binding: &KeyBinding) -> bool {
46 disabled_binding.keystrokes == binding.keystrokes
47 && disabled_binding
48 .action()
49 .as_any()
50 .downcast_ref::<Unbind>()
51 .is_some_and(|unbind| unbind.0.as_ref() == binding.action.name())
52}
53
54impl Keymap {
55 pub fn new(bindings: Vec<KeyBinding>) -> Self {
57 let mut this = Self::default();
58 this.add_bindings(bindings);
59 this
60 }
61
62 pub fn version(&self) -> KeymapVersion {
64 self.version
65 }
66
67 pub fn add_bindings<T: IntoIterator<Item = KeyBinding>>(&mut self, bindings: T) {
69 for binding in bindings {
70 let action_id = binding.action().as_any().type_id();
71 if is_no_action(&*binding.action) || is_unbind(&*binding.action) {
72 self.disabled_binding_indices.push(self.bindings.len());
73 } else {
74 self.binding_indices_by_action_id
75 .entry(action_id)
76 .or_default()
77 .push(self.bindings.len());
78 }
79 self.bindings.push(binding);
80 }
81
82 self.version.0 += 1;
83 }
84
85 pub fn clear(&mut self) {
87 self.bindings.clear();
88 self.binding_indices_by_action_id.clear();
89 self.disabled_binding_indices.clear();
90 self.version.0 += 1;
91 }
92
93 pub fn bindings(&self) -> impl DoubleEndedIterator<Item = &KeyBinding> + ExactSizeIterator {
95 self.bindings.iter()
96 }
97
98 pub fn bindings_for_action<'a>(
101 &'a self,
102 action: &'a dyn Action,
103 ) -> impl 'a + DoubleEndedIterator<Item = &'a KeyBinding> {
104 let action_id = action.type_id();
105 let binding_indices = self
106 .binding_indices_by_action_id
107 .get(&action_id)
108 .map_or(&[] as _, SmallVec::as_slice)
109 .iter();
110
111 binding_indices.filter_map(|ix| {
112 let binding = &self.bindings[*ix];
113 if !binding.action().partial_eq(action) {
114 return None;
115 }
116
117 for disabled_ix in &self.disabled_binding_indices {
118 if disabled_ix > ix {
119 let disabled_binding = &self.bindings[*disabled_ix];
120 if disabled_binding.keystrokes != binding.keystrokes {
121 continue;
122 }
123
124 if is_no_action(&*disabled_binding.action) {
125 if disabled_binding_matches_context(disabled_binding, binding) {
126 return None;
127 }
128 } else if is_unbind(&*disabled_binding.action)
129 && disabled_binding_matches_context(disabled_binding, binding)
130 && binding_is_unbound(disabled_binding, binding)
131 {
132 return None;
133 }
134 }
135 }
136
137 Some(binding)
138 })
139 }
140
141 pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
144 self.bindings()
145 .rev()
146 .filter(|binding| {
147 binding
148 .match_keystrokes(input)
149 .is_some_and(|pending| !pending)
150 })
151 .cloned()
152 .collect()
153 }
154
155 pub fn bindings_for_input(
168 &self,
169 input: &[impl AsKeystroke],
170 context_stack: &[KeyContext],
171 ) -> (SmallVec<[KeyBinding; 1]>, bool) {
172 let mut matched_bindings = SmallVec::<[(usize, BindingIndex, &KeyBinding); 1]>::new();
173 let mut pending_bindings = SmallVec::<[(BindingIndex, &KeyBinding); 1]>::new();
174
175 for (ix, binding) in self.bindings().enumerate().rev() {
176 let Some(depth) = self.binding_enabled(binding, context_stack) else {
177 continue;
178 };
179 let Some(pending) = binding.match_keystrokes(input) else {
180 continue;
181 };
182
183 if !pending {
184 matched_bindings.push((depth, BindingIndex(ix), binding));
185 } else {
186 pending_bindings.push((BindingIndex(ix), binding));
187 }
188 }
189
190 matched_bindings.sort_by(|(depth_a, ix_a, _), (depth_b, ix_b, _)| {
191 depth_b.cmp(depth_a).then(ix_b.cmp(ix_a))
192 });
193
194 let mut bindings: SmallVec<[_; 1]> = SmallVec::new();
195 let mut first_binding_index = None;
196 let mut unbound_bindings: Vec<&KeyBinding> = Vec::new();
197
198 for (_, ix, binding) in matched_bindings {
199 if is_no_action(&*binding.action) {
200 if let Some(meta) = binding.meta {
203 if meta.0 == 0 {
204 break;
205 }
206 } else {
207 break;
209 }
210 continue;
212 }
213
214 if is_unbind(&*binding.action) {
215 unbound_bindings.push(binding);
216 continue;
217 }
218
219 if unbound_bindings
220 .iter()
221 .any(|disabled_binding| binding_is_unbound(disabled_binding, binding))
222 {
223 continue;
224 }
225
226 bindings.push(binding.clone());
227 first_binding_index.get_or_insert(ix);
228 }
229
230 let mut pending = HashSet::default();
231 for (ix, binding) in pending_bindings.into_iter().rev() {
232 if let Some(binding_ix) = first_binding_index
233 && binding_ix > ix
234 {
235 continue;
236 }
237 if is_no_action(&*binding.action) || is_unbind(&*binding.action) {
238 pending.remove(&&binding.keystrokes);
239 continue;
240 }
241 pending.insert(&binding.keystrokes);
242 }
243
244 (bindings, !pending.is_empty())
245 }
246 fn binding_enabled(&self, binding: &KeyBinding, contexts: &[KeyContext]) -> Option<usize> {
249 if let Some(predicate) = &binding.context_predicate {
250 predicate.depth_of(contexts)
251 } else {
252 Some(contexts.len())
253 }
254 }
255
256 pub fn possible_next_bindings_for_input(
258 &self,
259 input: &[Keystroke],
260 context_stack: &[KeyContext],
261 ) -> Vec<KeyBinding> {
262 let mut bindings = self
263 .bindings()
264 .enumerate()
265 .rev()
266 .filter_map(|(ix, binding)| {
267 let depth = self.binding_enabled(binding, context_stack)?;
268 let pending = binding.match_keystrokes(input);
269 match pending {
270 None => None,
271 Some(is_pending) => {
272 if !is_pending
273 || is_no_action(&*binding.action)
274 || is_unbind(&*binding.action)
275 {
276 return None;
277 }
278 Some((depth, BindingIndex(ix), binding))
279 }
280 }
281 })
282 .collect::<Vec<_>>();
283
284 bindings.sort_by(|(depth_a, ix_a, _), (depth_b, ix_b, _)| {
285 depth_b.cmp(depth_a).then(ix_b.cmp(ix_a))
286 });
287
288 bindings
289 .into_iter()
290 .map(|(_, _, binding)| binding.clone())
291 .collect::<Vec<_>>()
292 }
293}
294
295#[cfg(test)]
296mod tests {
297 use super::*;
298 use crate as rgpui;
299 use rgpui::{NoAction, Unbind};
300
301 actions!(
302 test_only,
303 [ActionAlpha, ActionBeta, ActionGamma, ActionDelta,]
304 );
305
306 #[test]
307 fn test_keymap() {
308 let bindings = [
309 KeyBinding::new("ctrl-a", ActionAlpha {}, None),
310 KeyBinding::new("ctrl-a", ActionBeta {}, Some("pane")),
311 KeyBinding::new("ctrl-a", ActionGamma {}, Some("editor && mode==full")),
312 ];
313
314 let mut keymap = Keymap::default();
315 keymap.add_bindings(bindings.clone());
316
317 assert_eq!(keymap.binding_enabled(&bindings[0], &[]), Some(0));
319 assert_eq!(
320 keymap.binding_enabled(&bindings[0], &[KeyContext::parse("terminal").unwrap()]),
321 Some(1)
322 );
323
324 assert_eq!(
326 keymap.binding_enabled(&bindings[1], &[KeyContext::parse("barf x=y").unwrap()]),
327 None
328 );
329 assert_eq!(
330 keymap.binding_enabled(&bindings[1], &[KeyContext::parse("pane x=y").unwrap()]),
331 Some(1)
332 );
333
334 assert_eq!(
335 keymap.binding_enabled(&bindings[2], &[KeyContext::parse("editor").unwrap()]),
336 None
337 );
338 assert_eq!(
339 keymap.binding_enabled(
340 &bindings[2],
341 &[KeyContext::parse("editor mode=full").unwrap()]
342 ),
343 Some(1)
344 );
345 }
346
347 #[test]
348 fn test_depth_precedence() {
349 let bindings = [
350 KeyBinding::new("ctrl-a", ActionBeta {}, Some("pane")),
351 KeyBinding::new("ctrl-a", ActionGamma {}, Some("editor")),
352 ];
353
354 let mut keymap = Keymap::default();
355 keymap.add_bindings(bindings);
356
357 let (result, pending) = keymap.bindings_for_input(
358 &[Keystroke::parse("ctrl-a").unwrap()],
359 &[
360 KeyContext::parse("pane").unwrap(),
361 KeyContext::parse("editor").unwrap(),
362 ],
363 );
364
365 assert!(!pending);
366 assert_eq!(result.len(), 2);
367 assert!(result[0].action.partial_eq(&ActionGamma {}));
368 assert!(result[1].action.partial_eq(&ActionBeta {}));
369 }
370
371 #[test]
372 fn test_keymap_disabled() {
373 let bindings = [
374 KeyBinding::new("ctrl-a", ActionAlpha {}, Some("editor")),
375 KeyBinding::new("ctrl-b", ActionAlpha {}, Some("editor")),
376 KeyBinding::new("ctrl-a", NoAction {}, Some("editor && mode==full")),
377 KeyBinding::new("ctrl-b", NoAction {}, None),
378 ];
379
380 let mut keymap = Keymap::default();
381 keymap.add_bindings(bindings);
382
383 assert!(
385 keymap
386 .bindings_for_input(
387 &[Keystroke::parse("ctrl-a").unwrap()],
388 &[KeyContext::parse("barf").unwrap()],
389 )
390 .0
391 .is_empty()
392 );
393 assert!(
394 !keymap
395 .bindings_for_input(
396 &[Keystroke::parse("ctrl-a").unwrap()],
397 &[KeyContext::parse("editor").unwrap()],
398 )
399 .0
400 .is_empty()
401 );
402
403 assert!(
405 keymap
406 .bindings_for_input(
407 &[Keystroke::parse("ctrl-a").unwrap()],
408 &[KeyContext::parse("editor mode=full").unwrap()],
409 )
410 .0
411 .is_empty()
412 );
413
414 assert!(
416 keymap
417 .bindings_for_input(
418 &[Keystroke::parse("ctrl-b").unwrap()],
419 &[KeyContext::parse("barf").unwrap()],
420 )
421 .0
422 .is_empty()
423 );
424 }
425
426 #[test]
427 fn test_multiple_keystroke_binding_disabled() {
429 let bindings = [
430 KeyBinding::new("space w w", ActionAlpha {}, Some("workspace")),
431 KeyBinding::new("space w w", NoAction {}, Some("editor")),
432 ];
433
434 let mut keymap = Keymap::default();
435 keymap.add_bindings(bindings);
436
437 let space = || Keystroke::parse("space").unwrap();
438 let w = || Keystroke::parse("w").unwrap();
439
440 let space_w = [space(), w()];
441 let space_w_w = [space(), w(), w()];
442
443 let workspace_context = || [KeyContext::parse("workspace").unwrap()];
444
445 let editor_workspace_context = || {
446 [
447 KeyContext::parse("workspace").unwrap(),
448 KeyContext::parse("editor").unwrap(),
449 ]
450 };
451
452 let space_workspace = keymap.bindings_for_input(&[space()], &workspace_context());
454 assert!(space_workspace.0.is_empty());
455 assert!(space_workspace.1);
456
457 let space_editor = keymap.bindings_for_input(&[space()], &editor_workspace_context());
458 assert!(space_editor.0.is_empty());
459 assert!(!space_editor.1);
460
461 let space_w_workspace = keymap.bindings_for_input(&space_w, &workspace_context());
463 assert!(space_w_workspace.0.is_empty());
464 assert!(space_w_workspace.1);
465
466 let space_w_editor = keymap.bindings_for_input(&space_w, &editor_workspace_context());
467 assert!(space_w_editor.0.is_empty());
468 assert!(!space_w_editor.1);
469
470 let space_w_w_workspace = keymap.bindings_for_input(&space_w_w, &workspace_context());
472 assert!(!space_w_w_workspace.0.is_empty());
473 assert!(!space_w_w_workspace.1);
474
475 let space_w_w_editor = keymap.bindings_for_input(&space_w_w, &editor_workspace_context());
476 assert!(space_w_w_editor.0.is_empty());
477 assert!(!space_w_w_editor.1);
478
479 let bindings = [
482 KeyBinding::new("space w w", ActionAlpha {}, Some("workspace")),
483 KeyBinding::new("space w w", NoAction {}, Some("editor")),
484 KeyBinding::new("space w x", ActionAlpha {}, Some("editor")),
485 ];
486 let mut keymap = Keymap::default();
487 keymap.add_bindings(bindings);
488
489 let space_editor = keymap.bindings_for_input(&[space()], &editor_workspace_context());
490 assert!(space_editor.0.is_empty());
491 assert!(space_editor.1);
492
493 let bindings = [
496 KeyBinding::new("space w w", ActionAlpha {}, Some("workspace")),
497 KeyBinding::new("space w x", ActionAlpha {}, Some("editor")),
498 KeyBinding::new("space w w", NoAction {}, Some("editor")),
499 ];
500 let mut keymap = Keymap::default();
501 keymap.add_bindings(bindings);
502
503 let space_editor = keymap.bindings_for_input(&[space()], &editor_workspace_context());
504 assert!(space_editor.0.is_empty());
505 assert!(space_editor.1);
506
507 let bindings = [
510 KeyBinding::new("space w w", ActionAlpha {}, Some("workspace")),
511 KeyBinding::new("space w x", ActionAlpha {}, Some("workspace")),
512 KeyBinding::new("space w w", NoAction {}, Some("editor")),
513 ];
514 let mut keymap = Keymap::default();
515 keymap.add_bindings(bindings);
516
517 let space_editor = keymap.bindings_for_input(&[space()], &editor_workspace_context());
518 assert!(space_editor.0.is_empty());
519 assert!(space_editor.1);
520 }
521
522 #[test]
523 fn test_override_multikey() {
524 let bindings = [
525 KeyBinding::new("ctrl-w left", ActionAlpha {}, Some("editor")),
526 KeyBinding::new("ctrl-w", NoAction {}, Some("editor")),
527 ];
528
529 let mut keymap = Keymap::default();
530 keymap.add_bindings(bindings);
531
532 let (result, pending) = keymap.bindings_for_input(
534 &[Keystroke::parse("ctrl-w").unwrap()],
535 &[KeyContext::parse("editor").unwrap()],
536 );
537 assert!(result.is_empty());
538 assert!(pending);
539
540 let bindings = [
541 KeyBinding::new("ctrl-w left", ActionAlpha {}, Some("editor")),
542 KeyBinding::new("ctrl-w", ActionBeta {}, Some("editor")),
543 ];
544
545 let mut keymap = Keymap::default();
546 keymap.add_bindings(bindings);
547
548 let (result, pending) = keymap.bindings_for_input(
550 &[Keystroke::parse("ctrl-w").unwrap()],
551 &[KeyContext::parse("editor").unwrap()],
552 );
553 assert_eq!(result.len(), 1);
554 assert!(!pending);
555 }
556
557 #[test]
558 fn test_simple_disable() {
559 let bindings = [
560 KeyBinding::new("ctrl-x", ActionAlpha {}, Some("editor")),
561 KeyBinding::new("ctrl-x", NoAction {}, Some("editor")),
562 ];
563
564 let mut keymap = Keymap::default();
565 keymap.add_bindings(bindings);
566
567 let (result, pending) = keymap.bindings_for_input(
569 &[Keystroke::parse("ctrl-x").unwrap()],
570 &[KeyContext::parse("editor").unwrap()],
571 );
572 assert!(result.is_empty());
573 assert!(!pending);
574 }
575
576 #[test]
577 fn test_fail_to_disable() {
578 let bindings = [
580 KeyBinding::new("ctrl-x", ActionAlpha {}, Some("editor")),
581 KeyBinding::new("ctrl-x", NoAction {}, Some("workspace")),
582 ];
583
584 let mut keymap = Keymap::default();
585 keymap.add_bindings(bindings);
586
587 let (result, pending) = keymap.bindings_for_input(
589 &[Keystroke::parse("ctrl-x").unwrap()],
590 &[
591 KeyContext::parse("workspace").unwrap(),
592 KeyContext::parse("editor").unwrap(),
593 ],
594 );
595 assert_eq!(result.len(), 1);
596 assert!(!pending);
597 }
598
599 #[test]
600 fn test_disable_deeper() {
601 let bindings = [
602 KeyBinding::new("ctrl-x", ActionAlpha {}, Some("workspace")),
603 KeyBinding::new("ctrl-x", NoAction {}, Some("editor")),
604 ];
605
606 let mut keymap = Keymap::default();
607 keymap.add_bindings(bindings);
608
609 let (result, pending) = keymap.bindings_for_input(
611 &[Keystroke::parse("ctrl-x").unwrap()],
612 &[
613 KeyContext::parse("workspace").unwrap(),
614 KeyContext::parse("editor").unwrap(),
615 ],
616 );
617 assert_eq!(result.len(), 0);
618 assert!(!pending);
619 }
620
621 #[test]
622 fn test_pending_match_enabled() {
623 let bindings = [
624 KeyBinding::new("ctrl-x", ActionBeta, Some("vim_mode == normal")),
625 KeyBinding::new("ctrl-x 0", ActionAlpha, Some("Workspace")),
626 ];
627 let mut keymap = Keymap::default();
628 keymap.add_bindings(bindings);
629
630 let matched = keymap.bindings_for_input(
631 &[Keystroke::parse("ctrl-x")].map(Result::unwrap),
632 &[
633 KeyContext::parse("Workspace"),
634 KeyContext::parse("Pane"),
635 KeyContext::parse("Editor vim_mode=normal"),
636 ]
637 .map(Result::unwrap),
638 );
639 assert_eq!(matched.0.len(), 1);
640 assert!(matched.0[0].action.partial_eq(&ActionBeta));
641 assert!(matched.1);
642 }
643
644 #[test]
645 fn test_pending_match_enabled_extended() {
646 let bindings = [
647 KeyBinding::new("ctrl-x", ActionBeta, Some("vim_mode == normal")),
648 KeyBinding::new("ctrl-x 0", NoAction, Some("Workspace")),
649 ];
650 let mut keymap = Keymap::default();
651 keymap.add_bindings(bindings);
652
653 let matched = keymap.bindings_for_input(
654 &[Keystroke::parse("ctrl-x")].map(Result::unwrap),
655 &[
656 KeyContext::parse("Workspace"),
657 KeyContext::parse("Pane"),
658 KeyContext::parse("Editor vim_mode=normal"),
659 ]
660 .map(Result::unwrap),
661 );
662 assert_eq!(matched.0.len(), 1);
663 assert!(matched.0[0].action.partial_eq(&ActionBeta));
664 assert!(!matched.1);
665 let bindings = [
666 KeyBinding::new("ctrl-x", ActionBeta, Some("Workspace")),
667 KeyBinding::new("ctrl-x 0", NoAction, Some("vim_mode == normal")),
668 ];
669 let mut keymap = Keymap::default();
670 keymap.add_bindings(bindings);
671
672 let matched = keymap.bindings_for_input(
673 &[Keystroke::parse("ctrl-x")].map(Result::unwrap),
674 &[
675 KeyContext::parse("Workspace"),
676 KeyContext::parse("Pane"),
677 KeyContext::parse("Editor vim_mode=normal"),
678 ]
679 .map(Result::unwrap),
680 );
681 assert_eq!(matched.0.len(), 1);
682 assert!(matched.0[0].action.partial_eq(&ActionBeta));
683 assert!(!matched.1);
684 }
685
686 #[test]
687 fn test_overriding_prefix() {
688 let bindings = [
689 KeyBinding::new("ctrl-x 0", ActionAlpha, Some("Workspace")),
690 KeyBinding::new("ctrl-x", ActionBeta, Some("vim_mode == normal")),
691 ];
692 let mut keymap = Keymap::default();
693 keymap.add_bindings(bindings);
694
695 let matched = keymap.bindings_for_input(
696 &[Keystroke::parse("ctrl-x")].map(Result::unwrap),
697 &[
698 KeyContext::parse("Workspace"),
699 KeyContext::parse("Pane"),
700 KeyContext::parse("Editor vim_mode=normal"),
701 ]
702 .map(Result::unwrap),
703 );
704 assert_eq!(matched.0.len(), 1);
705 assert!(matched.0[0].action.partial_eq(&ActionBeta));
706 assert!(!matched.1);
707 }
708
709 #[test]
710 fn test_context_precedence_with_same_source() {
711 let bindings = [
714 KeyBinding::new("cmd-r", ActionAlpha {}, Some("Workspace")),
715 KeyBinding::new("cmd-r", ActionBeta {}, Some("Editor")),
716 ];
717
718 let mut keymap = Keymap::default();
719 keymap.add_bindings(bindings);
720
721 let (result, _) = keymap.bindings_for_input(
723 &[Keystroke::parse("cmd-r").unwrap()],
724 &[
725 KeyContext::parse("Workspace").unwrap(),
726 KeyContext::parse("Editor").unwrap(),
727 ],
728 );
729
730 assert_eq!(result.len(), 2);
732 assert!(result[0].action.partial_eq(&ActionBeta {})); assert!(result[1].action.partial_eq(&ActionAlpha {})); }
735
736 #[test]
737 fn test_bindings_for_action() {
738 let bindings = [
739 KeyBinding::new("ctrl-a", ActionAlpha {}, Some("pane")),
740 KeyBinding::new("ctrl-b", ActionBeta {}, Some("editor && mode == full")),
741 KeyBinding::new("ctrl-c", ActionGamma {}, Some("workspace")),
742 KeyBinding::new("ctrl-a", NoAction {}, Some("pane && active")),
743 KeyBinding::new("ctrl-b", NoAction {}, Some("editor")),
744 ];
745
746 let mut keymap = Keymap::default();
747 keymap.add_bindings(bindings);
748
749 assert_bindings(&keymap, &ActionAlpha {}, &["ctrl-a"]);
750 assert_bindings(&keymap, &ActionBeta {}, &[]);
751 assert_bindings(&keymap, &ActionGamma {}, &["ctrl-c"]);
752
753 #[track_caller]
754 fn assert_bindings(keymap: &Keymap, action: &dyn Action, expected: &[&str]) {
755 let actual = keymap
756 .bindings_for_action(action)
757 .map(|binding| binding.keystrokes[0].inner().unparse())
758 .collect::<Vec<_>>();
759 assert_eq!(actual, expected, "{:?}", action);
760 }
761 }
762
763 #[test]
764 fn test_targeted_unbind_ignores_target_context() {
765 let bindings = [
766 KeyBinding::new("tab", ActionAlpha {}, Some("Editor")),
767 KeyBinding::new("tab", ActionBeta {}, Some("Editor && showing_completions")),
768 KeyBinding::new(
769 "tab",
770 Unbind("test_only::ActionAlpha".into()),
771 Some("Editor && edit_prediction"),
772 ),
773 ];
774
775 let mut keymap = Keymap::default();
776 keymap.add_bindings(bindings);
777
778 let (result, pending) = keymap.bindings_for_input(
779 &[Keystroke::parse("tab").unwrap()],
780 &[KeyContext::parse("Editor showing_completions edit_prediction").unwrap()],
781 );
782
783 assert!(!pending);
784 assert_eq!(result.len(), 1);
785 assert!(result[0].action.partial_eq(&ActionBeta {}));
786 }
787
788 #[test]
789 fn test_bindings_for_action_keeps_binding_for_narrower_targeted_unbind() {
790 let bindings = [
791 KeyBinding::new("tab", ActionAlpha {}, Some("Editor")),
792 KeyBinding::new(
793 "tab",
794 Unbind("test_only::ActionAlpha".into()),
795 Some("Editor && edit_prediction"),
796 ),
797 KeyBinding::new("tab", ActionBeta {}, Some("Editor && showing_completions")),
798 ];
799
800 let mut keymap = Keymap::default();
801 keymap.add_bindings(bindings);
802
803 assert_bindings(&keymap, &ActionAlpha {}, &["tab"]);
804 assert_bindings(&keymap, &ActionBeta {}, &["tab"]);
805
806 #[track_caller]
807 fn assert_bindings(keymap: &Keymap, action: &dyn Action, expected: &[&str]) {
808 let actual = keymap
809 .bindings_for_action(action)
810 .map(|binding| binding.keystrokes[0].inner().unparse())
811 .collect::<Vec<_>>();
812 assert_eq!(actual, expected, "{:?}", action);
813 }
814 }
815
816 #[test]
817 fn test_bindings_for_action_removes_binding_for_broader_targeted_unbind() {
818 let bindings = [
819 KeyBinding::new("tab", ActionAlpha {}, Some("Editor && edit_prediction")),
820 KeyBinding::new(
821 "tab",
822 Unbind("test_only::ActionAlpha".into()),
823 Some("Editor"),
824 ),
825 ];
826
827 let mut keymap = Keymap::default();
828 keymap.add_bindings(bindings);
829
830 assert!(keymap.bindings_for_action(&ActionAlpha {}).next().is_none());
831 }
832
833 #[test]
834 fn test_source_precedence_sorting() {
835 let mut keymap = Keymap::default();
838
839 let mut default_binding = KeyBinding::new("cmd-r", ActionAlpha {}, Some("Editor"));
841 default_binding.set_meta(KeyBindingMetaIndex(3)); keymap.add_bindings([default_binding]);
843
844 let mut user_binding = KeyBinding::new("cmd-r", ActionBeta {}, Some("Editor"));
846 user_binding.set_meta(KeyBindingMetaIndex(0)); keymap.add_bindings([user_binding]);
848
849 let (result, _) = keymap.bindings_for_input(
851 &[Keystroke::parse("cmd-r").unwrap()],
852 &[KeyContext::parse("Editor").unwrap()],
853 );
854
855 assert_eq!(result.len(), 2);
857 assert!(result[0].action.partial_eq(&ActionBeta {}));
858 assert!(result[1].action.partial_eq(&ActionAlpha {}));
859 }
860}