1use crate::{KeyName, KeySpec};
14
15#[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
53pub 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
134pub 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 (c('c'), Copy),
155 (c('x'), Cut),
156 (c('v'), Paste),
157 (c('f'), Find),
158 (key(KeyName::F(3)), FindNext),
159 (shift_key(KeyName::F(3)), FindPrevious),
160 (c('h'), Replace),
161 (c('g'), GotoLine),
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
180pub 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
187pub 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
195pub 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
203pub 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
211pub 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('c'), 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 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}