Skip to main content

rustaco_core/
keymap.rs

1//! Keybindings: key chords mapped to command ids, with `when` conditions and chords of two
2//! keys. Keymaps are data (VS Code's format, flattened), so presets and user overrides are
3//! lists of entries, not code.
4
5use std::collections::HashMap;
6
7/// A key with modifiers. `key` is the `KeyboardEvent.key` value, lowercased (`"a"`, `"/"`,
8/// `"arrowup"`, `"enter"`, `"f2"`).
9#[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    /// Parses `"ctrl+shift+k"`, `"cmd+/"`, `"alt+up"`. `cmd` and `win` mean the meta key;
20    /// `up`, `down`, `left`, `right` and `esc` are short for the DOM key names.
21    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        // "ctrl++" binds the plus key.
26        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    /// Whether a pressed key matches this binding key. For symbol keys (not letters, digits
56    /// or named keys) shift is ignored: on many layouts `/` or `[` need shift to type, and a
57    /// `ctrl+/` binding should still fire. The space bar is a named key: `ctrl+space` and
58    /// `ctrl+shift+space` are different commands.
59    fn matches(&self, pressed: &KeyPress) -> bool {
60        let symbol = self.key.chars().count() == 1 && !self.key.chars().all(char::is_alphanumeric) && self.key != " ";
61        self.key == pressed.key
62            && self.ctrl == pressed.ctrl
63            && self.alt == pressed.alt
64            && self.meta == pressed.meta
65            && (symbol || self.shift == pressed.shift)
66    }
67}
68
69#[derive(Clone, Debug, PartialEq, Eq)]
70pub struct Binding {
71    /// One key, or two for a chord (`ctrl+k ctrl+x`).
72    pub keys: Vec<KeyPress>,
73    pub command: String,
74    pub when: Option<String>,
75}
76
77#[derive(Clone, Copy, Debug, PartialEq, Eq)]
78pub enum Platform {
79    Windows,
80    Linux,
81    Mac,
82}
83
84/// What a key press resolved to.
85#[derive(Clone, Debug, PartialEq, Eq)]
86pub enum Resolved {
87    Command(String),
88    /// The first key of a chord; the next key completes it.
89    Pending,
90    /// Not bound: the frontend lets the key through (typing, AltGr characters).
91    Unbound,
92}
93
94#[derive(Clone, Debug, Default)]
95pub struct Keymap {
96    bindings: Vec<Binding>,
97    pending: Option<KeyPress>,
98}
99
100impl Keymap {
101    /// Builds a keymap from (keys, command, when) entries. Later entries win over earlier
102    /// ones for the same keys, so user entries go last. A command starting with `-` removes
103    /// that command's earlier binding for the keys, as in VS Code.
104    pub fn from_entries<'a>(entries: impl IntoIterator<Item = (&'a str, &'a str, Option<&'a str>)>) -> Keymap {
105        let mut bindings: Vec<Binding> = Vec::new();
106        for (keys, command, when) in entries {
107            let Some(keys) = keys.split_whitespace().map(KeyPress::parse).collect::<Option<Vec<_>>>() else { continue };
108            if let Some(removed) = command.strip_prefix('-') {
109                bindings.retain(|b| !(b.keys == keys && b.command == removed));
110                continue;
111            }
112            bindings.push(Binding { keys, command: command.to_owned(), when: when.map(str::to_owned) });
113        }
114        Keymap { bindings, pending: None }
115    }
116
117    pub fn bindings(&self) -> &[Binding] {
118        &self.bindings
119    }
120
121    /// Appends entries (user overrides) on top of the current bindings.
122    pub fn extend<'a>(&mut self, entries: impl IntoIterator<Item = (&'a str, &'a str, Option<&'a str>)>) {
123        let mut all: Vec<(String, String, Option<String>)> =
124            self.bindings.iter().map(|b| (keys_to_string(&b.keys), b.command.clone(), b.when.clone())).collect();
125        all.extend(entries.into_iter().map(|(k, c, w)| (k.to_owned(), c.to_owned(), w.map(str::to_owned))));
126        *self = Keymap::from_entries(all.iter().map(|(k, c, w)| (k.as_str(), c.as_str(), w.as_deref())));
127    }
128
129    /// Resolves a key press against the bindings whose `when` holds in `context`. The last
130    /// matching binding wins.
131    pub fn resolve(&mut self, pressed: &KeyPress, context: &HashMap<String, bool>) -> Resolved {
132        // Pressing a modifier on its own (the first event of every shortcut) neither matches
133        // nor cancels a pending chord.
134        if matches!(pressed.key.as_str(), "control" | "shift" | "alt" | "meta" | "os" | "altgraph" | "capslock") {
135            return Resolved::Unbound;
136        }
137        let applies = |b: &Binding| b.when.as_deref().is_none_or(|w| eval_when(w, context));
138        if let Some(first) = self.pending.take() {
139            return self
140                .bindings
141                .iter()
142                .rev()
143                .find(|b| b.keys.len() == 2 && b.keys[0].matches(&first) && b.keys[1].matches(pressed) && applies(b))
144                .map_or(Resolved::Unbound, |b| Resolved::Command(b.command.clone()));
145        }
146        if let Some(b) =
147            self.bindings.iter().rev().find(|b| b.keys.len() == 1 && b.keys[0].matches(pressed) && applies(b))
148        {
149            return Resolved::Command(b.command.clone());
150        }
151        if self.bindings.iter().any(|b| b.keys.len() == 2 && b.keys[0].matches(pressed) && applies(b)) {
152            self.pending = Some(pressed.clone());
153            return Resolved::Pending;
154        }
155        Resolved::Unbound
156    }
157
158    pub fn has_pending_chord(&self) -> bool {
159        self.pending.is_some()
160    }
161}
162
163fn keys_to_string(keys: &[KeyPress]) -> String {
164    keys.iter()
165        .map(|k| {
166            let mut s = String::new();
167            for (on, name) in [(k.ctrl, "ctrl+"), (k.shift, "shift+"), (k.alt, "alt+"), (k.meta, "cmd+")] {
168                if on {
169                    s.push_str(name);
170                }
171            }
172            s.push_str(if k.key == " " { "space" } else { &k.key });
173            s
174        })
175        .collect::<Vec<_>>()
176        .join(" ")
177}
178
179/// Evaluates a `when` clause: context keys combined with `!`, `&&` and `||` (`&&` binds
180/// tighter). Unknown keys are false.
181pub fn eval_when(expr: &str, context: &HashMap<String, bool>) -> bool {
182    expr.split("||").any(|conj| {
183        conj.split("&&").all(|term| {
184            let term = term.trim();
185            match term.strip_prefix('!') {
186                Some(key) => !context.get(key.trim()).copied().unwrap_or(false),
187                None => context.get(term).copied().unwrap_or(false),
188            }
189        })
190    })
191}
192
193/// (keys, command, when) for one platform.
194type Entry = (&'static str, &'static str, Option<&'static str>);
195
196const SHARED: &[Entry] = &[
197    ("left", "cursorLeft", None),
198    ("shift+left", "cursorLeftSelect", None),
199    ("right", "cursorRight", None),
200    ("shift+right", "cursorRightSelect", None),
201    ("up", "cursorUp", None),
202    ("shift+up", "cursorUpSelect", None),
203    ("down", "cursorDown", None),
204    ("shift+down", "cursorDownSelect", None),
205    ("pageup", "cursorPageUp", None),
206    ("shift+pageup", "cursorPageUpSelect", None),
207    ("pagedown", "cursorPageDown", None),
208    ("shift+pagedown", "cursorPageDownSelect", None),
209    ("backspace", "deleteLeft", None),
210    ("shift+backspace", "deleteLeft", None),
211    ("delete", "deleteRight", None),
212    ("enter", "editor.action.newline", None),
213    ("shift+enter", "editor.action.newline", None),
214    ("tab", "tab", None),
215    ("shift+tab", "outdent", None),
216    ("escape", "removeSecondaryCursors", Some("editorHasMultipleSelections")),
217    ("escape", "cancelSelection", Some("editorHasSelection && !editorHasMultipleSelections")),
218    ("tab", "jumpToNextSnippetPlaceholder", Some("inSnippetMode")),
219    ("shift+tab", "jumpToPrevSnippetPlaceholder", Some("inSnippetMode")),
220    ("escape", "leaveSnippet", Some("inSnippetMode")),
221    ("ctrl+space", "editor.action.triggerSuggest", None),
222    ("ctrl+shift+space", "editor.action.triggerParameterHints", None),
223    ("f12", "editor.action.revealDefinition", None),
224    ("shift+f12", "editor.action.referenceSearch.trigger", None),
225    ("f2", "editor.action.rename", None),
226    ("shift+alt+f", "editor.action.formatDocument", None),
227    ("alt+up", "editor.action.moveLinesUpAction", None),
228    ("alt+down", "editor.action.moveLinesDownAction", None),
229    ("shift+alt+up", "editor.action.copyLinesUpAction", None),
230    ("shift+alt+down", "editor.action.copyLinesDownAction", None),
231    ("shift+alt+a", "editor.action.blockComment", None),
232    ("shift+alt+right", "editor.action.smartSelect.expand", None),
233    ("shift+alt+left", "editor.action.smartSelect.shrink", None),
234    ("f3", "editor.action.nextMatchFindAction", None),
235    ("shift+f3", "editor.action.previousMatchFindAction", None),
236];
237
238const WINDOWS_LINUX: &[Entry] = &[
239    ("ctrl+left", "cursorWordLeft", None),
240    ("ctrl+shift+left", "cursorWordLeftSelect", None),
241    ("ctrl+right", "cursorWordRight", None),
242    ("ctrl+shift+right", "cursorWordRightSelect", None),
243    ("home", "cursorHome", None),
244    ("shift+home", "cursorHomeSelect", None),
245    ("end", "cursorEnd", None),
246    ("shift+end", "cursorEndSelect", None),
247    ("ctrl+home", "cursorTop", None),
248    ("ctrl+shift+home", "cursorTopSelect", None),
249    ("ctrl+end", "cursorBottom", None),
250    ("ctrl+shift+end", "cursorBottomSelect", None),
251    ("ctrl+backspace", "deleteWordLeft", None),
252    ("ctrl+delete", "deleteWordRight", None),
253    ("ctrl+a", "editor.action.selectAll", None),
254    ("ctrl+z", "undo", None),
255    ("ctrl+y", "redo", None),
256    ("ctrl+shift+z", "redo", None),
257    ("ctrl+enter", "editor.action.insertLineAfter", None),
258    ("ctrl+shift+enter", "editor.action.insertLineBefore", None),
259    ("ctrl+shift+k", "editor.action.deleteLines", None),
260    ("ctrl+/", "editor.action.commentLine", None),
261    ("ctrl+d", "editor.action.addSelectionToNextFindMatch", None),
262    ("ctrl+shift+l", "editor.action.selectHighlights", None),
263    ("ctrl+alt+up", "editor.action.insertCursorAbove", None),
264    ("ctrl+alt+down", "editor.action.insertCursorBelow", None),
265    ("ctrl+k ctrl+x", "editor.action.trimTrailingWhitespace", None),
266    ("ctrl+u", "cursorUndo", None),
267    ("ctrl+shift+\\", "editor.action.jumpToBracket", None),
268    ("ctrl+]", "editor.action.indentLines", None),
269    ("ctrl+[", "editor.action.outdentLines", None),
270    ("ctrl+f", "actions.find", None),
271    ("ctrl+k ctrl+i", "editor.action.showHover", None),
272    ("ctrl+.", "editor.action.quickFix", None),
273    ("ctrl+shift+o", "editor.action.quickOutline", None),
274    ("ctrl+h", "editor.action.startFindReplaceAction", None),
275    ("ctrl+shift+[", "editor.fold", None),
276    ("ctrl+shift+]", "editor.unfold", None),
277    ("ctrl+k ctrl+l", "editor.toggleFold", None),
278    ("ctrl+k ctrl+0", "editor.foldAll", None),
279    ("ctrl+k ctrl+j", "editor.unfoldAll", None),
280];
281
282const MAC: &[Entry] = &[
283    ("alt+left", "cursorWordLeft", None),
284    ("shift+alt+left", "cursorWordLeftSelect", None),
285    ("alt+right", "cursorWordRight", None),
286    ("shift+alt+right", "cursorWordRightSelect", None),
287    ("cmd+left", "cursorHome", None),
288    ("shift+cmd+left", "cursorHomeSelect", None),
289    ("cmd+right", "cursorEnd", None),
290    ("shift+cmd+right", "cursorEndSelect", None),
291    ("home", "cursorHome", None),
292    ("end", "cursorEnd", None),
293    ("cmd+up", "cursorTop", None),
294    ("shift+cmd+up", "cursorTopSelect", None),
295    ("cmd+down", "cursorBottom", None),
296    ("shift+cmd+down", "cursorBottomSelect", None),
297    ("alt+backspace", "deleteWordLeft", None),
298    ("alt+delete", "deleteWordRight", None),
299    ("cmd+a", "editor.action.selectAll", None),
300    ("cmd+z", "undo", None),
301    ("shift+cmd+z", "redo", None),
302    ("cmd+enter", "editor.action.insertLineAfter", None),
303    ("shift+cmd+enter", "editor.action.insertLineBefore", None),
304    ("shift+cmd+k", "editor.action.deleteLines", None),
305    ("cmd+/", "editor.action.commentLine", None),
306    ("cmd+d", "editor.action.addSelectionToNextFindMatch", None),
307    ("shift+cmd+l", "editor.action.selectHighlights", None),
308    ("alt+cmd+up", "editor.action.insertCursorAbove", None),
309    ("alt+cmd+down", "editor.action.insertCursorBelow", None),
310    ("cmd+k cmd+x", "editor.action.trimTrailingWhitespace", None),
311    ("cmd+u", "cursorUndo", None),
312    ("shift+cmd+\\", "editor.action.jumpToBracket", None),
313    ("cmd+]", "editor.action.indentLines", None),
314    ("cmd+[", "editor.action.outdentLines", None),
315    ("cmd+f", "actions.find", None),
316    ("cmd+k cmd+i", "editor.action.showHover", None),
317    ("cmd+.", "editor.action.quickFix", None),
318    ("shift+cmd+o", "editor.action.quickOutline", None),
319    ("alt+cmd+f", "editor.action.startFindReplaceAction", None),
320    ("alt+cmd+[", "editor.fold", None),
321    ("alt+cmd+]", "editor.unfold", None),
322    ("cmd+k cmd+l", "editor.toggleFold", None),
323    ("cmd+k cmd+0", "editor.foldAll", None),
324    ("cmd+k cmd+j", "editor.unfoldAll", None),
325    ("cmd+g", "editor.action.nextMatchFindAction", None),
326    ("shift+cmd+g", "editor.action.previousMatchFindAction", None),
327];
328
329/// JetBrains-style bindings, layered over the default keymap.
330const JETBRAINS: &[Entry] = &[
331    ("ctrl+d", "editor.action.copyLinesDownAction", None),
332    ("ctrl+y", "editor.action.deleteLines", None),
333    ("ctrl+shift+up", "editor.action.moveLinesUpAction", None),
334    ("ctrl+shift+down", "editor.action.moveLinesDownAction", None),
335    ("alt+j", "editor.action.addSelectionToNextFindMatch", None),
336    ("ctrl+shift+alt+j", "editor.action.selectHighlights", None),
337    ("ctrl+shift+u", "editor.action.transformToUppercase", None),
338];
339
340/// The default keymap, following VS Code and Monaco.
341pub fn default_keymap(platform: Platform) -> Keymap {
342    let specific = if platform == Platform::Mac { MAC } else { WINDOWS_LINUX };
343    Keymap::from_entries(SHARED.iter().chain(specific).copied())
344}
345
346/// Bindings modelled on JetBrains IDEs over the default keymap (Windows and Linux keys).
347pub fn jetbrains_keymap(platform: Platform) -> Keymap {
348    let specific = if platform == Platform::Mac { MAC } else { WINDOWS_LINUX };
349    Keymap::from_entries(SHARED.iter().chain(specific).chain(JETBRAINS).copied())
350}
351
352#[cfg(test)]
353mod tests {
354    use super::*;
355
356    fn key(s: &str) -> KeyPress {
357        KeyPress::parse(s).unwrap()
358    }
359
360    fn ctx(pairs: &[(&str, bool)]) -> HashMap<String, bool> {
361        pairs.iter().map(|&(k, v)| (k.to_owned(), v)).collect()
362    }
363
364    #[test]
365    fn parses_keys() {
366        assert_eq!(key("Ctrl+Shift+K"), KeyPress { ctrl: true, shift: true, alt: false, meta: false, key: "k".into() });
367        assert_eq!(key("cmd+up").key, "arrowup");
368        assert_eq!(key("ctrl++").key, "+");
369        assert!(KeyPress::parse("hyper+x").is_none());
370    }
371
372    #[test]
373    fn resolves_single_keys_chords_and_when() {
374        let mut km = default_keymap(Platform::Windows);
375        let none = ctx(&[]);
376        assert_eq!(km.resolve(&key("ctrl+/"), &none), Resolved::Command("editor.action.commentLine".into()));
377        // Shift is ignored for symbol keys: on a German layout `/` is shift+7.
378        assert_eq!(km.resolve(&key("ctrl+shift+/"), &none), Resolved::Command("editor.action.commentLine".into()));
379        assert_eq!(km.resolve(&key("ctrl+k"), &none), Resolved::Pending);
380        // The keydown of Ctrl alone, before the X, keeps the chord pending.
381        assert_eq!(km.resolve(&key("ctrl+control"), &none), Resolved::Unbound);
382        assert_eq!(km.resolve(&key("ctrl+x"), &none), Resolved::Command("editor.action.trimTrailingWhitespace".into()));
383        assert_eq!(km.resolve(&key("escape"), &none), Resolved::Unbound);
384        assert_eq!(
385            km.resolve(&key("escape"), &ctx(&[("editorHasMultipleSelections", true), ("editorHasSelection", true)])),
386            Resolved::Command("removeSecondaryCursors".into())
387        );
388        // Space is not a symbol key: shift tells completion from parameter hints.
389        assert_eq!(km.resolve(&key("ctrl+space"), &none), Resolved::Command("editor.action.triggerSuggest".into()));
390        assert_eq!(
391            km.resolve(&key("ctrl+shift+space"), &none),
392            Resolved::Command("editor.action.triggerParameterHints".into())
393        );
394        // AltGr arrives as ctrl+alt: unbound letters stay free for typing (Polish ą, ę).
395        assert_eq!(km.resolve(&key("ctrl+alt+a"), &none), Resolved::Unbound);
396    }
397
398    #[test]
399    fn later_entries_override_and_minus_removes() {
400        let mut km = default_keymap(Platform::Windows);
401        km.extend([("ctrl+d", "editor.action.copyLinesDownAction", None)]);
402        assert_eq!(
403            km.resolve(&key("ctrl+d"), &ctx(&[])),
404            Resolved::Command("editor.action.copyLinesDownAction".into())
405        );
406        km.extend([("ctrl+d", "-editor.action.copyLinesDownAction", None)]);
407        assert_eq!(
408            km.resolve(&key("ctrl+d"), &ctx(&[])),
409            Resolved::Command("editor.action.addSelectionToNextFindMatch".into())
410        );
411        let mut jb = jetbrains_keymap(Platform::Windows);
412        assert_eq!(jb.resolve(&key("ctrl+y"), &ctx(&[])), Resolved::Command("editor.action.deleteLines".into()));
413    }
414
415    #[test]
416    fn when_clauses() {
417        let c = ctx(&[("a", true), ("b", false)]);
418        assert!(eval_when("a && !b", &c));
419        assert!(eval_when("b || a", &c));
420        assert!(!eval_when("a && b", &c));
421        assert!(!eval_when("unknown", &c));
422    }
423}