Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
gpui: Hide disabled bindings from the which-key popup (#64935)
Smit Barmase71456c40f397
diff --git a/crates/gpui/src/keymap.rs b/crates/gpui/src/keymap.rsindex bef0d03a2b9..477c5a0a53f 100644--- a/crates/gpui/src/keymap.rs+++ b/crates/gpui/src/keymap.rs@@ -167,10 +167,38 @@ impl Keymap {input: &[impl AsKeystroke],context_stack: &[KeyContext],) -> (SmallVec<[KeyBinding; 1]>, bool) {+ let (bindings, pending) = self.resolve_bindings_for_input(+ input,+ context_stack,+ self.bindings().enumerate().rev(),+ );+ (+ bindings+ .into_iter()+ .map(|(_, binding)| binding.clone())+ .collect(),+ pending,+ )+ }++ /// Same as `bindings_for_input`, but only looks at `keymap_bindings` instead of the whole+ /// keymap, and returns each binding with its keymap index.+ ///+ /// `keymap_bindings` must be in reverse keymap order and include every binding that could+ /// match `input`. For example, leaving out a `null` binding would make the binding it disables+ /// look like it wins. `bindings_for_input` passes the whole keymap, which always meets this but+ /// goes through every binding on every call. Passing a pre-filtered list is cheaper when+ /// resolving many inputs against it.+ fn resolve_bindings_for_input<'a>(+ &self,+ input: &[impl AsKeystroke],+ context_stack: &[KeyContext],+ keymap_bindings: impl IntoIterator<Item = (usize, &'a KeyBinding)>,+ ) -> (SmallVec<[(BindingIndex, &'a KeyBinding); 1]>, bool) {let mut matched_bindings = SmallVec::<[(usize, BindingIndex, &KeyBinding); 1]>::new();let mut pending_bindings = SmallVec::<[(BindingIndex, &KeyBinding); 1]>::new();- for (ix, binding) in self.bindings().enumerate().rev() {+ for (ix, binding) in keymap_bindings {let Some(depth) = self.binding_enabled(binding, context_stack) else {continue;};@@ -221,7 +249,7 @@ impl Keymap {continue;}- bindings.push(binding.clone());+ bindings.push((ix, binding));first_binding_index.get_or_insert(ix);}@@ -251,42 +279,61 @@ impl Keymap {}}- /// Find the bindings that can follow the current input sequence.+ /// Find the bindings that can follow the current input sequence, in precedence order. Only+ /// includes bindings that dispatch would run for their full keystrokes, so bindings disabled+ /// with `null` or `Unbind` are left out.pub fn possible_next_bindings_for_input(&self,input: &[Keystroke],context_stack: &[KeyContext],) -> Vec<KeyBinding> {- let mut bindings = self+ // Keeps `null` and `Unbind` bindings, which can disable candidates.+ let bindings_extending_input = self.bindings().enumerate().rev()- .filter_map(|(ix, binding)| {- let depth = self.binding_enabled(binding, context_stack)?;- let pending = binding.match_keystrokes(input);- match pending {- None => None,- Some(is_pending) => {- if !is_pending- || is_no_action(&*binding.action)- || is_unbind(&*binding.action)- {- return None;- }- Some((depth, BindingIndex(ix), binding))- }- }+ .filter(|(_, binding)| {+ binding+ .match_keystrokes(input)+ .is_some_and(|pending| pending)}).collect::<Vec<_>>();- bindings.sort_by(|(depth_a, ix_a, _), (depth_b, ix_b, _)| {+ let mut full_input = SmallVec::<[&Keystroke; 4]>::new();+ let mut candidates = bindings_extending_input+ .iter()+ .filter(|(_, binding)| !is_no_action(&*binding.action) && !is_unbind(&*binding.action))+ .filter_map(|&(ix, binding)| {+ let depth = self.binding_enabled(binding, context_stack)?;+ // Use the typed input rather than the binding's own keystrokes. A typed keystroke+ // can match through its physical key, like `alt-s`, or the character it produced,+ // like `ß`.+ full_input.clear();+ full_input.extend(input.iter());+ full_input.extend(+ binding.keystrokes[input.len()..]+ .iter()+ .map(AsKeystroke::as_keystroke),+ );+ let (dispatched, _) = self.resolve_bindings_for_input(+ &full_input,+ context_stack,+ bindings_extending_input.iter().copied(),+ );+ dispatched+ .iter()+ .any(|(dispatched_ix, _)| *dispatched_ix == BindingIndex(ix))+ .then_some((depth, ix, binding))+ })+ .collect::<Vec<_>>();+ candidates.sort_unstable_by(|(depth_a, ix_a, _), (depth_b, ix_b, _)| {depth_b.cmp(depth_a).then(ix_b.cmp(ix_a))});- bindings+ candidates.into_iter().map(|(_, _, binding)| binding.clone())- .collect::<Vec<_>>()+ .collect()}}@@ -924,4 +971,165 @@ mod tests {assert!(result[0].action.partial_eq(&ActionBeta {}));assert!(result[1].action.partial_eq(&ActionAlpha {}));}++ #[test]+ fn test_possible_next_bindings_exclude_null_bindings() {+ let keymap = Keymap::new(vec![+ KeyBinding::new("ctrl-k a", ActionAlpha {}, Some("Editor")),+ KeyBinding::new("ctrl-k b", ActionBeta {}, Some("Editor")),+ KeyBinding::new("ctrl-k a", NoAction {}, Some("Editor")),+ ]);++ let bindings = keymap.possible_next_bindings_for_input(+ &[Keystroke::parse("ctrl-k").unwrap()],+ &[KeyContext::parse("Editor").unwrap()],+ );+ assert_eq!(+ describe_bindings(&bindings),+ vec![("ctrl-k b".to_string(), "test_only::ActionBeta")]+ );+ }++ #[test]+ fn test_possible_next_bindings_exclude_unbound_bindings() {+ let keymap = Keymap::new(vec![+ KeyBinding::new("ctrl-k a", ActionAlpha {}, Some("Editor")),+ KeyBinding::new("ctrl-k b", ActionBeta {}, Some("Editor")),+ KeyBinding::new(+ "ctrl-k a",+ Unbind("test_only::ActionAlpha".into()),+ Some("Editor"),+ ),+ ]);++ let bindings = keymap.possible_next_bindings_for_input(+ &[Keystroke::parse("ctrl-k").unwrap()],+ &[KeyContext::parse("Editor").unwrap()],+ );+ assert_eq!(+ describe_bindings(&bindings),+ vec![("ctrl-k b".to_string(), "test_only::ActionBeta")]+ );+ }++ #[test]+ fn test_possible_next_bindings_keep_user_binding_over_base_keymap_null() {+ const USER: KeyBindingMetaIndex = KeyBindingMetaIndex(0);+ const BASE: KeyBindingMetaIndex = KeyBindingMetaIndex(2);+ const DEFAULT: KeyBindingMetaIndex = KeyBindingMetaIndex(3);++ let mut keymap = Keymap::default();+ keymap.add_bindings([+ KeyBinding::new("ctrl-k a", ActionAlpha {}, Some("Editor")).with_meta(DEFAULT),+ KeyBinding::new("ctrl-k a", NoAction {}, Some("Editor")).with_meta(BASE),+ KeyBinding::new("ctrl-k a", ActionBeta {}, Some("Editor")).with_meta(USER),+ ]);++ let bindings = keymap.possible_next_bindings_for_input(+ &[Keystroke::parse("ctrl-k").unwrap()],+ &[KeyContext::parse("Editor").unwrap()],+ );+ assert_eq!(+ describe_bindings(&bindings),+ vec![("ctrl-k a".to_string(), "test_only::ActionBeta")]+ );+ }++ #[test]+ fn test_possible_next_bindings_apply_disabling_by_context() {+ let keymap = Keymap::new(vec![+ KeyBinding::new("ctrl-k a", ActionAlpha {}, Some("Workspace")),+ KeyBinding::new("ctrl-k a", ActionBeta {}, Some("Editor")),+ KeyBinding::new("ctrl-k b", ActionGamma {}, Some("Editor")),+ // Only removes the editor binding, so the workspace binding still dispatches.+ KeyBinding::new(+ "ctrl-k a",+ Unbind("test_only::ActionBeta".into()),+ Some("Editor"),+ ),+ // Doesn't apply because `Terminal` isn't in the context stack.+ KeyBinding::new("ctrl-k b", NoAction {}, Some("Terminal")),+ ]);++ let bindings = keymap.possible_next_bindings_for_input(+ &[Keystroke::parse("ctrl-k").unwrap()],+ &[+ KeyContext::parse("Workspace").unwrap(),+ KeyContext::parse("Editor").unwrap(),+ ],+ );+ assert_eq!(+ describe_bindings(&bindings),+ vec![+ ("ctrl-k b".to_string(), "test_only::ActionGamma"),+ ("ctrl-k a".to_string(), "test_only::ActionAlpha"),+ ]+ );+ }++ #[test]+ fn test_possible_next_bindings_exclude_longer_chord_disabled_in_deeper_context() {+ let keymap = Keymap::new(vec![+ KeyBinding::new("space w w", ActionAlpha {}, Some("Workspace")),+ KeyBinding::new("space w x", ActionBeta {}, Some("Workspace")),+ KeyBinding::new("space w w", NoAction {}, Some("AgentPanel")),+ ]);+ let context_stack = [+ KeyContext::parse("Workspace").unwrap(),+ KeyContext::parse("AgentPanel").unwrap(),+ ];++ for input in ["space", "space w"] {+ let input = input+ .split(' ')+ .map(|keystroke| Keystroke::parse(keystroke).unwrap())+ .collect::<Vec<_>>();+ let bindings = keymap.possible_next_bindings_for_input(&input, &context_stack);+ assert_eq!(+ describe_bindings(&bindings),+ vec![("space w x".to_string(), "test_only::ActionBeta")]+ );+ }+ }++ #[test]+ fn test_possible_next_bindings_exclude_disabled_bindings_with_typed_input() {+ // Option-S reports both its physical key and the character it produced, so typed input+ // matches bindings written with either.+ let typed_input = [Keystroke::parse("alt-s->ß").unwrap()];+ let keymap = Keymap::new(vec![+ KeyBinding::new("ß a", ActionAlpha {}, None),+ KeyBinding::new("alt-s a", NoAction {}, None),+ ]);+ assert!(+ keymap+ .possible_next_bindings_for_input(&typed_input, &[])+ .is_empty()+ );++ // Cross-check against dispatch of the same typed input.+ let typed_then_a = [+ Keystroke::parse("alt-s->ß").unwrap(),+ Keystroke::parse("a").unwrap(),+ ];+ let (dispatched, _) = keymap.bindings_for_input(&typed_then_a, &[]);+ assert!(dispatched.is_empty());+ }++ fn describe_bindings(bindings: &[KeyBinding]) -> Vec<(String, &'static str)> {+ bindings+ .iter()+ .map(|binding| {+ (+ binding+ .keystrokes()+ .iter()+ .map(|keystroke| keystroke.inner().unparse())+ .collect::<Vec<_>>()+ .join(" "),+ binding.action().name(),+ )+ })+ .collect()+ }}diff --git a/crates/gpui/src/platform/keystroke.rs b/crates/gpui/src/platform/keystroke.rsindex c45c7c1b335..c24433d0e58 100644--- a/crates/gpui/src/platform/keystroke.rs+++ b/crates/gpui/src/platform/keystroke.rs@@ -680,6 +680,12 @@ impl AsKeystroke for KeybindingKeystroke {}}+impl<T: AsKeystroke + ?Sized> AsKeystroke for &T {+ fn as_keystroke(&self) -> &Keystroke {+ (**self).as_keystroke()+ }+}+fn display_modifiers(modifiers: &Modifiers, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {if modifiers.control {#[cfg(target_os = "macos")]