1use std::collections::HashMap;
6
7#[derive(Clone, Debug, PartialEq, Eq, Hash)]
10pub struct KeyPress {
11 pub ctrl: bool,
12 pub shift: bool,
13 pub alt: bool,
14 pub meta: bool,
15 pub key: String,
16}
17
18impl KeyPress {
19 pub fn parse(s: &str) -> Option<KeyPress> {
22 let mut k = KeyPress { ctrl: false, shift: false, alt: false, meta: false, key: String::new() };
23 let lower = s.to_ascii_lowercase();
24 let mut parts: Vec<&str> = lower.split('+').collect();
25 if lower.ends_with("++") {
27 parts.retain(|p| !p.is_empty());
28 parts.push("+");
29 }
30 let (last, mods) = parts.split_last()?;
31 for m in mods {
32 match *m {
33 "ctrl" => k.ctrl = true,
34 "shift" => k.shift = true,
35 "alt" | "option" => k.alt = true,
36 "cmd" | "meta" | "win" | "super" => k.meta = true,
37 _ => return None,
38 }
39 }
40 k.key = match *last {
41 "up" => "arrowup",
42 "down" => "arrowdown",
43 "left" => "arrowleft",
44 "right" => "arrowright",
45 "esc" => "escape",
46 "space" => " ",
47 "pageup" => "pageup",
48 "pagedown" => "pagedown",
49 other => other,
50 }
51 .to_owned();
52 (!k.key.is_empty()).then_some(k)
53 }
54
55 fn matches(&self, pressed: &KeyPress) -> bool {
59 let symbol = self.key.chars().count() == 1 && !self.key.chars().all(char::is_alphanumeric);
60 self.key == pressed.key
61 && self.ctrl == pressed.ctrl
62 && self.alt == pressed.alt
63 && self.meta == pressed.meta
64 && (symbol || self.shift == pressed.shift)
65 }
66}
67
68#[derive(Clone, Debug, PartialEq, Eq)]
69pub struct Binding {
70 pub keys: Vec<KeyPress>,
72 pub command: String,
73 pub when: Option<String>,
74}
75
76#[derive(Clone, Copy, Debug, PartialEq, Eq)]
77pub enum Platform {
78 Windows,
79 Linux,
80 Mac,
81}
82
83#[derive(Clone, Debug, PartialEq, Eq)]
85pub enum Resolved {
86 Command(String),
87 Pending,
89 Unbound,
91}
92
93#[derive(Clone, Debug, Default)]
94pub struct Keymap {
95 bindings: Vec<Binding>,
96 pending: Option<KeyPress>,
97}
98
99impl Keymap {
100 pub fn from_entries<'a>(entries: impl IntoIterator<Item = (&'a str, &'a str, Option<&'a str>)>) -> Keymap {
104 let mut bindings: Vec<Binding> = Vec::new();
105 for (keys, command, when) in entries {
106 let Some(keys) = keys.split_whitespace().map(KeyPress::parse).collect::<Option<Vec<_>>>() else { continue };
107 if let Some(removed) = command.strip_prefix('-') {
108 bindings.retain(|b| !(b.keys == keys && b.command == removed));
109 continue;
110 }
111 bindings.push(Binding { keys, command: command.to_owned(), when: when.map(str::to_owned) });
112 }
113 Keymap { bindings, pending: None }
114 }
115
116 pub fn bindings(&self) -> &[Binding] {
117 &self.bindings
118 }
119
120 pub fn extend<'a>(&mut self, entries: impl IntoIterator<Item = (&'a str, &'a str, Option<&'a str>)>) {
122 let mut all: Vec<(String, String, Option<String>)> =
123 self.bindings.iter().map(|b| (keys_to_string(&b.keys), b.command.clone(), b.when.clone())).collect();
124 all.extend(entries.into_iter().map(|(k, c, w)| (k.to_owned(), c.to_owned(), w.map(str::to_owned))));
125 *self = Keymap::from_entries(all.iter().map(|(k, c, w)| (k.as_str(), c.as_str(), w.as_deref())));
126 }
127
128 pub fn resolve(&mut self, pressed: &KeyPress, context: &HashMap<String, bool>) -> Resolved {
131 if matches!(pressed.key.as_str(), "control" | "shift" | "alt" | "meta" | "os" | "altgraph" | "capslock") {
134 return Resolved::Unbound;
135 }
136 let applies = |b: &Binding| b.when.as_deref().is_none_or(|w| eval_when(w, context));
137 if let Some(first) = self.pending.take() {
138 return self
139 .bindings
140 .iter()
141 .rev()
142 .find(|b| b.keys.len() == 2 && b.keys[0].matches(&first) && b.keys[1].matches(pressed) && applies(b))
143 .map_or(Resolved::Unbound, |b| Resolved::Command(b.command.clone()));
144 }
145 if let Some(b) =
146 self.bindings.iter().rev().find(|b| b.keys.len() == 1 && b.keys[0].matches(pressed) && applies(b))
147 {
148 return Resolved::Command(b.command.clone());
149 }
150 if self.bindings.iter().any(|b| b.keys.len() == 2 && b.keys[0].matches(pressed) && applies(b)) {
151 self.pending = Some(pressed.clone());
152 return Resolved::Pending;
153 }
154 Resolved::Unbound
155 }
156
157 pub fn has_pending_chord(&self) -> bool {
158 self.pending.is_some()
159 }
160}
161
162fn keys_to_string(keys: &[KeyPress]) -> String {
163 keys.iter()
164 .map(|k| {
165 let mut s = String::new();
166 for (on, name) in [(k.ctrl, "ctrl+"), (k.shift, "shift+"), (k.alt, "alt+"), (k.meta, "cmd+")] {
167 if on {
168 s.push_str(name);
169 }
170 }
171 s.push_str(if k.key == " " { "space" } else { &k.key });
172 s
173 })
174 .collect::<Vec<_>>()
175 .join(" ")
176}
177
178pub fn eval_when(expr: &str, context: &HashMap<String, bool>) -> bool {
181 expr.split("||").any(|conj| {
182 conj.split("&&").all(|term| {
183 let term = term.trim();
184 match term.strip_prefix('!') {
185 Some(key) => !context.get(key.trim()).copied().unwrap_or(false),
186 None => context.get(term).copied().unwrap_or(false),
187 }
188 })
189 })
190}
191
192type Entry = (&'static str, &'static str, Option<&'static str>);
194
195const SHARED: &[Entry] = &[
196 ("left", "cursorLeft", None),
197 ("shift+left", "cursorLeftSelect", None),
198 ("right", "cursorRight", None),
199 ("shift+right", "cursorRightSelect", None),
200 ("up", "cursorUp", None),
201 ("shift+up", "cursorUpSelect", None),
202 ("down", "cursorDown", None),
203 ("shift+down", "cursorDownSelect", None),
204 ("pageup", "cursorPageUp", None),
205 ("shift+pageup", "cursorPageUpSelect", None),
206 ("pagedown", "cursorPageDown", None),
207 ("shift+pagedown", "cursorPageDownSelect", None),
208 ("backspace", "deleteLeft", None),
209 ("shift+backspace", "deleteLeft", None),
210 ("delete", "deleteRight", None),
211 ("enter", "editor.action.newline", None),
212 ("shift+enter", "editor.action.newline", None),
213 ("tab", "tab", None),
214 ("shift+tab", "outdent", None),
215 ("escape", "removeSecondaryCursors", Some("editorHasMultipleSelections")),
216 ("escape", "cancelSelection", Some("editorHasSelection && !editorHasMultipleSelections")),
217 ("tab", "jumpToNextSnippetPlaceholder", Some("inSnippetMode")),
218 ("shift+tab", "jumpToPrevSnippetPlaceholder", Some("inSnippetMode")),
219 ("escape", "leaveSnippet", Some("inSnippetMode")),
220 ("ctrl+space", "editor.action.triggerSuggest", None),
221 ("ctrl+shift+space", "editor.action.triggerParameterHints", None),
222 ("f12", "editor.action.revealDefinition", None),
223 ("shift+f12", "editor.action.referenceSearch.trigger", None),
224 ("f2", "editor.action.rename", None),
225 ("shift+alt+f", "editor.action.formatDocument", None),
226 ("alt+up", "editor.action.moveLinesUpAction", None),
227 ("alt+down", "editor.action.moveLinesDownAction", None),
228 ("shift+alt+up", "editor.action.copyLinesUpAction", None),
229 ("shift+alt+down", "editor.action.copyLinesDownAction", None),
230 ("shift+alt+a", "editor.action.blockComment", None),
231 ("shift+alt+right", "editor.action.smartSelect.expand", None),
232 ("shift+alt+left", "editor.action.smartSelect.shrink", None),
233 ("f3", "editor.action.nextMatchFindAction", None),
234 ("shift+f3", "editor.action.previousMatchFindAction", None),
235];
236
237const WINDOWS_LINUX: &[Entry] = &[
238 ("ctrl+left", "cursorWordLeft", None),
239 ("ctrl+shift+left", "cursorWordLeftSelect", None),
240 ("ctrl+right", "cursorWordRight", None),
241 ("ctrl+shift+right", "cursorWordRightSelect", None),
242 ("home", "cursorHome", None),
243 ("shift+home", "cursorHomeSelect", None),
244 ("end", "cursorEnd", None),
245 ("shift+end", "cursorEndSelect", None),
246 ("ctrl+home", "cursorTop", None),
247 ("ctrl+shift+home", "cursorTopSelect", None),
248 ("ctrl+end", "cursorBottom", None),
249 ("ctrl+shift+end", "cursorBottomSelect", None),
250 ("ctrl+backspace", "deleteWordLeft", None),
251 ("ctrl+delete", "deleteWordRight", None),
252 ("ctrl+a", "editor.action.selectAll", None),
253 ("ctrl+z", "undo", None),
254 ("ctrl+y", "redo", None),
255 ("ctrl+shift+z", "redo", None),
256 ("ctrl+enter", "editor.action.insertLineAfter", None),
257 ("ctrl+shift+enter", "editor.action.insertLineBefore", None),
258 ("ctrl+shift+k", "editor.action.deleteLines", None),
259 ("ctrl+/", "editor.action.commentLine", None),
260 ("ctrl+d", "editor.action.addSelectionToNextFindMatch", None),
261 ("ctrl+shift+l", "editor.action.selectHighlights", None),
262 ("ctrl+alt+up", "editor.action.insertCursorAbove", None),
263 ("ctrl+alt+down", "editor.action.insertCursorBelow", None),
264 ("ctrl+k ctrl+x", "editor.action.trimTrailingWhitespace", None),
265 ("ctrl+u", "cursorUndo", None),
266 ("ctrl+shift+\\", "editor.action.jumpToBracket", None),
267 ("ctrl+]", "editor.action.indentLines", None),
268 ("ctrl+[", "editor.action.outdentLines", None),
269 ("ctrl+f", "actions.find", None),
270 ("ctrl+k ctrl+i", "editor.action.showHover", None),
271 ("ctrl+.", "editor.action.quickFix", None),
272 ("ctrl+shift+o", "editor.action.quickOutline", None),
273 ("ctrl+h", "editor.action.startFindReplaceAction", None),
274 ("ctrl+shift+[", "editor.fold", None),
275 ("ctrl+shift+]", "editor.unfold", None),
276 ("ctrl+k ctrl+l", "editor.toggleFold", None),
277 ("ctrl+k ctrl+0", "editor.foldAll", None),
278 ("ctrl+k ctrl+j", "editor.unfoldAll", None),
279];
280
281const MAC: &[Entry] = &[
282 ("alt+left", "cursorWordLeft", None),
283 ("shift+alt+left", "cursorWordLeftSelect", None),
284 ("alt+right", "cursorWordRight", None),
285 ("shift+alt+right", "cursorWordRightSelect", None),
286 ("cmd+left", "cursorHome", None),
287 ("shift+cmd+left", "cursorHomeSelect", None),
288 ("cmd+right", "cursorEnd", None),
289 ("shift+cmd+right", "cursorEndSelect", None),
290 ("home", "cursorHome", None),
291 ("end", "cursorEnd", None),
292 ("cmd+up", "cursorTop", None),
293 ("shift+cmd+up", "cursorTopSelect", None),
294 ("cmd+down", "cursorBottom", None),
295 ("shift+cmd+down", "cursorBottomSelect", None),
296 ("alt+backspace", "deleteWordLeft", None),
297 ("alt+delete", "deleteWordRight", None),
298 ("cmd+a", "editor.action.selectAll", None),
299 ("cmd+z", "undo", None),
300 ("shift+cmd+z", "redo", None),
301 ("cmd+enter", "editor.action.insertLineAfter", None),
302 ("shift+cmd+enter", "editor.action.insertLineBefore", None),
303 ("shift+cmd+k", "editor.action.deleteLines", None),
304 ("cmd+/", "editor.action.commentLine", None),
305 ("cmd+d", "editor.action.addSelectionToNextFindMatch", None),
306 ("shift+cmd+l", "editor.action.selectHighlights", None),
307 ("alt+cmd+up", "editor.action.insertCursorAbove", None),
308 ("alt+cmd+down", "editor.action.insertCursorBelow", None),
309 ("cmd+k cmd+x", "editor.action.trimTrailingWhitespace", None),
310 ("cmd+u", "cursorUndo", None),
311 ("shift+cmd+\\", "editor.action.jumpToBracket", None),
312 ("cmd+]", "editor.action.indentLines", None),
313 ("cmd+[", "editor.action.outdentLines", None),
314 ("cmd+f", "actions.find", None),
315 ("cmd+k cmd+i", "editor.action.showHover", None),
316 ("cmd+.", "editor.action.quickFix", None),
317 ("shift+cmd+o", "editor.action.quickOutline", None),
318 ("alt+cmd+f", "editor.action.startFindReplaceAction", None),
319 ("alt+cmd+[", "editor.fold", None),
320 ("alt+cmd+]", "editor.unfold", None),
321 ("cmd+k cmd+l", "editor.toggleFold", None),
322 ("cmd+k cmd+0", "editor.foldAll", None),
323 ("cmd+k cmd+j", "editor.unfoldAll", None),
324 ("cmd+g", "editor.action.nextMatchFindAction", None),
325 ("shift+cmd+g", "editor.action.previousMatchFindAction", None),
326];
327
328const JETBRAINS: &[Entry] = &[
330 ("ctrl+d", "editor.action.copyLinesDownAction", None),
331 ("ctrl+y", "editor.action.deleteLines", None),
332 ("ctrl+shift+up", "editor.action.moveLinesUpAction", None),
333 ("ctrl+shift+down", "editor.action.moveLinesDownAction", None),
334 ("alt+j", "editor.action.addSelectionToNextFindMatch", None),
335 ("ctrl+shift+alt+j", "editor.action.selectHighlights", None),
336 ("ctrl+shift+u", "editor.action.transformToUppercase", None),
337];
338
339pub fn default_keymap(platform: Platform) -> Keymap {
341 let specific = if platform == Platform::Mac { MAC } else { WINDOWS_LINUX };
342 Keymap::from_entries(SHARED.iter().chain(specific).copied())
343}
344
345pub fn jetbrains_keymap(platform: Platform) -> Keymap {
347 let specific = if platform == Platform::Mac { MAC } else { WINDOWS_LINUX };
348 Keymap::from_entries(SHARED.iter().chain(specific).chain(JETBRAINS).copied())
349}
350
351#[cfg(test)]
352mod tests {
353 use super::*;
354
355 fn key(s: &str) -> KeyPress {
356 KeyPress::parse(s).unwrap()
357 }
358
359 fn ctx(pairs: &[(&str, bool)]) -> HashMap<String, bool> {
360 pairs.iter().map(|&(k, v)| (k.to_owned(), v)).collect()
361 }
362
363 #[test]
364 fn parses_keys() {
365 assert_eq!(key("Ctrl+Shift+K"), KeyPress { ctrl: true, shift: true, alt: false, meta: false, key: "k".into() });
366 assert_eq!(key("cmd+up").key, "arrowup");
367 assert_eq!(key("ctrl++").key, "+");
368 assert!(KeyPress::parse("hyper+x").is_none());
369 }
370
371 #[test]
372 fn resolves_single_keys_chords_and_when() {
373 let mut km = default_keymap(Platform::Windows);
374 let none = ctx(&[]);
375 assert_eq!(km.resolve(&key("ctrl+/"), &none), Resolved::Command("editor.action.commentLine".into()));
376 assert_eq!(km.resolve(&key("ctrl+shift+/"), &none), Resolved::Command("editor.action.commentLine".into()));
378 assert_eq!(km.resolve(&key("ctrl+k"), &none), Resolved::Pending);
379 assert_eq!(km.resolve(&key("ctrl+control"), &none), Resolved::Unbound);
381 assert_eq!(km.resolve(&key("ctrl+x"), &none), Resolved::Command("editor.action.trimTrailingWhitespace".into()));
382 assert_eq!(km.resolve(&key("escape"), &none), Resolved::Unbound);
383 assert_eq!(
384 km.resolve(&key("escape"), &ctx(&[("editorHasMultipleSelections", true), ("editorHasSelection", true)])),
385 Resolved::Command("removeSecondaryCursors".into())
386 );
387 assert_eq!(km.resolve(&key("ctrl+alt+a"), &none), Resolved::Unbound);
389 }
390
391 #[test]
392 fn later_entries_override_and_minus_removes() {
393 let mut km = default_keymap(Platform::Windows);
394 km.extend([("ctrl+d", "editor.action.copyLinesDownAction", None)]);
395 assert_eq!(
396 km.resolve(&key("ctrl+d"), &ctx(&[])),
397 Resolved::Command("editor.action.copyLinesDownAction".into())
398 );
399 km.extend([("ctrl+d", "-editor.action.copyLinesDownAction", None)]);
400 assert_eq!(
401 km.resolve(&key("ctrl+d"), &ctx(&[])),
402 Resolved::Command("editor.action.addSelectionToNextFindMatch".into())
403 );
404 let mut jb = jetbrains_keymap(Platform::Windows);
405 assert_eq!(jb.resolve(&key("ctrl+y"), &ctx(&[])), Resolved::Command("editor.action.deleteLines".into()));
406 }
407
408 #[test]
409 fn when_clauses() {
410 let c = ctx(&[("a", true), ("b", false)]);
411 assert!(eval_when("a && !b", &c));
412 assert!(eval_when("b || a", &c));
413 assert!(!eval_when("a && b", &c));
414 assert!(!eval_when("unknown", &c));
415 }
416}