Skip to main content

rgpui/
keymap.rs

1//! 快捷键映射:定义按键绑定与上下文匹配逻辑。
2
3mod binding;
4mod context;
5/// keymap.json 文件加载(M7:`load_keymap_json`)。
6mod 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/// 当前活动按键映射版本的不透明标识符。
17/// 每当添加或移除绑定时,按键映射的版本都会更改。
18#[derive(Copy, Clone, Eq, PartialEq, Default)]
19pub struct KeymapVersion(usize);
20
21/// 用户应用程序的按键绑定集合。
22#[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/// 按键映射中绑定的索引。
31#[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    /// 使用给定绑定创建新的按键映射。
56    pub fn new(bindings: Vec<KeyBinding>) -> Self {
57        let mut this = Self::default();
58        this.add_bindings(bindings);
59        this
60    }
61
62    /// 获取按键映射的当前版本。
63    pub fn version(&self) -> KeymapVersion {
64        self.version
65    }
66
67    /// 向按键映射添加更多绑定。
68    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    /// 将此按键映射重置为初始状态。
86    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    /// 按添加顺序迭代所有绑定。
94    pub fn bindings(&self) -> impl DoubleEndedIterator<Item = &KeyBinding> + ExactSizeIterator {
95        self.bindings.iter()
96    }
97
98    /// 按添加顺序迭代给定动作的所有绑定。用于显示时,
99    /// 最后一个绑定应优先。
100    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    /// 返回可能匹配输入的所有绑定,不检查上下文。绑定按优先级顺序返回
142    /// (与添加到按键映射的顺序相反)。
143    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    /// 返回匹配给定输入的绑定列表,以及一个布尔值指示如果输入更长是否可能
156    /// 匹配更多绑定。绑定按优先级顺序返回(较高优先级在先,与添加到按键映射的
157    /// 顺序相反)。
158    ///
159    /// 优先级由树中的深度定义(在 Editor 上的匹配优先于在 Pane 上的匹配,
160    /// 然后是 Workspace 等)。没有上下文的绑定被视为与最深上下文相同。
161    ///
162    /// 在相同深度有多个绑定的情况下,后添加到按键映射的绑定优先。
163    /// 用户绑定在内置绑定之后添加,因此它们优先。
164    ///
165    /// 如果用户通过 `"x": null` 禁用了绑定,它将不会返回。禁用的绑定
166    /// 使用相同的优先级规则进行评估,因此你可以仅在给定上下文中禁用规则。
167    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                // Only break if this is a user-defined NoAction binding
201                // This allows user keymaps to override base keymap NoAction bindings
202                if let Some(meta) = binding.meta {
203                    if meta.0 == 0 {
204                        break;
205                    }
206                } else {
207                    // If no meta is set, assume it's a user binding for safety
208                    break;
209                }
210                // For non-user NoAction bindings, continue searching for user overrides
211                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    /// 检查给定绑定在给定按键上下文下是否启用。
247    /// 返回绑定匹配的最深深度,如果不匹配则返回 None。
248    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    /// 查找可以跟随当前输入序列的绑定。
257    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        // global bindings are enabled in all contexts
318        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        // contextual bindings are enabled in contexts that match their predicate
325        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        // binding is only enabled in a specific context
384        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        // binding is disabled in a more specific context
404        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        // binding is globally disabled
415        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    /// 测试 https://github.com/zed-industries/zed/issues/30259
428    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        // Ensure `space` results in pending input on the workspace, but not editor
453        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        // Ensure `space w` results in pending input on the workspace, but not editor
462        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        // Ensure `space w w` results in the binding in the workspace, but not in the editor
471        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        // Now test what happens if we have another binding defined AFTER the NoAction
480        // that should result in pending
481        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        // Now test what happens if we have another binding defined BEFORE the NoAction
494        // that should result in pending
495        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        // Now test what happens if we have another binding defined at a higher context
508        // that should result in pending
509        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        // Ensure `space` results in pending input on the workspace, but not editor
533        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        // Ensure `space` results in pending input on the workspace, but not editor
549        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        // Ensure `space` results in pending input on the workspace, but not editor
568        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        // disabled at the wrong level
579        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        // Ensure `space` results in pending input on the workspace, but not editor
588        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        // Ensure `space` results in pending input on the workspace, but not editor
610        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        // Test case: User has both Workspace and Editor bindings for the same key
712        // Editor binding should take precedence over Workspace binding
713        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        // Test with context stack: [Workspace, Editor] (Editor is deeper)
722        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        // Both bindings should be returned, but Editor binding should be first (highest precedence)
731        assert_eq!(result.len(), 2);
732        assert!(result[0].action.partial_eq(&ActionBeta {})); // Editor binding first
733        assert!(result[1].action.partial_eq(&ActionAlpha {})); // Workspace binding second
734    }
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        // KeybindSource precedence: User (0) > Vim (1) > Base (2) > Default (3)
836        // Test that user keymaps take precedence over default keymaps at the same context depth
837        let mut keymap = Keymap::default();
838
839        // Add a default keymap binding first
840        let mut default_binding = KeyBinding::new("cmd-r", ActionAlpha {}, Some("Editor"));
841        default_binding.set_meta(KeyBindingMetaIndex(3)); // Default source
842        keymap.add_bindings([default_binding]);
843
844        // Add a user keymap binding
845        let mut user_binding = KeyBinding::new("cmd-r", ActionBeta {}, Some("Editor"));
846        user_binding.set_meta(KeyBindingMetaIndex(0)); // User source
847        keymap.add_bindings([user_binding]);
848
849        // Test with Editor context stack
850        let (result, _) = keymap.bindings_for_input(
851            &[Keystroke::parse("cmd-r").unwrap()],
852            &[KeyContext::parse("Editor").unwrap()],
853        );
854
855        // User binding should take precedence over default binding
856        assert_eq!(result.len(), 2);
857        assert!(result[0].action.partial_eq(&ActionBeta {}));
858        assert!(result[1].action.partial_eq(&ActionAlpha {}));
859    }
860}