Skip to main content

fast_text_plugin/
keymap.rs

1//! The shared editing keymap.
2//!
3//! Every frontend (terminal, desktop, web) resolves a key press through the
4//! same [`EditorCommand`] table, so `Ctrl+S` saves and `Ctrl+P` opens the fuzzy
5//! file finder whether you are in a terminal, a native window or a browser.
6//! Frontends translate their native key event into a [`KeySpec`] and call
7//! [`command_for`]; user configuration can then override any binding by name.
8//!
9//! The table deliberately avoids `Cmd` as a separate modifier: the desktop and
10//! web frontends translate `Cmd`/`Super` to [`KeySpec::ctrl`], which gives macOS
11//! users the conventional Cmd shortcuts without a second set of bindings.
12
13use crate::{KeyName, KeySpec};
14
15/// An editor command that every frontend understands.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17pub enum EditorCommand {
18    Save,
19    SaveAs,
20    Open,
21    New,
22    Close,
23    Quit,
24    Undo,
25    Redo,
26    SelectAll,
27    Copy,
28    Cut,
29    Paste,
30    Find,
31    FindNext,
32    FindPrevious,
33    Replace,
34    GotoLine,
35    CommandPalette,
36    FileFinder,
37    LanguagePicker,
38    ToggleSidebar,
39    ToggleConsole,
40    ToggleTheme,
41    Help,
42    Repl,
43    ToggleComment,
44    AddCursorAbove,
45    AddCursorBelow,
46    SelectNextOccurrence,
47    NextBuffer,
48    PrevBuffer,
49    Format,
50    DuplicateLine,
51}
52
53/// Every command, with its stable id, human title and default binding.
54///
55/// The id is what `config.toml` and plugins use (`"save"`, `"file_finder"`),
56/// while the title is what command palettes display. Keeping both makes the
57/// mapping stable across releases even if a title is reworded.
58pub const COMMANDS: &[(EditorCommand, &str, &str)] = &[
59    (EditorCommand::Save, "save", "Save"),
60    (EditorCommand::SaveAs, "save_as", "Save As…"),
61    (EditorCommand::Open, "open", "Open File…"),
62    (EditorCommand::New, "new", "New Buffer"),
63    (EditorCommand::Close, "close", "Close Buffer"),
64    (EditorCommand::Quit, "quit", "Quit"),
65    (EditorCommand::Undo, "undo", "Undo"),
66    (EditorCommand::Redo, "redo", "Redo"),
67    (EditorCommand::SelectAll, "select_all", "Select All"),
68    (EditorCommand::Copy, "copy", "Copy"),
69    (EditorCommand::Cut, "cut", "Cut"),
70    (EditorCommand::Paste, "paste", "Paste"),
71    (EditorCommand::Find, "find", "Find…"),
72    (EditorCommand::FindNext, "find_next", "Find Next"),
73    (
74        EditorCommand::FindPrevious,
75        "find_previous",
76        "Find Previous",
77    ),
78    (EditorCommand::Replace, "replace", "Replace…"),
79    (EditorCommand::GotoLine, "goto_line", "Go to Line…"),
80    (
81        EditorCommand::CommandPalette,
82        "command_palette",
83        "Command Palette…",
84    ),
85    (EditorCommand::FileFinder, "file_finder", "Go to File…"),
86    (
87        EditorCommand::LanguagePicker,
88        "language",
89        "Change Language…",
90    ),
91    (
92        EditorCommand::ToggleSidebar,
93        "toggle_sidebar",
94        "Toggle Sidebar",
95    ),
96    (
97        EditorCommand::ToggleConsole,
98        "toggle_console",
99        "Toggle Terminal",
100    ),
101    (EditorCommand::ToggleTheme, "toggle_theme", "Toggle Theme"),
102    (EditorCommand::Help, "help", "Keyboard Shortcuts"),
103    (EditorCommand::Repl, "repl", "TextWrite REPL…"),
104    (
105        EditorCommand::ToggleComment,
106        "toggle_comment",
107        "Toggle Comment",
108    ),
109    (
110        EditorCommand::AddCursorAbove,
111        "cursor_above",
112        "Add Cursor Above",
113    ),
114    (
115        EditorCommand::AddCursorBelow,
116        "cursor_below",
117        "Add Cursor Below",
118    ),
119    (
120        EditorCommand::SelectNextOccurrence,
121        "select_next_occurrence",
122        "Select Next Occurrence",
123    ),
124    (EditorCommand::NextBuffer, "next_buffer", "Next Buffer"),
125    (EditorCommand::PrevBuffer, "prev_buffer", "Previous Buffer"),
126    (EditorCommand::Format, "format", "Format Document"),
127    (
128        EditorCommand::DuplicateLine,
129        "duplicate_line",
130        "Duplicate Line",
131    ),
132];
133
134/// The default key bindings, in table order.
135pub fn default_bindings() -> Vec<(KeySpec, EditorCommand)> {
136    use EditorCommand::*;
137    let c = |ch: char| KeySpec::new(KeyName::Char(ch), true, false, false);
138    let cs = |ch: char| KeySpec::new(KeyName::Char(ch), true, false, true);
139    let a = |ch: char| KeySpec::new(KeyName::Char(ch), false, true, false);
140    let key = |name| KeySpec::new(name, false, false, false);
141    let shift_key = |name| KeySpec::new(name, false, false, true);
142    vec![
143        (c('s'), Save),
144        (cs('s'), SaveAs),
145        (c('o'), Open),
146        (c('n'), New),
147        (c('w'), Close),
148        (c('q'), Quit),
149        (c('z'), Undo),
150        (cs('z'), Redo),
151        (c('y'), Redo),
152        (c('a'), SelectAll),
153        (cs('c'), CommandPalette),
154        (cs('p'), CommandPalette),
155        (c('c'), Copy),
156        (c('x'), Cut),
157        (c('v'), Paste),
158        (c('f'), Find),
159        (key(KeyName::F(3)), FindNext),
160        (shift_key(KeyName::F(3)), FindPrevious),
161        (c('h'), Replace),
162        (c('g'), GotoLine),
163        (c('p'), FileFinder),
164        (c('l'), LanguagePicker),
165        (c('b'), ToggleSidebar),
166        (a('c'), ToggleConsole),
167        (a('t'), ToggleTheme),
168        (key(KeyName::F(1)), Help),
169        (c('e'), Repl),
170        (c('/'), ToggleComment),
171        (shift_key(KeyName::Up), AddCursorAbove),
172        (shift_key(KeyName::Down), AddCursorBelow),
173        (c('d'), SelectNextOccurrence),
174        (KeySpec::new(KeyName::Tab, true, false, false), NextBuffer),
175        (KeySpec::new(KeyName::Tab, true, false, true), PrevBuffer),
176        (cs('i'), Format),
177        (cs('d'), DuplicateLine),
178    ]
179}
180
181/// The binding in `default_bindings()` for this key, if any.
182pub fn command_for(key: KeySpec) -> Option<EditorCommand> {
183    default_bindings()
184        .into_iter()
185        .find_map(|(candidate, command)| (candidate == key).then_some(command))
186}
187
188/// The stable id of a command (`"save"`, `"file_finder"`).
189pub fn command_id(command: EditorCommand) -> &'static str {
190    COMMANDS
191        .iter()
192        .find_map(|(candidate, id, _)| (*candidate == command).then_some(*id))
193        .unwrap_or("unknown")
194}
195
196/// A command's human title (`"Save As…"`).
197pub fn command_title(command: EditorCommand) -> &'static str {
198    COMMANDS
199        .iter()
200        .find_map(|(candidate, _, title)| (*candidate == command).then_some(*title))
201        .unwrap_or("Unknown")
202}
203
204/// Resolves a stable id or a human title (case- and separator-insensitive).
205pub fn command_from_name(name: &str) -> Option<EditorCommand> {
206    let wanted = normalize(name);
207    COMMANDS.iter().find_map(|(command, id, title)| {
208        (normalize(id) == wanted || normalize(title) == wanted).then_some(*command)
209    })
210}
211
212/// The display spelling of a command's default binding, e.g. `Ctrl+P`.
213pub fn default_shortcut(command: EditorCommand) -> Option<String> {
214    default_bindings()
215        .into_iter()
216        .find_map(|(key, candidate)| (candidate == command).then(|| key.display()))
217}
218
219fn normalize(text: &str) -> String {
220    text.trim()
221        .to_ascii_lowercase()
222        .replace(['_', '-', ' ', '…'], "")
223}
224
225#[cfg(test)]
226mod tests {
227    use super::*;
228
229    #[test]
230    fn important_commands_are_bound() {
231        let finder = KeySpec::new(KeyName::Char('p'), true, false, false);
232        assert_eq!(command_for(finder), Some(EditorCommand::FileFinder));
233        let palette = KeySpec::new(KeyName::Char('c'), true, false, true);
234        assert_eq!(command_for(palette), Some(EditorCommand::CommandPalette));
235        let palette_alt = KeySpec::new(KeyName::Char('p'), true, false, true);
236        assert_eq!(
237            command_for(palette_alt),
238            Some(EditorCommand::CommandPalette)
239        );
240        assert_eq!(
241            command_for(KeySpec::parse("ctrl+s").unwrap()),
242            Some(EditorCommand::Save)
243        );
244        assert_eq!(
245            command_for(KeySpec::parse("alt+c").unwrap()),
246            Some(EditorCommand::ToggleConsole)
247        );
248    }
249
250    #[test]
251    fn ids_and_titles_resolve_to_the_same_command() {
252        for (command, id, title) in COMMANDS {
253            assert_eq!(command_from_name(id), Some(*command), "{id}");
254            assert_eq!(command_from_name(title), Some(*command), "{title}");
255            assert_eq!(command_id(*command), *id);
256            assert_eq!(command_title(*command), *title);
257        }
258    }
259
260    #[test]
261    fn every_command_has_a_unique_id_and_title() {
262        let mut ids: Vec<&str> = COMMANDS.iter().map(|(_, id, _)| *id).collect();
263        ids.sort_unstable();
264        ids.dedup();
265        assert_eq!(ids.len(), COMMANDS.len());
266        let mut titles: Vec<&str> = COMMANDS.iter().map(|(_, _, title)| *title).collect();
267        titles.sort_unstable();
268        titles.dedup();
269        assert_eq!(titles.len(), COMMANDS.len());
270    }
271
272    #[test]
273    fn most_commands_have_a_shortcut() {
274        let missing: Vec<&str> = COMMANDS
275            .iter()
276            .filter(|(command, _, _)| default_shortcut(*command).is_none())
277            .map(|(_, id, _)| *id)
278            .collect();
279        // Prev/next buffer intentionally share Ctrl+Tab with Shift as a prefix
280        // on some terminals, and Format/Duplicate have alternates.
281        assert!(missing.len() <= 3, "unbound commands: {missing:?}");
282    }
283
284    #[test]
285    fn no_key_is_bound_twice() {
286        let mut keys: Vec<String> = default_bindings()
287            .iter()
288            .map(|(key, _)| key.display())
289            .collect();
290        keys.sort();
291        let before = keys.len();
292        keys.dedup();
293        assert_eq!(before, keys.len());
294    }
295
296    #[test]
297    fn shortcut_display_uses_the_canonical_spelling() {
298        assert_eq!(
299            default_shortcut(EditorCommand::FileFinder).as_deref(),
300            Some("Ctrl+P")
301        );
302        assert_eq!(
303            default_shortcut(EditorCommand::ToggleTheme).as_deref(),
304            Some("Alt+T")
305        );
306    }
307}