1mod binding;
2mod context;
3
4pub use binding::*;
5pub use context::*;
6
7use crate::{Action, Keystroke, is_no_action};
8use collections::HashMap;
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)]
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 self.bindings_for_action_with_indices(action)
81 .map(|(_, binding)| binding)
82 }
83
84 /// Like `bindings_for_action_with_indices`, but also returns the binding indices.
85 pub fn bindings_for_action_with_indices<'a>(
86 &'a self,
87 action: &'a dyn Action,
88 ) -> impl 'a + DoubleEndedIterator<Item = (BindingIndex, &'a KeyBinding)> {
89 let action_id = action.type_id();
90 let binding_indices = self
91 .binding_indices_by_action_id
92 .get(&action_id)
93 .map_or(&[] as _, SmallVec::as_slice)
94 .iter();
95
96 binding_indices.filter_map(|ix| {
97 let binding = &self.bindings[*ix];
98 if !binding.action().partial_eq(action) {
99 return None;
100 }
101
102 for null_ix in &self.no_action_binding_indices {
103 if null_ix > ix {
104 let null_binding = &self.bindings[*null_ix];
105 if null_binding.keystrokes == binding.keystrokes {
106 let null_binding_matches =
107 match (&null_binding.context_predicate, &binding.context_predicate) {
108 (None, _) => true,
109 (Some(_), None) => false,
110 (Some(null_predicate), Some(predicate)) => {
111 null_predicate.is_superset(predicate)
112 }
113 };
114 if null_binding_matches {
115 return None;
116 }
117 }
118 }
119 }
120
121 Some((BindingIndex(*ix), binding))
122 })
123 }
124
125 /// Returns all bindings that might match the input without checking context. The bindings
126 /// returned in precedence order (reverse of the order they were added to the keymap).
127 pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
128 self.bindings()
129 .rev()
130 .filter_map(|binding| {
131 binding.match_keystrokes(input).filter(|pending| !pending)?;
132 Some(binding.clone())
133 })
134 .collect()
135 }
136
137 /// Returns a list of bindings that match the given input, and a boolean indicating whether or
138 /// not more bindings might match if the input was longer. Bindings are returned in precedence
139 /// order (higher precedence first, reverse of the order they were added to the keymap).
140 ///
141 /// Precedence is defined by the depth in the tree (matches on the Editor take precedence over
142 /// matches on the Pane, then the Workspace, etc.). Bindings with no context are treated as the
143 /// same as the deepest context.
144 ///
145 /// In the case of multiple bindings at the same depth, the ones added to the keymap later take
146 /// precedence. User bindings are added after built-in bindings so that they take precedence.
147 ///
148 /// If a user has disabled a binding with `"x": null` it will not be returned. Disabled bindings
149 /// are evaluated with the same precedence rules so you can disable a rule in a given context
150 /// only.
151 pub fn bindings_for_input(
152 &self,
153 input: &[Keystroke],
154 context_stack: &[KeyContext],
155 ) -> (SmallVec<[KeyBinding; 1]>, bool) {
156 let (bindings, pending) = self.bindings_for_input_with_indices(input, context_stack);
157 let bindings = bindings
158 .into_iter()
159 .map(|(_, binding)| binding)
160 .collect::<SmallVec<[KeyBinding; 1]>>();
161 (bindings, pending)
162 }
163
164 /// Like `bindings_for_input`, but also returns the binding indices.
165 pub fn bindings_for_input_with_indices(
166 &self,
167 input: &[Keystroke],
168 context_stack: &[KeyContext],
169 ) -> (SmallVec<[(BindingIndex, KeyBinding); 1]>, bool) {
170 let possibilities = self
171 .bindings()
172 .enumerate()
173 .rev()
174 .filter_map(|(ix, binding)| {
175 binding
176 .match_keystrokes(input)
177 .map(|pending| (BindingIndex(ix), binding, pending))
178 });
179
180 let mut bindings: SmallVec<[(BindingIndex, KeyBinding, usize); 1]> = SmallVec::new();
181
182 // (pending, is_no_action, depth, keystrokes)
183 let mut pending_info_opt: Option<(bool, bool, usize, &[Keystroke])> = None;
184
185 'outer: for (binding_index, binding, pending) in possibilities {
186 for depth in (0..=context_stack.len()).rev() {
187 if self.binding_enabled(binding, &context_stack[0..depth]) {
188 let is_no_action = is_no_action(&*binding.action);
189 // We only want to consider a binding pending if it has an action
190 // This, however, means that if we have both a NoAction binding and a binding
191 // with an action at the same depth, we should still set is_pending to true.
192 if let Some(pending_info) = pending_info_opt.as_mut() {
193 let (
194 already_pending,
195 pending_is_no_action,
196 pending_depth,
197 pending_keystrokes,
198 ) = *pending_info;
199
200 // We only want to change the pending status if it's not already pending AND if
201 // the existing pending status was set by a NoAction binding. This avoids a NoAction
202 // binding erroneously setting the pending status to true when a binding with an action
203 // already set it to false
204 //
205 // We also want to change the pending status if the keystrokes don't match,
206 // meaning it's different keystrokes than the NoAction that set pending to false
207 if pending
208 && !already_pending
209 && pending_is_no_action
210 && (pending_depth == depth
211 || pending_keystrokes != binding.keystrokes())
212 {
213 pending_info.0 = !is_no_action;
214 }
215 } else {
216 pending_info_opt = Some((
217 pending && !is_no_action,
218 is_no_action,
219 depth,
220 binding.keystrokes(),
221 ));
222 }
223
224 if !pending {
225 bindings.push((binding_index, binding.clone(), depth));
226 continue 'outer;
227 }
228 }
229 }
230 }
231 // sort by descending depth
232 bindings.sort_by(|a, b| a.2.cmp(&b.2).reverse());
233 let bindings = bindings
234 .into_iter()
235 .map_while(|(binding_index, binding, _)| {
236 if is_no_action(&*binding.action) {
237 None
238 } else {
239 Some((binding_index, binding))
240 }
241 })
242 .collect();
243
244 (bindings, pending_info_opt.unwrap_or_default().0)
245 }
246
247 /// Check if the given binding is enabled, given a certain key context.
248 fn binding_enabled(&self, binding: &KeyBinding, context: &[KeyContext]) -> bool {
249 // If binding has a context predicate, it must match the current context,
250 if let Some(predicate) = &binding.context_predicate {
251 if !predicate.eval(context) {
252 return false;
253 }
254 }
255
256 true
257 }
258}
259
260#[cfg(test)]
261mod tests {
262 use super::*;
263 use crate as gpui;
264 use gpui::NoAction;
265
266 actions!(
267 test_only,
268 [ActionAlpha, ActionBeta, ActionGamma, ActionDelta,]
269 );
270
271 #[test]
272 fn test_keymap() {
273 let bindings = [
274 KeyBinding::new("ctrl-a", ActionAlpha {}, None),
275 KeyBinding::new("ctrl-a", ActionBeta {}, Some("pane")),
276 KeyBinding::new("ctrl-a", ActionGamma {}, Some("editor && mode==full")),
277 ];
278
279 let mut keymap = Keymap::default();
280 keymap.add_bindings(bindings.clone());
281
282 // global bindings are enabled in all contexts
283 assert!(keymap.binding_enabled(&bindings[0], &[]));
284 assert!(keymap.binding_enabled(&bindings[0], &[KeyContext::parse("terminal").unwrap()]));
285
286 // contextual bindings are enabled in contexts that match their predicate
287 assert!(!keymap.binding_enabled(&bindings[1], &[KeyContext::parse("barf x=y").unwrap()]));
288 assert!(keymap.binding_enabled(&bindings[1], &[KeyContext::parse("pane x=y").unwrap()]));
289
290 assert!(!keymap.binding_enabled(&bindings[2], &[KeyContext::parse("editor").unwrap()]));
291 assert!(keymap.binding_enabled(
292 &bindings[2],
293 &[KeyContext::parse("editor mode=full").unwrap()]
294 ));
295 }
296
297 #[test]
298 fn test_keymap_disabled() {
299 let bindings = [
300 KeyBinding::new("ctrl-a", ActionAlpha {}, Some("editor")),
301 KeyBinding::new("ctrl-b", ActionAlpha {}, Some("editor")),
302 KeyBinding::new("ctrl-a", NoAction {}, Some("editor && mode==full")),
303 KeyBinding::new("ctrl-b", NoAction {}, None),
304 ];
305
306 let mut keymap = Keymap::default();
307 keymap.add_bindings(bindings.clone());
308
309 // binding is only enabled in a specific context
310 assert!(
311 keymap
312 .bindings_for_input(
313 &[Keystroke::parse("ctrl-a").unwrap()],
314 &[KeyContext::parse("barf").unwrap()],
315 )
316 .0
317 .is_empty()
318 );
319 assert!(
320 !keymap
321 .bindings_for_input(
322 &[Keystroke::parse("ctrl-a").unwrap()],
323 &[KeyContext::parse("editor").unwrap()],
324 )
325 .0
326 .is_empty()
327 );
328
329 // binding is disabled in a more specific context
330 assert!(
331 keymap
332 .bindings_for_input(
333 &[Keystroke::parse("ctrl-a").unwrap()],
334 &[KeyContext::parse("editor mode=full").unwrap()],
335 )
336 .0
337 .is_empty()
338 );
339
340 // binding is globally disabled
341 assert!(
342 keymap
343 .bindings_for_input(
344 &[Keystroke::parse("ctrl-b").unwrap()],
345 &[KeyContext::parse("barf").unwrap()],
346 )
347 .0
348 .is_empty()
349 );
350 }
351
352 #[test]
353 /// Tests for https://github.com/zed-industries/zed/issues/30259
354 fn test_multiple_keystroke_binding_disabled() {
355 let bindings = [
356 KeyBinding::new("space w w", ActionAlpha {}, Some("workspace")),
357 KeyBinding::new("space w w", NoAction {}, Some("editor")),
358 ];
359
360 let mut keymap = Keymap::default();
361 keymap.add_bindings(bindings.clone());
362
363 let space = || Keystroke::parse("space").unwrap();
364 let w = || Keystroke::parse("w").unwrap();
365
366 let space_w = [space(), w()];
367 let space_w_w = [space(), w(), w()];
368
369 let workspace_context = || [KeyContext::parse("workspace").unwrap()];
370
371 let editor_workspace_context = || {
372 [
373 KeyContext::parse("workspace").unwrap(),
374 KeyContext::parse("editor").unwrap(),
375 ]
376 };
377
378 // Ensure `space` results in pending input on the workspace, but not editor
379 let space_workspace = keymap.bindings_for_input(&[space()], &workspace_context());
380 assert!(space_workspace.0.is_empty());
381 assert_eq!(space_workspace.1, true);
382
383 let space_editor = keymap.bindings_for_input(&[space()], &editor_workspace_context());
384 assert!(space_editor.0.is_empty());
385 assert_eq!(space_editor.1, false);
386
387 // Ensure `space w` results in pending input on the workspace, but not editor
388 let space_w_workspace = keymap.bindings_for_input(&space_w, &workspace_context());
389 assert!(space_w_workspace.0.is_empty());
390 assert_eq!(space_w_workspace.1, true);
391
392 let space_w_editor = keymap.bindings_for_input(&space_w, &editor_workspace_context());
393 assert!(space_w_editor.0.is_empty());
394 assert_eq!(space_w_editor.1, false);
395
396 // Ensure `space w w` results in the binding in the workspace, but not in the editor
397 let space_w_w_workspace = keymap.bindings_for_input(&space_w_w, &workspace_context());
398 assert!(!space_w_w_workspace.0.is_empty());
399 assert_eq!(space_w_w_workspace.1, false);
400
401 let space_w_w_editor = keymap.bindings_for_input(&space_w_w, &editor_workspace_context());
402 assert!(space_w_w_editor.0.is_empty());
403 assert_eq!(space_w_w_editor.1, false);
404
405 // Now test what happens if we have another binding defined AFTER the NoAction
406 // that should result in pending
407 let bindings = [
408 KeyBinding::new("space w w", ActionAlpha {}, Some("workspace")),
409 KeyBinding::new("space w w", NoAction {}, Some("editor")),
410 KeyBinding::new("space w x", ActionAlpha {}, Some("editor")),
411 ];
412 let mut keymap = Keymap::default();
413 keymap.add_bindings(bindings.clone());
414
415 let space_editor = keymap.bindings_for_input(&[space()], &editor_workspace_context());
416 assert!(space_editor.0.is_empty());
417 assert_eq!(space_editor.1, true);
418
419 // Now test what happens if we have another binding defined BEFORE the NoAction
420 // that should result in pending
421 let bindings = [
422 KeyBinding::new("space w w", ActionAlpha {}, Some("workspace")),
423 KeyBinding::new("space w x", ActionAlpha {}, Some("editor")),
424 KeyBinding::new("space w w", NoAction {}, Some("editor")),
425 ];
426 let mut keymap = Keymap::default();
427 keymap.add_bindings(bindings.clone());
428
429 let space_editor = keymap.bindings_for_input(&[space()], &editor_workspace_context());
430 assert!(space_editor.0.is_empty());
431 assert_eq!(space_editor.1, true);
432
433 // Now test what happens if we have another binding defined at a higher context
434 // that should result in pending
435 let bindings = [
436 KeyBinding::new("space w w", ActionAlpha {}, Some("workspace")),
437 KeyBinding::new("space w x", ActionAlpha {}, Some("workspace")),
438 KeyBinding::new("space w w", NoAction {}, Some("editor")),
439 ];
440 let mut keymap = Keymap::default();
441 keymap.add_bindings(bindings.clone());
442
443 let space_editor = keymap.bindings_for_input(&[space()], &editor_workspace_context());
444 assert!(space_editor.0.is_empty());
445 assert_eq!(space_editor.1, true);
446 }
447
448 #[test]
449 fn test_bindings_for_action() {
450 let bindings = [
451 KeyBinding::new("ctrl-a", ActionAlpha {}, Some("pane")),
452 KeyBinding::new("ctrl-b", ActionBeta {}, Some("editor && mode == full")),
453 KeyBinding::new("ctrl-c", ActionGamma {}, Some("workspace")),
454 KeyBinding::new("ctrl-a", NoAction {}, Some("pane && active")),
455 KeyBinding::new("ctrl-b", NoAction {}, Some("editor")),
456 ];
457
458 let mut keymap = Keymap::default();
459 keymap.add_bindings(bindings.clone());
460
461 assert_bindings(&keymap, &ActionAlpha {}, &["ctrl-a"]);
462 assert_bindings(&keymap, &ActionBeta {}, &[]);
463 assert_bindings(&keymap, &ActionGamma {}, &["ctrl-c"]);
464
465 #[track_caller]
466 fn assert_bindings(keymap: &Keymap, action: &dyn Action, expected: &[&str]) {
467 let actual = keymap
468 .bindings_for_action(action)
469 .map(|binding| binding.keystrokes[0].unparse())
470 .collect::<Vec<_>>();
471 assert_eq!(actual, expected, "{:?}", action);
472 }
473 }
474}