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        (c('c'), Copy),
154        (c('x'), Cut),
155        (c('v'), Paste),
156        (c('f'), Find),
157        (key(KeyName::F(3)), FindNext),
158        (shift_key(KeyName::F(3)), FindPrevious),
159        (c('h'), Replace),
160        (c('g'), GotoLine),
161        (cs('p'), CommandPalette),
162        (c('p'), FileFinder),
163        (c('l'), LanguagePicker),
164        (c('b'), ToggleSidebar),
165        (a('c'), ToggleConsole),
166        (a('t'), ToggleTheme),
167        (key(KeyName::F(1)), Help),
168        (c('e'), Repl),
169        (c('/'), ToggleComment),
170        (shift_key(KeyName::Up), AddCursorAbove),
171        (shift_key(KeyName::Down), AddCursorBelow),
172        (c('d'), SelectNextOccurrence),
173        (KeySpec::new(KeyName::Tab, true, false, false), NextBuffer),
174        (KeySpec::new(KeyName::Tab, true, false, true), PrevBuffer),
175        (cs('i'), Format),
176        (cs('d'), DuplicateLine),
177    ]
178}
179
180/// The binding in `default_bindings()` for this key, if any.
181pub fn command_for(key: KeySpec) -> Option<EditorCommand> {
182    default_bindings()
183        .into_iter()
184        .find_map(|(candidate, command)| (candidate == key).then_some(command))
185}
186
187/// The stable id of a command (`"save"`, `"file_finder"`).
188pub fn command_id(command: EditorCommand) -> &'static str {
189    COMMANDS
190        .iter()
191        .find_map(|(candidate, id, _)| (*candidate == command).then_some(*id))
192        .unwrap_or("unknown")
193}
194
195/// A command's human title (`"Save As…"`).
196pub fn command_title(command: EditorCommand) -> &'static str {
197    COMMANDS
198        .iter()
199        .find_map(|(candidate, _, title)| (*candidate == command).then_some(*title))
200        .unwrap_or("Unknown")
201}
202
203/// Resolves a stable id or a human title (case- and separator-insensitive).
204pub fn command_from_name(name: &str) -> Option<EditorCommand> {
205    let wanted = normalize(name);
206    COMMANDS.iter().find_map(|(command, id, title)| {
207        (normalize(id) == wanted || normalize(title) == wanted).then_some(*command)
208    })
209}
210
211/// The display spelling of a command's default binding, e.g. `Ctrl+P`.
212pub fn default_shortcut(command: EditorCommand) -> Option<String> {
213    default_bindings()
214        .into_iter()
215        .find_map(|(key, candidate)| (candidate == command).then(|| key.display()))
216}
217
218fn normalize(text: &str) -> String {
219    text.trim()
220        .to_ascii_lowercase()
221        .replace(['_', '-', ' ', '…'], "")
222}
223
224#[cfg(test)]
225mod tests {
226    use super::*;
227
228    #[test]
229    fn important_commands_are_bound() {
230        let finder = KeySpec::new(KeyName::Char('p'), true, false, false);
231        assert_eq!(command_for(finder), Some(EditorCommand::FileFinder));
232        let palette = KeySpec::new(KeyName::Char('p'), true, false, true);
233        assert_eq!(command_for(palette), Some(EditorCommand::CommandPalette));
234        assert_eq!(
235            command_for(KeySpec::parse("ctrl+s").unwrap()),
236            Some(EditorCommand::Save)
237        );
238        assert_eq!(
239            command_for(KeySpec::parse("alt+c").unwrap()),
240            Some(EditorCommand::ToggleConsole)
241        );
242    }
243
244    #[test]
245    fn ids_and_titles_resolve_to_the_same_command() {
246        for (command, id, title) in COMMANDS {
247            assert_eq!(command_from_name(id), Some(*command), "{id}");
248            assert_eq!(command_from_name(title), Some(*command), "{title}");
249            assert_eq!(command_id(*command), *id);
250            assert_eq!(command_title(*command), *title);
251        }
252    }
253
254    #[test]
255    fn every_command_has_a_unique_id_and_title() {
256        let mut ids: Vec<&str> = COMMANDS.iter().map(|(_, id, _)| *id).collect();
257        ids.sort_unstable();
258        ids.dedup();
259        assert_eq!(ids.len(), COMMANDS.len());
260        let mut titles: Vec<&str> = COMMANDS.iter().map(|(_, _, title)| *title).collect();
261        titles.sort_unstable();
262        titles.dedup();
263        assert_eq!(titles.len(), COMMANDS.len());
264    }
265
266    #[test]
267    fn most_commands_have_a_shortcut() {
268        let missing: Vec<&str> = COMMANDS
269            .iter()
270            .filter(|(command, _, _)| default_shortcut(*command).is_none())
271            .map(|(_, id, _)| *id)
272            .collect();
273        // Prev/next buffer intentionally share Ctrl+Tab with Shift as a prefix
274        // on some terminals, and Format/Duplicate have alternates.
275        assert!(missing.len() <= 3, "unbound commands: {missing:?}");
276    }
277
278    #[test]
279    fn no_key_is_bound_twice() {
280        let mut keys: Vec<String> = default_bindings()
281            .iter()
282            .map(|(key, _)| key.display())
283            .collect();
284        keys.sort();
285        let before = keys.len();
286        keys.dedup();
287        assert_eq!(before, keys.len());
288    }
289
290    #[test]
291    fn shortcut_display_uses_the_canonical_spelling() {
292        assert_eq!(
293            default_shortcut(EditorCommand::FileFinder).as_deref(),
294            Some("Ctrl+P")
295        );
296        assert_eq!(
297            default_shortcut(EditorCommand::ToggleTheme).as_deref(),
298            Some("Alt+T")
299        );
300    }
301}