Skip to main content

cellix_input/
keymap.rs

1use crate::{Command, Direction, Key, KeyEvent};
2
3/// VS Code-style keys. Returns None for plain characters, which the view inserts.
4pub fn simple_keymap(event: KeyEvent) -> Option<Command> {
5    use Command::*;
6    let KeyEvent { key, mods } = event;
7    let shift = mods.shift;
8    let word = mods.ctrl || mods.alt;
9    Some(match key {
10        Key::Left if word => Move(Direction::WordLeft, shift),
11        Key::Right if word => Move(Direction::WordRight, shift),
12        Key::Left => Move(Direction::Left, shift),
13        Key::Right => Move(Direction::Right, shift),
14        Key::Up if mods.ctrl && mods.alt => AddCursorAbove,
15        Key::Down if mods.ctrl && mods.alt => AddCursorBelow,
16        Key::Down if mods.alt && shift => DuplicateLine,
17        Key::Up if mods.alt => MoveLineUp,
18        Key::Down if mods.alt => MoveLineDown,
19        Key::Up => Move(Direction::Up, shift),
20        Key::Down => Move(Direction::Down, shift),
21        Key::Home if mods.ctrl => Move(Direction::Top, shift),
22        Key::End if mods.ctrl => Move(Direction::Bottom, shift),
23        Key::Home => Move(Direction::LineStart, shift),
24        Key::End => Move(Direction::LineEnd, shift),
25        // Ctrl+PageUp and PageDown change tabs, so with Alt as well they change workspaces.
26        Key::PageUp if mods.ctrl && mods.alt => PreviousWorkspace,
27        Key::PageDown if mods.ctrl && mods.alt => NextWorkspace,
28        Key::PageUp if mods.ctrl => PreviousTab,
29        Key::PageDown if mods.ctrl => NextTab,
30        Key::PageUp => Move(Direction::PageUp, shift),
31        Key::PageDown => Move(Direction::PageDown, shift),
32        Key::Char('`') if mods.ctrl && mods.shift => CloseDock,
33        Key::Char('~') if mods.ctrl => CloseDock,
34        Key::Char('`') if mods.ctrl => FocusAgent,
35        Key::Char('b' | 'B') if mods.ctrl && mods.alt => BuildPdf,
36        // Telling this from Ctrl+B needs the Kitty keyboard protocol.
37        Key::Char('b' | 'B') if mods.ctrl && mods.shift => RunBuildTask,
38        Key::Char('j' | 'J') if mods.ctrl && mods.alt => ShowInPdf,
39        Key::Char('j') if mods.ctrl => ToggleTerminal,
40        Key::Enter if mods.ctrl && shift => InsertLineAbove,
41        Key::Enter if mods.ctrl => InsertLineBelow,
42        Key::Enter => Newline,
43        // Where the terminal tells Ctrl+Tab from Tab, it changes tab as in VS Code.
44        Key::Tab if mods.ctrl => NextTab,
45        Key::BackTab if mods.ctrl => PreviousTab,
46        Key::Tab => Indent,
47        Key::BackTab => Outdent,
48        Key::Backspace if word => DeleteWordLeft,
49        Key::Delete if word => DeleteWordRight,
50        Key::Backspace => DeleteBackward,
51        Key::Delete => DeleteForward,
52        // Before Option+Right below, which is the same letter without Shift.
53        Key::Char('F') if mods.alt => FormatDocument,
54        Key::Char('f') if mods.alt && shift => FormatDocument,
55        // What terminals send for Option+Left and Option+Right.
56        Key::Char('b') if mods.alt => Move(Direction::WordLeft, shift),
57        Key::Char('f') if mods.alt => Move(Direction::WordRight, shift),
58        Key::Char('z' | 'Z') if mods.ctrl && mods.shift => Redo,
59        Key::Char('z' | 'Z') if mods.alt && !mods.ctrl => ToggleWordWrap,
60        // Ctrl+Shift+[ and ], which arrive as the shifted characters too.
61        Key::Char('[' | '{') if mods.ctrl && mods.shift => Fold,
62        Key::Char(']' | '}') if mods.ctrl && mods.shift => Unfold,
63        // Terminals without the Kitty protocol send Ctrl+/ as Ctrl+_ or Ctrl+7.
64        // Ctrl+- and Ctrl+Shift+-, as in VS Code, where the terminal tells them apart.
65        Key::Char('-') if mods.ctrl && !shift => GoBack,
66        Key::Char('_' | '-') if mods.ctrl && shift => GoForward,
67        Key::Char('/' | '_' | '7') if mods.ctrl => ToggleComment,
68        Key::Esc => Cancel,
69        Key::F(1) => CommandPalette,
70        Key::F(2) => RenameSymbol,
71        Key::F(5) if mods.alt && shift => PreviousChange,
72        Key::F(5) if mods.alt => NextChange,
73        Key::F(8) if shift => PreviousProblem,
74        Key::F(8) => NextProblem,
75        Key::F(12) if shift => GoToReferences,
76        Key::F(12) => GoToDefinition,
77        Key::Char(' ') if mods.ctrl => Complete,
78        Key::Char('p') if mods.alt => CommandPalette,
79        Key::Char('c') if mods.alt => AddComment,
80        // As in VS Code. Telling these from Ctrl+P needs the Kitty keyboard protocol.
81        Key::Char('p' | 'P') if mods.ctrl && mods.shift => CommandPalette,
82        Key::Char('f' | 'F') if mods.ctrl && mods.shift => FindInProject,
83        Key::Char('o' | 'O') if mods.ctrl && mods.shift => GoToSymbol,
84        Key::Char('k' | 'K') if mods.ctrl && mods.shift => DeleteLine,
85        Key::Char('l' | 'L') if mods.ctrl && mods.shift => SelectAllMatches,
86        Key::Char(c) if mods.ctrl => match c.to_ascii_lowercase() {
87            // Ghostty sends these for Cmd+Backspace and Cmd+Right, and they're the
88            // Mac's own text shortcuts everywhere else.
89            'l' => GoToLine,
90            'u' => DeleteToLineStart,
91            'k' => DeleteToLineEnd,
92            'e' => Move(Direction::LineEnd, shift),
93            'q' => Quit,
94            's' => Save,
95            'z' => Undo,
96            'y' => Redo,
97            'c' => Copy,
98            'x' => Cut,
99            'v' => Paste,
100            'a' => SelectAll,
101            'd' => SelectNextMatch,
102            'w' => CloseTab,
103            'p' => QuickOpen,
104            't' => GoToWorkspaceSymbol,
105            'f' => FindInFile,
106            // Ctrl+H is Backspace in too many terminals.
107            'r' => ReplaceInFile,
108            'b' => ToggleSidebar,
109            'g' => OpenDiff,
110            // Without the kitty protocol Ctrl+\ arrives as the byte 0x1c, read as Ctrl+4.
111            '\\' | '4' => SplitPane,
112            'o' => FocusNextPane,
113            'n' => NewDocument,
114            '.' => QuickFix,
115            ',' => OpenSettings,
116            ']' => Indent,
117            // Ctrl+[ only arrives as itself with the kitty protocol; elsewhere it's Escape.
118            '[' => Outdent,
119            _ => return None,
120        },
121        _ => return None,
122    })
123}
124
125#[cfg(test)]
126mod tests {
127    use super::*;
128    use crate::Mods;
129
130    #[test]
131    fn vs_codes_everyday_shortcuts_are_here() {
132        let key = |key, ctrl, shift, alt| {
133            simple_keymap(KeyEvent {
134                key,
135                mods: Mods { ctrl, shift, alt },
136            })
137        };
138        let ctrl = |c| key(Key::Char(c), true, false, false);
139        let ctrl_shift = |c| key(Key::Char(c), true, true, false);
140        assert_eq!(ctrl('a'), Some(Command::SelectAll));
141        assert_eq!(ctrl('n'), Some(Command::NewDocument));
142        assert_eq!(ctrl(','), Some(Command::OpenSettings));
143        assert_eq!(ctrl(']'), Some(Command::Indent));
144        assert_eq!(ctrl_shift('K'), Some(Command::DeleteLine));
145        assert_eq!(ctrl_shift('L'), Some(Command::SelectAllMatches));
146        assert_eq!(ctrl_shift('['), Some(Command::Fold));
147        assert_eq!(ctrl_shift('}'), Some(Command::Unfold));
148        assert_eq!(
149            key(Key::Char('z'), false, false, true),
150            Some(Command::ToggleWordWrap)
151        );
152        assert_eq!(ctrl_shift('O'), Some(Command::GoToSymbol));
153        assert_eq!(ctrl('t'), Some(Command::GoToWorkspaceSymbol));
154        assert_eq!(ctrl('o'), Some(Command::FocusNextPane));
155        assert_eq!(
156            key(Key::Enter, true, false, false),
157            Some(Command::InsertLineBelow)
158        );
159        assert_eq!(
160            key(Key::Enter, true, true, false),
161            Some(Command::InsertLineAbove)
162        );
163        assert_eq!(
164            key(Key::Up, true, false, true),
165            Some(Command::AddCursorAbove)
166        );
167        assert_eq!(
168            key(Key::Down, true, false, true),
169            Some(Command::AddCursorBelow)
170        );
171        assert_eq!(
172            key(Key::F(8), false, false, false),
173            Some(Command::NextProblem)
174        );
175        assert_eq!(key(Key::Tab, true, false, false), Some(Command::NextTab));
176        assert_eq!(key(Key::Tab, false, false, false), Some(Command::Indent));
177    }
178
179    #[test]
180    fn ctrl_backslash_splits_in_either_encoding() {
181        let ctrl = |c| KeyEvent {
182            key: Key::Char(c),
183            mods: Mods {
184                ctrl: true,
185                ..Mods::default()
186            },
187        };
188        assert_eq!(simple_keymap(ctrl('\\')), Some(Command::SplitPane));
189        assert_eq!(simple_keymap(ctrl('4')), Some(Command::SplitPane));
190    }
191
192    #[test]
193    fn option_shift_f_formats_and_option_f_still_moves() {
194        let alt = |c, shift| KeyEvent {
195            key: Key::Char(c),
196            mods: Mods {
197                alt: true,
198                shift,
199                ..Mods::default()
200            },
201        };
202        assert_eq!(simple_keymap(alt('F', true)), Some(Command::FormatDocument));
203        assert_eq!(
204            simple_keymap(alt('F', false)),
205            Some(Command::FormatDocument)
206        );
207        assert_eq!(
208            simple_keymap(alt('f', false)),
209            Some(Command::Move(Direction::WordRight, false))
210        );
211    }
212
213    #[test]
214    fn plain_characters_are_text() {
215        assert_eq!(simple_keymap(KeyEvent::plain(Key::Char('s'))), None);
216    }
217
218    #[test]
219    fn ctrl_keys_are_commands() {
220        assert_eq!(simple_keymap(KeyEvent::ctrl('s')), Some(Command::Save));
221    }
222
223    #[test]
224    fn ctrl_p_opens_files_and_ctrl_shift_p_opens_commands() {
225        assert_eq!(simple_keymap(KeyEvent::ctrl('p')), Some(Command::QuickOpen));
226        let event = KeyEvent {
227            key: Key::Char('P'),
228            mods: Mods {
229                ctrl: true,
230                shift: true,
231                ..Mods::default()
232            },
233        };
234        assert_eq!(simple_keymap(event), Some(Command::CommandPalette));
235    }
236
237    #[test]
238    fn mac_text_shortcuts_work() {
239        let alt = |key| KeyEvent {
240            key,
241            mods: Mods {
242                alt: true,
243                ..Mods::default()
244            },
245        };
246        assert_eq!(
247            simple_keymap(alt(Key::Backspace)),
248            Some(Command::DeleteWordLeft)
249        );
250        assert_eq!(
251            simple_keymap(alt(Key::Delete)),
252            Some(Command::DeleteWordRight)
253        );
254        let word_left = Some(Command::Move(Direction::WordLeft, false));
255        assert_eq!(simple_keymap(alt(Key::Char('b'))), word_left);
256        assert_eq!(
257            simple_keymap(KeyEvent::ctrl('u')),
258            Some(Command::DeleteToLineStart)
259        );
260        assert_eq!(simple_keymap(KeyEvent::ctrl('z')), Some(Command::Undo));
261    }
262
263    #[test]
264    fn shift_extends_selection() {
265        let event = KeyEvent {
266            key: Key::Left,
267            mods: Mods {
268                shift: true,
269                ..Mods::default()
270            },
271        };
272        assert_eq!(
273            simple_keymap(event),
274            Some(Command::Move(Direction::Left, true))
275        );
276    }
277}