1mod binding;
  2mod context;
  3
  4pub use binding::*;
  5pub use context::*;
  6
  7use crate::{Action, AsKeystroke, Keystroke, is_no_action};
  8use collections::{HashMap, HashSet};
  9use smallvec::SmallVec;
 10use std::any::TypeId;
 11
 12/// An opaque identifier of which version of the keymap is currently active.
 13/// The keymap's version is changed whenever bindings are added or removed.
 14#[derive(Copy, Clone, Eq, PartialEq, Default)]
 15pub struct KeymapVersion(usize);
 16
 17/// A collection of key bindings for the user's application.
 18#[derive(Default)]
 19pub struct Keymap {
 20    bindings: Vec<KeyBinding>,
 21    binding_indices_by_action_id: HashMap<TypeId, SmallVec<[usize; 3]>>,
 22    no_action_binding_indices: Vec<usize>,
 23    version: KeymapVersion,
 24}
 25
 26/// Index of a binding within a keymap.
 27#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
 28pub struct BindingIndex(usize);
 29
 30impl Keymap {
 31    /// Create a new keymap with the given bindings.
 32    pub fn new(bindings: Vec<KeyBinding>) -> Self {
 33        let mut this = Self::default();
 34        this.add_bindings(bindings);
 35        this
 36    }
 37
 38    /// Get the current version of the keymap.
 39    pub fn version(&self) -> KeymapVersion {
 40        self.version
 41    }
 42
 43    /// Add more bindings to the keymap.
 44    pub fn add_bindings<T: IntoIterator<Item = KeyBinding>>(&mut self, bindings: T) {
 45        for binding in bindings {
 46            let action_id = binding.action().as_any().type_id();
 47            if is_no_action(&*binding.action) {
 48                self.no_action_binding_indices.push(self.bindings.len());
 49            } else {
 50                self.binding_indices_by_action_id
 51                    .entry(action_id)
 52                    .or_default()
 53                    .push(self.bindings.len());
 54            }
 55            self.bindings.push(binding);
 56        }
 57
 58        self.version.0 += 1;
 59    }
 60
 61    /// Reset this keymap to its initial state.
 62    pub fn clear(&mut self) {
 63        self.bindings.clear();
 64        self.binding_indices_by_action_id.clear();
 65        self.no_action_binding_indices.clear();
 66        self.version.0 += 1;
 67    }
 68
 69    /// Iterate over all bindings, in the order they were added.
 70    pub fn bindings(&self) -> impl DoubleEndedIterator<Item = &KeyBinding> + ExactSizeIterator {
 71        self.bindings.iter()
 72    }
 73
 74    /// Iterate over all bindings for the given action, in the order they were added. For display,
 75    /// the last binding should take precedence.
 76    pub fn bindings_for_action<'a>(
 77        &'a self,
 78        action: &'a dyn Action,
 79    ) -> impl 'a + DoubleEndedIterator<Item = &'a KeyBinding> {
 80        let action_id = action.type_id();
 81        let binding_indices = self
 82            .binding_indices_by_action_id
 83            .get(&action_id)
 84            .map_or(&[] as _, SmallVec::as_slice)
 85            .iter();
 86
 87        binding_indices.filter_map(|ix| {
 88            let binding = &self.bindings[*ix];
 89            if !binding.action().partial_eq(action) {
 90                return None;
 91            }
 92
 93            for null_ix in &self.no_action_binding_indices {
 94                if null_ix > ix {
 95                    let null_binding = &self.bindings[*null_ix];
 96                    if null_binding.keystrokes == binding.keystrokes {
 97                        let null_binding_matches =
 98                            match (&null_binding.context_predicate, &binding.context_predicate) {
 99                                (None, _) => true,
100                                (Some(_), None) => false,
101                                (Some(null_predicate), Some(predicate)) => {
102                                    null_predicate.is_superset(predicate)
103                                }
104                            };
105                        if null_binding_matches {
106                            return None;
107                        }
108                    }
109                }
110            }
111
112            Some(binding)
113        })
114    }
115
116    /// Returns all bindings that might match the input without checking context. The bindings
117    /// returned in precedence order (reverse of the order they were added to the keymap).
118    pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
119        self.bindings()
120            .rev()
121            .filter(|binding| {
122                binding
123                    .match_keystrokes(input)
124                    .is_some_and(|pending| !pending)
125            })
126            .cloned()
127            .collect()
128    }
129
130    /// Returns a list of bindings that match the given input, and a boolean indicating whether or
131    /// not more bindings might match if the input was longer. Bindings are returned in precedence
132    /// order (higher precedence first, reverse of the order they were added to the keymap).
133    ///
134    /// Precedence is defined by the depth in the tree (matches on the Editor take precedence over
135    /// matches on the Pane, then the Workspace, etc.). Bindings with no context are treated as the
136    /// same as the deepest context.
137    ///
138    /// In the case of multiple bindings at the same depth, the ones added to the keymap later take
139    /// precedence. User bindings are added after built-in bindings so that they take precedence.
140    ///
141    /// If a user has disabled a binding with `"x": null` it will not be returned. Disabled bindings
142    /// are evaluated with the same precedence rules so you can disable a rule in a given context
143    /// only.
144    pub fn bindings_for_input(
145        &self,
146        input: &[impl AsKeystroke],
147        context_stack: &[KeyContext],
148    ) -> (SmallVec<[KeyBinding; 1]>, bool) {
149        let mut matched_bindings = SmallVec::<[(usize, BindingIndex, &KeyBinding); 1]>::new();
150        let mut pending_bindings = SmallVec::<[(BindingIndex, &KeyBinding); 1]>::new();
151
152        for (ix, binding) in self.bindings().enumerate().rev() {
153            let Some(depth) = self.binding_enabled(binding, context_stack) else {
154                continue;
155            };
156            let Some(pending) = binding.match_keystrokes(input) else {
157                continue;
158            };
159
160            if !pending {
161                matched_bindings.push((depth, BindingIndex(ix), binding));
162            } else {
163                pending_bindings.push((BindingIndex(ix), binding));
164            }
165        }
166
167        matched_bindings.sort_by(|(depth_a, ix_a, _), (depth_b, ix_b, _)| {
168            depth_b.cmp(depth_a).then(ix_b.cmp(ix_a))
169        });
170
171        let mut bindings: SmallVec<[_; 1]> = SmallVec::new();
172        let mut first_binding_index = None;
173
174        for (_, ix, binding) in matched_bindings {
175            if is_no_action(&*binding.action) {
176                // Only break if this is a user-defined NoAction binding
177                // This allows user keymaps to override base keymap NoAction bindings
178                if let Some(meta) = binding.meta {
179                    if meta.0 == 0 {
180                        break;
181                    }
182                } else {
183                    // If no meta is set, assume it's a user binding for safety
184                    break;
185                }
186                // For non-user NoAction bindings, continue searching for user overrides
187                continue;
188            }
189            bindings.push(binding.clone());
190            first_binding_index.get_or_insert(ix);
191        }
192
193        let mut pending = HashSet::default();
194        for (ix, binding) in pending_bindings.into_iter().rev() {
195            if let Some(binding_ix) = first_binding_index
196                && binding_ix > ix
197            {
198                continue;
199            }
200            if is_no_action(&*binding.action) {
201                pending.remove(&&binding.keystrokes);
202                continue;
203            }
204            pending.insert(&binding.keystrokes);
205        }
206
207        (bindings, !pending.is_empty())
208    }
209    /// Check if the given binding is enabled, given a certain key context.
210    /// Returns the deepest depth at which the binding matches, or None if it doesn't match.
211    fn binding_enabled(&self, binding: &KeyBinding, contexts: &[KeyContext]) -> Option<usize> {
212        if let Some(predicate) = &binding.context_predicate {
213            predicate.depth_of(contexts)
214        } else {
215            Some(contexts.len())
216        }
217    }
218}
219
220#[cfg(test)]
221mod tests {
222    use super::*;
223    use crate as gpui;
224    use gpui::NoAction;
225
226    actions!(
227        test_only,
228        [ActionAlpha, ActionBeta, ActionGamma, ActionDelta,]
229    );
230
231    #[test]
232    fn test_keymap() {
233        let bindings = [
234            KeyBinding::new("ctrl-a", ActionAlpha {}, None),
235            KeyBinding::new("ctrl-a", ActionBeta {}, Some("pane")),
236            KeyBinding::new("ctrl-a", ActionGamma {}, Some("editor && mode==full")),
237        ];
238
239        let mut keymap = Keymap::default();
240        keymap.add_bindings(bindings.clone());
241
242        // global bindings are enabled in all contexts
243        assert_eq!(keymap.binding_enabled(&bindings[0], &[]), Some(0));
244        assert_eq!(
245            keymap.binding_enabled(&bindings[0], &[KeyContext::parse("terminal").unwrap()]),
246            Some(1)
247        );
248
249        // contextual bindings are enabled in contexts that match their predicate
250        assert_eq!(
251            keymap.binding_enabled(&bindings[1], &[KeyContext::parse("barf x=y").unwrap()]),
252            None
253        );
254        assert_eq!(
255            keymap.binding_enabled(&bindings[1], &[KeyContext::parse("pane x=y").unwrap()]),
256            Some(1)
257        );
258
259        assert_eq!(
260            keymap.binding_enabled(&bindings[2], &[KeyContext::parse("editor").unwrap()]),
261            None
262        );
263        assert_eq!(
264            keymap.binding_enabled(
265                &bindings[2],
266                &[KeyContext::parse("editor mode=full").unwrap()]
267            ),
268            Some(1)
269        );
270    }
271
272    #[test]
273    fn test_depth_precedence() {
274        let bindings = [
275            KeyBinding::new("ctrl-a", ActionBeta {}, Some("pane")),
276            KeyBinding::new("ctrl-a", ActionGamma {}, Some("editor")),
277        ];
278
279        let mut keymap = Keymap::default();
280        keymap.add_bindings(bindings);
281
282        let (result, pending) = keymap.bindings_for_input(
283            &[Keystroke::parse("ctrl-a").unwrap()],
284            &[
285                KeyContext::parse("pane").unwrap(),
286                KeyContext::parse("editor").unwrap(),
287            ],
288        );
289
290        assert!(!pending);
291        assert_eq!(result.len(), 2);
292        assert!(result[0].action.partial_eq(&ActionGamma {}));
293        assert!(result[1].action.partial_eq(&ActionBeta {}));
294    }
295
296    #[test]
297    fn test_keymap_disabled() {
298        let bindings = [
299            KeyBinding::new("ctrl-a", ActionAlpha {}, Some("editor")),
300            KeyBinding::new("ctrl-b", ActionAlpha {}, Some("editor")),
301            KeyBinding::new("ctrl-a", NoAction {}, Some("editor && mode==full")),
302            KeyBinding::new("ctrl-b", NoAction {}, None),
303        ];
304
305        let mut keymap = Keymap::default();
306        keymap.add_bindings(bindings);
307
308        // binding is only enabled in a specific context
309        assert!(
310            keymap
311                .bindings_for_input(
312                    &[Keystroke::parse("ctrl-a").unwrap()],
313                    &[KeyContext::parse("barf").unwrap()],
314                )
315                .0
316                .is_empty()
317        );
318        assert!(
319            !keymap
320                .bindings_for_input(
321                    &[Keystroke::parse("ctrl-a").unwrap()],
322                    &[KeyContext::parse("editor").unwrap()],
323                )
324                .0
325                .is_empty()
326        );
327
328        // binding is disabled in a more specific context
329        assert!(
330            keymap
331                .bindings_for_input(
332                    &[Keystroke::parse("ctrl-a").unwrap()],
333                    &[KeyContext::parse("editor mode=full").unwrap()],
334                )
335                .0
336                .is_empty()
337        );
338
339        // binding is globally disabled
340        assert!(
341            keymap
342                .bindings_for_input(
343                    &[Keystroke::parse("ctrl-b").unwrap()],
344                    &[KeyContext::parse("barf").unwrap()],
345                )
346                .0
347                .is_empty()
348        );
349    }
350
351    #[test]
352    /// Tests for https://github.com/zed-industries/zed/issues/30259
353    fn test_multiple_keystroke_binding_disabled() {
354        let bindings = [
355            KeyBinding::new("space w w", ActionAlpha {}, Some("workspace")),
356            KeyBinding::new("space w w", NoAction {}, Some("editor")),
357        ];
358
359        let mut keymap = Keymap::default();
360        keymap.add_bindings(bindings);
361
362        let space = || Keystroke::parse("space").unwrap();
363        let w = || Keystroke::parse("w").unwrap();
364
365        let space_w = [space(), w()];
366        let space_w_w = [space(), w(), w()];
367
368        let workspace_context = || [KeyContext::parse("workspace").unwrap()];
369
370        let editor_workspace_context = || {
371            [
372                KeyContext::parse("workspace").unwrap(),
373                KeyContext::parse("editor").unwrap(),
374            ]
375        };
376
377        // Ensure `space` results in pending input on the workspace, but not editor
378        let space_workspace = keymap.bindings_for_input(&[space()], &workspace_context());
379        assert!(space_workspace.0.is_empty());
380        assert!(space_workspace.1);
381
382        let space_editor = keymap.bindings_for_input(&[space()], &editor_workspace_context());
383        assert!(space_editor.0.is_empty());
384        assert!(!space_editor.1);
385
386        // Ensure `space w` results in pending input on the workspace, but not editor
387        let space_w_workspace = keymap.bindings_for_input(&space_w, &workspace_context());
388        assert!(space_w_workspace.0.is_empty());
389        assert!(space_w_workspace.1);
390
391        let space_w_editor = keymap.bindings_for_input(&space_w, &editor_workspace_context());
392        assert!(space_w_editor.0.is_empty());
393        assert!(!space_w_editor.1);
394
395        // Ensure `space w w` results in the binding in the workspace, but not in the editor
396        let space_w_w_workspace = keymap.bindings_for_input(&space_w_w, &workspace_context());
397        assert!(!space_w_w_workspace.0.is_empty());
398        assert!(!space_w_w_workspace.1);
399
400        let space_w_w_editor = keymap.bindings_for_input(&space_w_w, &editor_workspace_context());
401        assert!(space_w_w_editor.0.is_empty());
402        assert!(!space_w_w_editor.1);
403
404        // Now test what happens if we have another binding defined AFTER the NoAction
405        // that should result in pending
406        let bindings = [
407            KeyBinding::new("space w w", ActionAlpha {}, Some("workspace")),
408            KeyBinding::new("space w w", NoAction {}, Some("editor")),
409            KeyBinding::new("space w x", ActionAlpha {}, Some("editor")),
410        ];
411        let mut keymap = Keymap::default();
412        keymap.add_bindings(bindings);
413
414        let space_editor = keymap.bindings_for_input(&[space()], &editor_workspace_context());
415        assert!(space_editor.0.is_empty());
416        assert!(space_editor.1);
417
418        // Now test what happens if we have another binding defined BEFORE the NoAction
419        // that should result in pending
420        let bindings = [
421            KeyBinding::new("space w w", ActionAlpha {}, Some("workspace")),
422            KeyBinding::new("space w x", ActionAlpha {}, Some("editor")),
423            KeyBinding::new("space w w", NoAction {}, Some("editor")),
424        ];
425        let mut keymap = Keymap::default();
426        keymap.add_bindings(bindings);
427
428        let space_editor = keymap.bindings_for_input(&[space()], &editor_workspace_context());
429        assert!(space_editor.0.is_empty());
430        assert!(space_editor.1);
431
432        // Now test what happens if we have another binding defined at a higher context
433        // that should result in pending
434        let bindings = [
435            KeyBinding::new("space w w", ActionAlpha {}, Some("workspace")),
436            KeyBinding::new("space w x", ActionAlpha {}, Some("workspace")),
437            KeyBinding::new("space w w", NoAction {}, Some("editor")),
438        ];
439        let mut keymap = Keymap::default();
440        keymap.add_bindings(bindings);
441
442        let space_editor = keymap.bindings_for_input(&[space()], &editor_workspace_context());
443        assert!(space_editor.0.is_empty());
444        assert!(space_editor.1);
445    }
446
447    #[test]
448    fn test_override_multikey() {
449        let bindings = [
450            KeyBinding::new("ctrl-w left", ActionAlpha {}, Some("editor")),
451            KeyBinding::new("ctrl-w", NoAction {}, Some("editor")),
452        ];
453
454        let mut keymap = Keymap::default();
455        keymap.add_bindings(bindings);
456
457        // Ensure `space` results in pending input on the workspace, but not editor
458        let (result, pending) = keymap.bindings_for_input(
459            &[Keystroke::parse("ctrl-w").unwrap()],
460            &[KeyContext::parse("editor").unwrap()],
461        );
462        assert!(result.is_empty());
463        assert!(pending);
464
465        let bindings = [
466            KeyBinding::new("ctrl-w left", ActionAlpha {}, Some("editor")),
467            KeyBinding::new("ctrl-w", ActionBeta {}, Some("editor")),
468        ];
469
470        let mut keymap = Keymap::default();
471        keymap.add_bindings(bindings);
472
473        // Ensure `space` results in pending input on the workspace, but not editor
474        let (result, pending) = keymap.bindings_for_input(
475            &[Keystroke::parse("ctrl-w").unwrap()],
476            &[KeyContext::parse("editor").unwrap()],
477        );
478        assert_eq!(result.len(), 1);
479        assert!(!pending);
480    }
481
482    #[test]
483    fn test_simple_disable() {
484        let bindings = [
485            KeyBinding::new("ctrl-x", ActionAlpha {}, Some("editor")),
486            KeyBinding::new("ctrl-x", NoAction {}, Some("editor")),
487        ];
488
489        let mut keymap = Keymap::default();
490        keymap.add_bindings(bindings);
491
492        // Ensure `space` results in pending input on the workspace, but not editor
493        let (result, pending) = keymap.bindings_for_input(
494            &[Keystroke::parse("ctrl-x").unwrap()],
495            &[KeyContext::parse("editor").unwrap()],
496        );
497        assert!(result.is_empty());
498        assert!(!pending);
499    }
500
501    #[test]
502    fn test_fail_to_disable() {
503        // disabled at the wrong level
504        let bindings = [
505            KeyBinding::new("ctrl-x", ActionAlpha {}, Some("editor")),
506            KeyBinding::new("ctrl-x", NoAction {}, Some("workspace")),
507        ];
508
509        let mut keymap = Keymap::default();
510        keymap.add_bindings(bindings);
511
512        // Ensure `space` results in pending input on the workspace, but not editor
513        let (result, pending) = keymap.bindings_for_input(
514            &[Keystroke::parse("ctrl-x").unwrap()],
515            &[
516                KeyContext::parse("workspace").unwrap(),
517                KeyContext::parse("editor").unwrap(),
518            ],
519        );
520        assert_eq!(result.len(), 1);
521        assert!(!pending);
522    }
523
524    #[test]
525    fn test_disable_deeper() {
526        let bindings = [
527            KeyBinding::new("ctrl-x", ActionAlpha {}, Some("workspace")),
528            KeyBinding::new("ctrl-x", NoAction {}, Some("editor")),
529        ];
530
531        let mut keymap = Keymap::default();
532        keymap.add_bindings(bindings);
533
534        // Ensure `space` results in pending input on the workspace, but not editor
535        let (result, pending) = keymap.bindings_for_input(
536            &[Keystroke::parse("ctrl-x").unwrap()],
537            &[
538                KeyContext::parse("workspace").unwrap(),
539                KeyContext::parse("editor").unwrap(),
540            ],
541        );
542        assert_eq!(result.len(), 0);
543        assert!(!pending);
544    }
545
546    #[test]
547    fn test_pending_match_enabled() {
548        let bindings = [
549            KeyBinding::new("ctrl-x", ActionBeta, Some("vim_mode == normal")),
550            KeyBinding::new("ctrl-x 0", ActionAlpha, Some("Workspace")),
551        ];
552        let mut keymap = Keymap::default();
553        keymap.add_bindings(bindings);
554
555        let matched = keymap.bindings_for_input(
556            &[Keystroke::parse("ctrl-x")].map(Result::unwrap),
557            &[
558                KeyContext::parse("Workspace"),
559                KeyContext::parse("Pane"),
560                KeyContext::parse("Editor vim_mode=normal"),
561            ]
562            .map(Result::unwrap),
563        );
564        assert_eq!(matched.0.len(), 1);
565        assert!(matched.0[0].action.partial_eq(&ActionBeta));
566        assert!(matched.1);
567    }
568
569    #[test]
570    fn test_pending_match_enabled_extended() {
571        let bindings = [
572            KeyBinding::new("ctrl-x", ActionBeta, Some("vim_mode == normal")),
573            KeyBinding::new("ctrl-x 0", NoAction, Some("Workspace")),
574        ];
575        let mut keymap = Keymap::default();
576        keymap.add_bindings(bindings);
577
578        let matched = keymap.bindings_for_input(
579            &[Keystroke::parse("ctrl-x")].map(Result::unwrap),
580            &[
581                KeyContext::parse("Workspace"),
582                KeyContext::parse("Pane"),
583                KeyContext::parse("Editor vim_mode=normal"),
584            ]
585            .map(Result::unwrap),
586        );
587        assert_eq!(matched.0.len(), 1);
588        assert!(matched.0[0].action.partial_eq(&ActionBeta));
589        assert!(!matched.1);
590        let bindings = [
591            KeyBinding::new("ctrl-x", ActionBeta, Some("Workspace")),
592            KeyBinding::new("ctrl-x 0", NoAction, Some("vim_mode == normal")),
593        ];
594        let mut keymap = Keymap::default();
595        keymap.add_bindings(bindings);
596
597        let matched = keymap.bindings_for_input(
598            &[Keystroke::parse("ctrl-x")].map(Result::unwrap),
599            &[
600                KeyContext::parse("Workspace"),
601                KeyContext::parse("Pane"),
602                KeyContext::parse("Editor vim_mode=normal"),
603            ]
604            .map(Result::unwrap),
605        );
606        assert_eq!(matched.0.len(), 1);
607        assert!(matched.0[0].action.partial_eq(&ActionBeta));
608        assert!(!matched.1);
609    }
610
611    #[test]
612    fn test_overriding_prefix() {
613        let bindings = [
614            KeyBinding::new("ctrl-x 0", ActionAlpha, Some("Workspace")),
615            KeyBinding::new("ctrl-x", ActionBeta, Some("vim_mode == normal")),
616        ];
617        let mut keymap = Keymap::default();
618        keymap.add_bindings(bindings);
619
620        let matched = keymap.bindings_for_input(
621            &[Keystroke::parse("ctrl-x")].map(Result::unwrap),
622            &[
623                KeyContext::parse("Workspace"),
624                KeyContext::parse("Pane"),
625                KeyContext::parse("Editor vim_mode=normal"),
626            ]
627            .map(Result::unwrap),
628        );
629        assert_eq!(matched.0.len(), 1);
630        assert!(matched.0[0].action.partial_eq(&ActionBeta));
631        assert!(!matched.1);
632    }
633
634    #[test]
635    fn test_context_precedence_with_same_source() {
636        // Test case: User has both Workspace and Editor bindings for the same key
637        // Editor binding should take precedence over Workspace binding
638        let bindings = [
639            KeyBinding::new("cmd-r", ActionAlpha {}, Some("Workspace")),
640            KeyBinding::new("cmd-r", ActionBeta {}, Some("Editor")),
641        ];
642
643        let mut keymap = Keymap::default();
644        keymap.add_bindings(bindings);
645
646        // Test with context stack: [Workspace, Editor] (Editor is deeper)
647        let (result, _) = keymap.bindings_for_input(
648            &[Keystroke::parse("cmd-r").unwrap()],
649            &[
650                KeyContext::parse("Workspace").unwrap(),
651                KeyContext::parse("Editor").unwrap(),
652            ],
653        );
654
655        // Both bindings should be returned, but Editor binding should be first (highest precedence)
656        assert_eq!(result.len(), 2);
657        assert!(result[0].action.partial_eq(&ActionBeta {})); // Editor binding first
658        assert!(result[1].action.partial_eq(&ActionAlpha {})); // Workspace binding second
659    }
660
661    #[test]
662    fn test_bindings_for_action() {
663        let bindings = [
664            KeyBinding::new("ctrl-a", ActionAlpha {}, Some("pane")),
665            KeyBinding::new("ctrl-b", ActionBeta {}, Some("editor && mode == full")),
666            KeyBinding::new("ctrl-c", ActionGamma {}, Some("workspace")),
667            KeyBinding::new("ctrl-a", NoAction {}, Some("pane && active")),
668            KeyBinding::new("ctrl-b", NoAction {}, Some("editor")),
669        ];
670
671        let mut keymap = Keymap::default();
672        keymap.add_bindings(bindings);
673
674        assert_bindings(&keymap, &ActionAlpha {}, &["ctrl-a"]);
675        assert_bindings(&keymap, &ActionBeta {}, &[]);
676        assert_bindings(&keymap, &ActionGamma {}, &["ctrl-c"]);
677
678        #[track_caller]
679        fn assert_bindings(keymap: &Keymap, action: &dyn Action, expected: &[&str]) {
680            let actual = keymap
681                .bindings_for_action(action)
682                .map(|binding| binding.keystrokes[0].inner().unparse())
683                .collect::<Vec<_>>();
684            assert_eq!(actual, expected, "{:?}", action);
685        }
686    }
687
688    #[test]
689    fn test_source_precedence_sorting() {
690        // KeybindSource precedence: User (0) > Vim (1) > Base (2) > Default (3)
691        // Test that user keymaps take precedence over default keymaps at the same context depth
692        let mut keymap = Keymap::default();
693
694        // Add a default keymap binding first
695        let mut default_binding = KeyBinding::new("cmd-r", ActionAlpha {}, Some("Editor"));
696        default_binding.set_meta(KeyBindingMetaIndex(3)); // Default source
697        keymap.add_bindings([default_binding]);
698
699        // Add a user keymap binding
700        let mut user_binding = KeyBinding::new("cmd-r", ActionBeta {}, Some("Editor"));
701        user_binding.set_meta(KeyBindingMetaIndex(0)); // User source
702        keymap.add_bindings([user_binding]);
703
704        // Test with Editor context stack
705        let (result, _) = keymap.bindings_for_input(
706            &[Keystroke::parse("cmd-r").unwrap()],
707            &[KeyContext::parse("Editor").unwrap()],
708        );
709
710        // User binding should take precedence over default binding
711        assert_eq!(result.len(), 2);
712        assert!(result[0].action.partial_eq(&ActionBeta {}));
713        assert!(result[1].action.partial_eq(&ActionAlpha {}));
714    }
715}