Debian Codegraph @

helix-term/src/keymap.rs

raw symbols SCIP
1 pub mod default;
2 pub mod macros;
3
4 pub use crate::commands::MappableCommand;
5 pub use default::default;
6
7 use arc_swap::{
8 access::{DynAccess, DynGuard},
9 ArcSwap,
10 };
11 use helix_view::{document::Mode, info::Info, input::KeyEvent};
12 use indexmap::IndexMap;
13 use macros::key;
14 use serde::Deserialize;
15 use std::{
16 borrow::Cow,
17 collections::{BTreeSet, HashMap},
18 ops::{Deref, DerefMut},
19 sync::Arc,
20 };
21
22 #[derive(Debug, Clone, Default, Deserialize)]
23 pub struct KeyTrieNode {
24 /// A label for keys coming under this node, like "Goto mode"
25 #[serde(skip)]
26 name: String,
27 #[serde(flatten)]
28 map: IndexMap<KeyEvent, KeyTrie>,
29 #[serde(skip)]
30 pub is_sticky: bool,
31 }
32
33 impl KeyTrieNode {
34 pub fn new(name: &str, map: IndexMap<KeyEvent, KeyTrie>) -> Self {
35 Self {
36 name: name.to_string(),
37 map,
38 is_sticky: false,
39 }
40 }
41
42 /// Merge another Node in. Leaves and subnodes from the other node replace
43 /// corresponding keyevent in self, except when both other and self have
44 /// subnodes for same key. In that case the merge is recursive.
45 pub fn merge(&mut self, mut other: Self) {
46 for (key, trie) in std::mem::take(&mut other.map) {
47 if let Some(KeyTrie::Node(node)) = self.map.get_mut(&key) {
48 if let KeyTrie::Node(other_node) = trie {
49 node.merge(other_node);
50 continue;
51 }
52 }
53 self.map.insert(key, trie);
54 }
55 }
56
57 pub fn infobox(&self) -> Info {
58 let mut body: Vec<(BTreeSet<KeyEvent>, &str)> = Vec::with_capacity(self.len());
59 for (&key, trie) in self.iter() {
60 let desc = match trie {
61 KeyTrie::MappableCommand(cmd) => {
62 if cmd.name() == "no_op" {
63 continue;
64 }
65 cmd.doc()
66 }
67 KeyTrie::Node(n) => &n.name,
68 KeyTrie::Sequence(_) => "[Multiple commands]",
69 };
70 match body.iter().position(|(_, d)| d == &desc) {
71 Some(pos) => {
72 body[pos].0.insert(key);
73 }
74 None => body.push((BTreeSet::from([key]), desc)),
75 }
76 }
77
78 let body: Vec<_> = body
79 .into_iter()
80 .map(|(events, desc)| {
81 let events = events.iter().map(ToString::to_string).collect::<Vec<_>>();
82 (events.join(", "), desc)
83 })
84 .collect();
85 Info::new(self.name.clone(), &body)
86 }
87 }
88
89 impl PartialEq for KeyTrieNode {
90 fn eq(&self, other: &Self) -> bool {
91 self.map == other.map
92 }
93 }
94
95 impl Deref for KeyTrieNode {
96 type Target = IndexMap<KeyEvent, KeyTrie>;
97
98 fn deref(&self) -> &Self::Target {
99 &self.map
100 }
101 }
102
103 impl DerefMut for KeyTrieNode {
104 fn deref_mut(&mut self) -> &mut Self::Target {
105 &mut self.map
106 }
107 }
108
109 #[derive(Debug, Clone, PartialEq)]
110 pub enum KeyTrie {
111 MappableCommand(MappableCommand),
112 Sequence(Vec<MappableCommand>),
113 Node(KeyTrieNode),
114 }
115
116 impl<'de> Deserialize<'de> for KeyTrie {
117 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
118 where
119 D: serde::Deserializer<'de>,
120 {
121 deserializer.deserialize_any(KeyTrieVisitor)
122 }
123 }
124
125 struct KeyTrieVisitor;
126
127 impl<'de> serde::de::Visitor<'de> for KeyTrieVisitor {
128 type Value = KeyTrie;
129
130 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
131 write!(formatter, "a command, list of commands, or sub-keymap")
132 }
133
134 fn visit_str<E>(self, command: &str) -> Result<Self::Value, E>
135 where
136 E: serde::de::Error,
137 {
138 command
139 .parse::<MappableCommand>()
140 .map(KeyTrie::MappableCommand)
141 .map_err(E::custom)
142 }
143
144 fn visit_seq<S>(self, mut seq: S) -> Result<Self::Value, S::Error>
145 where
146 S: serde::de::SeqAccess<'de>,
147 {
148 let mut commands = Vec::new();
149 while let Some(command) = seq.next_element::<String>()? {
150 commands.push(
151 command
152 .parse::<MappableCommand>()
153 .map_err(serde::de::Error::custom)?,
154 )
155 }
156
157 // Prevent macro keybindings from being used in command sequences.
158 // This is meant to be a temporary restriction pending a larger
159 // refactor of how command sequences are executed.
160 if commands
161 .iter()
162 .any(|cmd| matches!(cmd, MappableCommand::Macro { .. }))
163 {
164 return Err(serde::de::Error::custom(
165 "macro keybindings may not be used in command sequences",
166 ));
167 }
168
169 Ok(KeyTrie::Sequence(commands))
170 }
171
172 fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
173 where
174 M: serde::de::MapAccess<'de>,
175 {
176 let mut mapping = IndexMap::new();
177 while let Some((key, value)) = map.next_entry::<KeyEvent, KeyTrie>()? {
178 mapping.insert(key, value);
179 }
180 Ok(KeyTrie::Node(KeyTrieNode::new("", mapping)))
181 }
182 }
183
184 impl KeyTrie {
185 pub fn reverse_map(&self) -> ReverseKeymap {
186 // recursively visit all nodes in keymap
187 fn map_node(cmd_map: &mut ReverseKeymap, node: &KeyTrie, keys: &mut Vec<KeyEvent>) {
188 match node {
189 KeyTrie::MappableCommand(MappableCommand::Macro { .. }) => {}
190 KeyTrie::MappableCommand(cmd) => {
191 let name = cmd.name();
192 if name != "no_op" {
193 cmd_map.entry(name.into()).or_default().push(keys.clone())
194 }
195 }
196 KeyTrie::Node(next) => {
197 for (key, trie) in &next.map {
198 keys.push(*key);
199 map_node(cmd_map, trie, keys);
200 keys.pop();
201 }
202 }
203 KeyTrie::Sequence(_) => {}
204 };
205 }
206
207 let mut res = HashMap::new();
208 map_node(&mut res, self, &mut Vec::new());
209 res
210 }
211
212 pub fn node(&self) -> Option<&KeyTrieNode> {
213 match *self {
214 KeyTrie::Node(ref node) => Some(node),
215 KeyTrie::MappableCommand(_) | KeyTrie::Sequence(_) => None,
216 }
217 }
218
219 pub fn node_mut(&mut self) -> Option<&mut KeyTrieNode> {
220 match *self {
221 KeyTrie::Node(ref mut node) => Some(node),
222 KeyTrie::MappableCommand(_) | KeyTrie::Sequence(_) => None,
223 }
224 }
225
226 /// Merge another KeyTrie in, assuming that this KeyTrie and the other
227 /// are both Nodes. Panics otherwise.
228 pub fn merge_nodes(&mut self, mut other: Self) {
229 let node = std::mem::take(other.node_mut().unwrap());
230 self.node_mut().unwrap().merge(node);
231 }
232
233 /// Descend a trie following the given path of keys
234 pub fn search(&self, keys: &[KeyEvent]) -> Option<&KeyTrie> {
235 let mut trie = self;
236 for key in keys {
237 trie = match trie {
238 KeyTrie::Node(map) => map.get(key),
239 // leaf encountered while keys left to process
240 KeyTrie::MappableCommand(_) | KeyTrie::Sequence(_) => None,
241 }?
242 }
243 Some(trie)
244 }
245 }
246
247 #[derive(Debug, Clone, PartialEq)]
248 pub enum KeymapResult {
249 /// Needs more keys to execute a command. Contains valid keys for next keystroke.
250 Pending(KeyTrieNode),
251 Matched(MappableCommand),
252 /// Matched a sequence of commands to execute.
253 MatchedSequence(Vec<MappableCommand>),
254 /// Key was not found in the root keymap
255 NotFound,
256 /// Key is invalid in combination with previous keys. Contains keys leading upto
257 /// and including current (invalid) key.
258 Cancelled(Vec<KeyEvent>),
259 }
260
261 /// A map of command names to keybinds that will execute the command.
262 pub type ReverseKeymap = HashMap<String, Vec<Vec<KeyEvent>>>;
263
264 pub struct Keymaps {
265 pub map: Box<dyn DynAccess<HashMap<Mode, KeyTrie>>>,
266 /// Stores pending keys waiting for the next key. This is relative to a
267 /// sticky node if one is in use.
268 state: Vec<KeyEvent>,
269 /// Stores the sticky node if one is activated.
270 pub sticky: Option<KeyTrieNode>,
271 }
272
273 impl Keymaps {
274 pub fn new(map: Box<dyn DynAccess<HashMap<Mode, KeyTrie>>>) -> Self {
275 Self {
276 map,
277 state: Vec::new(),
278 sticky: None,
279 }
280 }
281
282 pub fn map(&self) -> DynGuard<HashMap<Mode, KeyTrie>> {
283 self.map.load()
284 }
285
286 /// Returns list of keys waiting to be disambiguated in current mode.
287 pub fn pending(&self) -> &[KeyEvent] {
288 &self.state
289 }
290
291 pub fn sticky(&self) -> Option<&KeyTrieNode> {
292 self.sticky.as_ref()
293 }
294
295 pub fn contains_key(&self, mode: Mode, key: KeyEvent) -> bool {
296 let keymaps = &*self.map();
297 let keymap = &keymaps[&mode];
298 keymap
299 .search(self.pending())
300 .and_then(KeyTrie::node)
301 .is_some_and(|node| node.contains_key(&key))
302 }
303
304 /// Lookup `key` in the keymap to try and find a command to execute. Escape
305 /// key cancels pending keystrokes. If there are no pending keystrokes but a
306 /// sticky node is in use, it will be cleared.
307 pub fn get(&mut self, mode: Mode, key: KeyEvent) -> KeymapResult {
308 // TODO: remove the sticky part and look up manually
309 let keymaps = &*self.map();
310 let keymap = &keymaps[&mode];
311
312 if key!(Esc) == key {
313 if !self.state.is_empty() {
314 // Note that Esc is not included here
315 return KeymapResult::Cancelled(self.state.drain(..).collect());
316 }
317 self.sticky = None;
318 }
319
320 let first = self.state.first().unwrap_or(&key);
321 let trie_node = match self.sticky {
322 Some(ref trie) => Cow::Owned(KeyTrie::Node(trie.clone())),
323 None => Cow::Borrowed(keymap),
324 };
325
326 let trie = match trie_node.search(&[*first]) {
327 Some(KeyTrie::MappableCommand(ref cmd)) => {
328 return KeymapResult::Matched(cmd.clone());
329 }
330 Some(KeyTrie::Sequence(ref cmds)) => {
331 return KeymapResult::MatchedSequence(cmds.clone());
332 }
333 None => return KeymapResult::NotFound,
334 Some(t) => t,
335 };
336
337 self.state.push(key);
338 match trie.search(&self.state[1..]) {
339 Some(KeyTrie::Node(map)) => {
340 if map.is_sticky {
341 self.state.clear();
342 self.sticky = Some(map.clone());
343 }
344 KeymapResult::Pending(map.clone())
345 }
346 Some(KeyTrie::MappableCommand(cmd)) => {
347 self.state.clear();
348 KeymapResult::Matched(cmd.clone())
349 }
350 Some(KeyTrie::Sequence(cmds)) => {
351 self.state.clear();
352 KeymapResult::MatchedSequence(cmds.clone())
353 }
354 None => KeymapResult::Cancelled(self.state.drain(..).collect()),
355 }
356 }
357 }
358
359 impl Default for Keymaps {
360 fn default() -> Self {
361 Self::new(Box::new(ArcSwap::new(Arc::new(default()))))
362 }
363 }
364
365 /// Merge default config keys with user overwritten keys for custom user config.
366 pub fn merge_keys(dst: &mut HashMap<Mode, KeyTrie>, mut delta: HashMap<Mode, KeyTrie>) {
367 for (mode, keys) in dst {
368 keys.merge_nodes(
369 delta
370 .remove(mode)
371 .unwrap_or_else(|| KeyTrie::Node(KeyTrieNode::default())),
372 )
373 }
374 }
375
376 #[cfg(test)]
377 mod tests {
378 use super::macros::keymap;
379 use super::*;
380 use crate::commands::MappableCommand;
381 use arc_swap::access::Constant;
382 use helix_core::hashmap;
383 use helix_view::input::{KeyCode, KeyEvent, KeyModifiers};
384 use indexmap::indexmap;
385
386 #[test]
387 #[should_panic]
388 fn duplicate_keys_should_panic() {
389 keymap!({ "Normal mode"
390 "i" => normal_mode,
391 "i" => goto_definition,
392 });
393 }
394
395 #[test]
396 fn check_duplicate_keys_in_default_keymap() {
397 // will panic on duplicate keys, assumes that `Keymaps` uses keymap! macro
398 Keymaps::default();
399 }
400
401 #[test]
402 fn merge_partial_keys() {
403 let keymap = hashmap! {
404 Mode::Normal => keymap!({ "Normal mode"
405 "i" => normal_mode,
406 "无" => insert_mode,
407 "z" => jump_backward,
408 "g" => { "Merge into goto mode"
409 "$" => goto_line_end,
410 "g" => delete_char_forward,
411 },
412 })
413 };
414 let mut merged_keyamp = default();
415 merge_keys(&mut merged_keyamp, keymap.clone());
416 assert_ne!(keymap, merged_keyamp);
417
418 let mut keymap = Keymaps::new(Box::new(Constant(merged_keyamp.clone())));
419 assert_eq!(
420 keymap.get(Mode::Normal, key!('i')),
421 KeymapResult::Matched(MappableCommand::normal_mode),
422 "Leaf should replace leaf"
423 );
424 assert_eq!(
425 keymap.get(Mode::Normal, key!('无')),
426 KeymapResult::Matched(MappableCommand::insert_mode),
427 "New leaf should be present in merged keymap"
428 );
429 // Assumes that z is a node in the default keymap
430 assert_eq!(
431 keymap.get(Mode::Normal, key!('z')),
432 KeymapResult::Matched(MappableCommand::jump_backward),
433 "Leaf should replace node"
434 );
435
436 let keymap = merged_keyamp.get_mut(&Mode::Normal).unwrap();
437 // Assumes that `g` is a node in default keymap
438 assert_eq!(
439 keymap.search(&[key!('g'), key!('$')]).unwrap(),
440 &KeyTrie::MappableCommand(MappableCommand::goto_line_end),
441 "Leaf should be present in merged subnode"
442 );
443 // Assumes that `gg` is in default keymap
444 assert_eq!(
445 keymap.search(&[key!('g'), key!('g')]).unwrap(),
446 &KeyTrie::MappableCommand(MappableCommand::delete_char_forward),
447 "Leaf should replace old leaf in merged subnode"
448 );
449 // Assumes that `ge` is in default keymap
450 assert_eq!(
451 keymap.search(&[key!('g'), key!('e')]).unwrap(),
452 &KeyTrie::MappableCommand(MappableCommand::goto_last_line),
453 "Old leaves in subnode should be present in merged node"
454 );
455
456 assert!(
457 merged_keyamp
458 .get(&Mode::Normal)
459 .and_then(|key_trie| key_trie.node())
460 .unwrap()
461 .len()
462 > 1
463 );
464 assert!(!merged_keyamp
465 .get(&Mode::Insert)
466 .and_then(|key_trie| key_trie.node())
467 .unwrap()
468 .is_empty());
469 }
470
471 #[test]
472 fn order_should_be_set() {
473 let keymap = hashmap! {
474 Mode::Normal => keymap!({ "Normal mode"
475 "space" => { ""
476 "s" => { ""
477 "v" => vsplit,
478 "c" => hsplit,
479 },
480 },
481 })
482 };
483 let mut merged_keymap = default();
484 merge_keys(&mut merged_keymap, keymap.clone());
485 assert_ne!(keymap, merged_keymap);
486 let keymap = merged_keymap.get_mut(&Mode::Normal).unwrap();
487 // Make sure mapping works
488 assert_eq!(
489 keymap.search(&[key!(' '), key!('s'), key!('v')]).unwrap(),
490 &KeyTrie::MappableCommand(MappableCommand::vsplit),
491 "Leaf should be present in merged subnode"
492 );
493 // Merged nodes were ordered at the end
494 let node = keymap.search(&[key!(' '), key!('s')]).unwrap();
495 assert_eq!(
496 node.node().unwrap().keys().copied().collect::<Vec<_>>(),
497 vec![key!('v'), key!('c')]
498 );
499 }
500
501 #[test]
502 fn aliased_modes_are_same_in_default_keymap() {
503 let keymaps = Keymaps::default().map();
504 let root = keymaps.get(&Mode::Normal).unwrap();
505 assert_eq!(
506 root.search(&[key!(' '), key!('w')]).unwrap(),
507 root.search(&["C-w".parse::<KeyEvent>().unwrap()]).unwrap(),
508 "Mismatch for window mode on `Space-w` and `Ctrl-w`"
509 );
510 assert_eq!(
511 root.search(&[key!('z')]).unwrap(),
512 root.search(&[key!('Z')]).unwrap(),
513 "Mismatch for view mode on `z` and `Z`"
514 );
515 }
516
517 #[test]
518 fn reverse_map() {
519 let normal_mode = keymap!({ "Normal mode"
520 "i" => insert_mode,
521 "g" => { "Goto"
522 "g" => goto_file_start,
523 "e" => goto_file_end,
524 },
525 "j" | "k" => move_line_down,
526 });
527 let keymap = normal_mode;
528 let mut reverse_map = keymap.reverse_map();
529
530 // sort keybindings in order to have consistent tests
531 // HashMaps can be compared but we can still get different ordering of bindings
532 // for commands that have multiple bindings assigned
533 for v in reverse_map.values_mut() {
534 v.sort()
535 }
536
537 assert_eq!(
538 reverse_map,
539 HashMap::from([
540 ("insert_mode".to_string(), vec![vec![key!('i')]]),
541 (
542 "goto_file_start".to_string(),
543 vec![vec![key!('g'), key!('g')]]
544 ),
545 (
546 "goto_file_end".to_string(),
547 vec![vec![key!('g'), key!('e')]]
548 ),
549 (
550 "move_line_down".to_string(),
551 vec![vec![key!('j')], vec![key!('k')]]
552 ),
553 ]),
554 "Mismatch"
555 )
556 }
557
558 /// Deserialize into KeyTrieNode
559 #[test]
560 fn deserialize_node() {
561 let keys = r#"
562 "+" = "select_all"
563 a = "append_mode"
564 "#;
565 let expectation = KeyTrie::Node(KeyTrieNode::new(
566 "",
567 indexmap! {
568 key!('+') => KeyTrie::MappableCommand(
569 MappableCommand::select_all
570 ),
571 key!('a') => KeyTrie::MappableCommand(
572 MappableCommand::append_mode
573 ),
574 },
575 ));
576
577 assert_eq!(toml::from_str(keys), Ok(expectation));
578
579 // Other fields in KeyTrieNode CANNOT be deserialized
580 let invalid = r#"
581 name = "name"
582 is_sticky = false
583 "#;
584 let result = toml::from_str::<KeyTrieNode>(invalid);
585 assert!(result.is_err_and(|error| error.message().contains("Invalid key code 'is_sticky'")));
586 }
587
588 #[test]
589 fn escaped_keymap() {
590 let keys = r#"
591 "+" = [
592 "select_all",
593 ":pipe sed -E 's/\\s+$//g'",
594 ]
595 "#;
596
597 let key = KeyEvent {
598 code: KeyCode::Char('+'),
599 modifiers: KeyModifiers::NONE,
600 };
601
602 let expectation = KeyTrie::Node(KeyTrieNode::new(
603 "",
604 indexmap! {
605 key => KeyTrie::Sequence(vec!{
606 MappableCommand::select_all,
607 MappableCommand::Typable {
608 name: "pipe".to_string(),
609 args: "sed -E 's/\\s+$//g'".to_string(),
610 doc: "".to_string(),
611 },
612 })
613 },
614 ));
615
616 assert_eq!(toml::from_str(keys), Ok(expectation));
617 }
618 }