1use command_palette::CommandInterceptResult;
2use editor::actions::{SortLinesCaseInsensitive, SortLinesCaseSensitive};
3use gpui::{impl_actions, Action, AppContext, ViewContext};
4use serde_derive::Deserialize;
5use workspace::{SaveIntent, Workspace};
6
7use crate::{
8 motion::{EndOfDocument, Motion, StartOfDocument},
9 normal::{
10 move_cursor,
11 search::{FindCommand, ReplaceCommand},
12 JoinLines,
13 },
14 state::Mode,
15 Vim,
16};
17
18#[derive(Debug, Clone, PartialEq, Deserialize)]
19pub struct GoToLine {
20 pub line: u32,
21}
22
23impl_actions!(vim, [GoToLine]);
24
25pub fn register(workspace: &mut Workspace, _: &mut ViewContext<Workspace>) {
26 workspace.register_action(|_: &mut Workspace, action: &GoToLine, cx| {
27 Vim::update(cx, |vim, cx| {
28 vim.switch_mode(Mode::Normal, false, cx);
29 move_cursor(vim, Motion::StartOfDocument, Some(action.line as usize), cx);
30 });
31 });
32}
33
34pub fn command_interceptor(mut query: &str, cx: &AppContext) -> Option<CommandInterceptResult> {
35 // Note: this is a very poor simulation of vim's command palette.
36 // In the future we should adjust it to handle parsing range syntax,
37 // and then calling the appropriate commands with/without ranges.
38 //
39 // We also need to support passing arguments to commands like :w
40 // (ideally with filename autocompletion).
41 //
42 // For now, you can only do a replace on the % range, and you can
43 // only use a specific line number range to "go to line"
44 while query.starts_with(":") {
45 query = &query[1..];
46 }
47
48 let (name, action) = match query {
49 // save and quit
50 "w" | "wr" | "wri" | "writ" | "write" => (
51 "write",
52 workspace::Save {
53 save_intent: Some(SaveIntent::Save),
54 }
55 .boxed_clone(),
56 ),
57 "w!" | "wr!" | "wri!" | "writ!" | "write!" => (
58 "write!",
59 workspace::Save {
60 save_intent: Some(SaveIntent::Overwrite),
61 }
62 .boxed_clone(),
63 ),
64 "q" | "qu" | "qui" | "quit" => (
65 "quit",
66 workspace::CloseActiveItem {
67 save_intent: Some(SaveIntent::Close),
68 }
69 .boxed_clone(),
70 ),
71 "q!" | "qu!" | "qui!" | "quit!" => (
72 "quit!",
73 workspace::CloseActiveItem {
74 save_intent: Some(SaveIntent::Skip),
75 }
76 .boxed_clone(),
77 ),
78 "wq" => (
79 "wq",
80 workspace::CloseActiveItem {
81 save_intent: Some(SaveIntent::Save),
82 }
83 .boxed_clone(),
84 ),
85 "wq!" => (
86 "wq!",
87 workspace::CloseActiveItem {
88 save_intent: Some(SaveIntent::Overwrite),
89 }
90 .boxed_clone(),
91 ),
92 "x" | "xi" | "xit" | "exi" | "exit" => (
93 "exit",
94 workspace::CloseActiveItem {
95 save_intent: Some(SaveIntent::SaveAll),
96 }
97 .boxed_clone(),
98 ),
99 "x!" | "xi!" | "xit!" | "exi!" | "exit!" => (
100 "exit!",
101 workspace::CloseActiveItem {
102 save_intent: Some(SaveIntent::Overwrite),
103 }
104 .boxed_clone(),
105 ),
106 "up" | "upd" | "upda" | "updat" | "update" => (
107 "update",
108 workspace::Save {
109 save_intent: Some(SaveIntent::SaveAll),
110 }
111 .boxed_clone(),
112 ),
113 "wa" | "wal" | "wall" => (
114 "wall",
115 workspace::SaveAll {
116 save_intent: Some(SaveIntent::SaveAll),
117 }
118 .boxed_clone(),
119 ),
120 "wa!" | "wal!" | "wall!" => (
121 "wall!",
122 workspace::SaveAll {
123 save_intent: Some(SaveIntent::Overwrite),
124 }
125 .boxed_clone(),
126 ),
127 "qa" | "qal" | "qall" | "quita" | "quital" | "quitall" => (
128 "quitall",
129 workspace::CloseAllItemsAndPanes {
130 save_intent: Some(SaveIntent::Close),
131 }
132 .boxed_clone(),
133 ),
134 "qa!" | "qal!" | "qall!" | "quita!" | "quital!" | "quitall!" => (
135 "quitall!",
136 workspace::CloseAllItemsAndPanes {
137 save_intent: Some(SaveIntent::Skip),
138 }
139 .boxed_clone(),
140 ),
141 "xa" | "xal" | "xall" => (
142 "xall",
143 workspace::CloseAllItemsAndPanes {
144 save_intent: Some(SaveIntent::SaveAll),
145 }
146 .boxed_clone(),
147 ),
148 "xa!" | "xal!" | "xall!" => (
149 "xall!",
150 workspace::CloseAllItemsAndPanes {
151 save_intent: Some(SaveIntent::Overwrite),
152 }
153 .boxed_clone(),
154 ),
155 "wqa" | "wqal" | "wqall" => (
156 "wqall",
157 workspace::CloseAllItemsAndPanes {
158 save_intent: Some(SaveIntent::SaveAll),
159 }
160 .boxed_clone(),
161 ),
162 "wqa!" | "wqal!" | "wqall!" => (
163 "wqall!",
164 workspace::CloseAllItemsAndPanes {
165 save_intent: Some(SaveIntent::Overwrite),
166 }
167 .boxed_clone(),
168 ),
169 "cq" | "cqu" | "cqui" | "cquit" | "cq!" | "cqu!" | "cqui!" | "cquit!" => {
170 ("cquit!", zed_actions::Quit.boxed_clone())
171 }
172
173 // pane management
174 "sp" | "spl" | "spli" | "split" => ("split", workspace::SplitUp.boxed_clone()),
175 "vs" | "vsp" | "vspl" | "vspli" | "vsplit" => {
176 ("vsplit", workspace::SplitLeft.boxed_clone())
177 }
178 "new" => (
179 "new",
180 workspace::NewFileInDirection(workspace::SplitDirection::Up).boxed_clone(),
181 ),
182 "vne" | "vnew" => (
183 "vnew",
184 workspace::NewFileInDirection(workspace::SplitDirection::Left).boxed_clone(),
185 ),
186 "tabe" | "tabed" | "tabedi" | "tabedit" => ("tabedit", workspace::NewFile.boxed_clone()),
187 "tabnew" => ("tabnew", workspace::NewFile.boxed_clone()),
188
189 "tabn" | "tabne" | "tabnex" | "tabnext" => {
190 ("tabnext", workspace::ActivateNextItem.boxed_clone())
191 }
192 "tabp" | "tabpr" | "tabpre" | "tabprev" | "tabprevi" | "tabprevio" | "tabpreviou"
193 | "tabprevious" => ("tabprevious", workspace::ActivatePrevItem.boxed_clone()),
194 "tabN" | "tabNe" | "tabNex" | "tabNext" => {
195 ("tabNext", workspace::ActivatePrevItem.boxed_clone())
196 }
197 "tabc" | "tabcl" | "tabclo" | "tabclos" | "tabclose" => (
198 "tabclose",
199 workspace::CloseActiveItem {
200 save_intent: Some(SaveIntent::Close),
201 }
202 .boxed_clone(),
203 ),
204
205 // quickfix / loclist (merged together for now)
206 "cl" | "cli" | "clis" | "clist" => (
207 "clist",
208 cx.build_action("diagnostics::Deploy", None).unwrap(),
209 ),
210 "cc" => ("cc", editor::actions::Hover.boxed_clone()),
211 "ll" => ("ll", editor::actions::Hover.boxed_clone()),
212 "cn" | "cne" | "cnex" | "cnext" => ("cnext", editor::actions::GoToDiagnostic.boxed_clone()),
213 "lne" | "lnex" | "lnext" => ("cnext", editor::actions::GoToDiagnostic.boxed_clone()),
214
215 "cpr" | "cpre" | "cprev" | "cprevi" | "cprevio" | "cpreviou" | "cprevious" => (
216 "cprevious",
217 editor::actions::GoToPrevDiagnostic.boxed_clone(),
218 ),
219 "cN" | "cNe" | "cNex" | "cNext" => {
220 ("cNext", editor::actions::GoToPrevDiagnostic.boxed_clone())
221 }
222 "lp" | "lpr" | "lpre" | "lprev" | "lprevi" | "lprevio" | "lpreviou" | "lprevious" => (
223 "lprevious",
224 editor::actions::GoToPrevDiagnostic.boxed_clone(),
225 ),
226 "lN" | "lNe" | "lNex" | "lNext" => {
227 ("lNext", editor::actions::GoToPrevDiagnostic.boxed_clone())
228 }
229
230 // modify the buffer (should accept [range])
231 "j" | "jo" | "joi" | "join" => ("join", JoinLines.boxed_clone()),
232 "d" | "de" | "del" | "dele" | "delet" | "delete" | "dl" | "dell" | "delel" | "deletl"
233 | "deletel" | "dp" | "dep" | "delp" | "delep" | "deletp" | "deletep" => {
234 ("delete", editor::actions::DeleteLine.boxed_clone())
235 }
236 "sor" | "sor " | "sort" | "sort " => ("sort", SortLinesCaseSensitive.boxed_clone()),
237 "sor i" | "sort i" => ("sort i", SortLinesCaseInsensitive.boxed_clone()),
238
239 // Explore, etc.
240 "E" | "Ex" | "Exp" | "Expl" | "Explo" | "Explor" | "Explore" => (
241 "Explore",
242 cx.build_action("project_panel::ToggleFocus", None).unwrap(),
243 ),
244 "H" | "He" | "Hex" | "Hexp" | "Hexpl" | "Hexplo" | "Hexplor" | "Hexplore" => (
245 "Hexplore",
246 cx.build_action("project_panel::ToggleFocus", None).unwrap(),
247 ),
248 "L" | "Le" | "Lex" | "Lexp" | "Lexpl" | "Lexplo" | "Lexplor" | "Lexplore" => (
249 "Lexplore",
250 cx.build_action("project_panel::ToggleFocus", None).unwrap(),
251 ),
252 "S" | "Se" | "Sex" | "Sexp" | "Sexpl" | "Sexplo" | "Sexplor" | "Sexplore" => (
253 "Sexplore",
254 cx.build_action("project_panel::ToggleFocus", None).unwrap(),
255 ),
256 "Ve" | "Vex" | "Vexp" | "Vexpl" | "Vexplo" | "Vexplor" | "Vexplore" => (
257 "Vexplore",
258 cx.build_action("project_panel::ToggleFocus", None).unwrap(),
259 ),
260 "te" | "ter" | "term" => (
261 "term",
262 cx.build_action("terminal_panel::ToggleFocus", None)
263 .unwrap(),
264 ),
265 // Zed panes
266 "T" | "Te" | "Ter" | "Term" => (
267 "Term",
268 cx.build_action("terminal_panel::ToggleFocus", None)
269 .unwrap(),
270 ),
271 "C" | "Co" | "Col" | "Coll" | "Colla" | "Collab" => (
272 "Collab",
273 cx.build_action("collab_panel::ToggleFocus", None).unwrap(),
274 ),
275 "Ch" | "Cha" | "Chat" => (
276 "Chat",
277 cx.build_action("chat_panel::ToggleFocus", None).unwrap(),
278 ),
279 "No" | "Not" | "Noti" | "Notif" | "Notifi" | "Notific" | "Notifica" | "Notificat"
280 | "Notificati" | "Notificatio" | "Notification" => (
281 "Notifications",
282 cx.build_action("notification_panel::ToggleFocus", None)
283 .unwrap(),
284 ),
285 "A" | "AI" | "Ai" => (
286 "AI",
287 cx.build_action("assistant::ToggleFocus", None).unwrap(),
288 ),
289
290 // goto (other ranges handled under _ => )
291 "$" => ("$", EndOfDocument.boxed_clone()),
292 "%" => ("%", EndOfDocument.boxed_clone()),
293 "0" => ("0", StartOfDocument.boxed_clone()),
294
295 _ => {
296 if query.starts_with("/") || query.starts_with("?") {
297 (
298 query,
299 FindCommand {
300 query: query[1..].to_string(),
301 backwards: query.starts_with("?"),
302 }
303 .boxed_clone(),
304 )
305 } else if query.starts_with("%") {
306 (
307 query,
308 ReplaceCommand {
309 query: query.to_string(),
310 }
311 .boxed_clone(),
312 )
313 } else if let Ok(line) = query.parse::<u32>() {
314 (query, GoToLine { line }.boxed_clone())
315 } else {
316 return None;
317 }
318 }
319 };
320
321 let string = ":".to_owned() + name;
322 let positions = generate_positions(&string, query);
323
324 Some(CommandInterceptResult {
325 action,
326 string,
327 positions,
328 })
329}
330
331fn generate_positions(string: &str, query: &str) -> Vec<usize> {
332 let mut positions = Vec::new();
333 let mut chars = query.chars().into_iter();
334
335 let Some(mut current) = chars.next() else {
336 return positions;
337 };
338
339 for (i, c) in string.char_indices() {
340 if c == current {
341 positions.push(i);
342 if let Some(c) = chars.next() {
343 current = c;
344 } else {
345 break;
346 }
347 }
348 }
349
350 positions
351}
352
353#[cfg(test)]
354mod test {
355 use std::path::Path;
356
357 use crate::test::{NeovimBackedTestContext, VimTestContext};
358 use gpui::TestAppContext;
359 use indoc::indoc;
360
361 #[gpui::test]
362 async fn test_command_basics(cx: &mut TestAppContext) {
363 let mut cx = NeovimBackedTestContext::new(cx).await;
364
365 cx.set_shared_state(indoc! {"
366 ˇa
367 b
368 c"})
369 .await;
370
371 cx.simulate_shared_keystrokes([":", "j", "enter"]).await;
372
373 // hack: our cursor positionining after a join command is wrong
374 cx.simulate_shared_keystrokes(["^"]).await;
375 cx.assert_shared_state(indoc! {
376 "ˇa b
377 c"
378 })
379 .await;
380 }
381
382 #[gpui::test]
383 async fn test_command_goto(cx: &mut TestAppContext) {
384 let mut cx = NeovimBackedTestContext::new(cx).await;
385
386 cx.set_shared_state(indoc! {"
387 ˇa
388 b
389 c"})
390 .await;
391 cx.simulate_shared_keystrokes([":", "3", "enter"]).await;
392 cx.assert_shared_state(indoc! {"
393 a
394 b
395 ˇc"})
396 .await;
397 }
398
399 #[gpui::test]
400 async fn test_command_replace(cx: &mut TestAppContext) {
401 let mut cx = NeovimBackedTestContext::new(cx).await;
402
403 cx.set_shared_state(indoc! {"
404 ˇa
405 b
406 c"})
407 .await;
408 cx.simulate_shared_keystrokes([":", "%", "s", "/", "b", "/", "d", "enter"])
409 .await;
410 cx.assert_shared_state(indoc! {"
411 a
412 ˇd
413 c"})
414 .await;
415 cx.simulate_shared_keystrokes([
416 ":", "%", "s", ":", ".", ":", "\\", "0", "\\", "0", "enter",
417 ])
418 .await;
419 cx.assert_shared_state(indoc! {"
420 aa
421 dd
422 ˇcc"})
423 .await;
424 }
425
426 #[gpui::test]
427 async fn test_command_search(cx: &mut TestAppContext) {
428 let mut cx = NeovimBackedTestContext::new(cx).await;
429
430 cx.set_shared_state(indoc! {"
431 ˇa
432 b
433 a
434 c"})
435 .await;
436 cx.simulate_shared_keystrokes([":", "/", "b", "enter"])
437 .await;
438 cx.assert_shared_state(indoc! {"
439 a
440 ˇb
441 a
442 c"})
443 .await;
444 cx.simulate_shared_keystrokes([":", "?", "a", "enter"])
445 .await;
446 cx.assert_shared_state(indoc! {"
447 ˇa
448 b
449 a
450 c"})
451 .await;
452 }
453
454 #[gpui::test]
455 async fn test_command_write(cx: &mut TestAppContext) {
456 let mut cx = VimTestContext::new(cx, true).await;
457 let path = Path::new("/root/dir/file.rs");
458 let fs = cx.workspace(|workspace, cx| workspace.project().read(cx).fs().clone());
459
460 cx.simulate_keystrokes(["i", "@", "escape"]);
461 cx.simulate_keystrokes([":", "w", "enter"]);
462
463 assert_eq!(fs.load(&path).await.unwrap(), "@\n");
464
465 fs.as_fake()
466 .write_file_internal(path, "oops\n".to_string())
467 .unwrap();
468
469 // conflict!
470 cx.simulate_keystrokes(["i", "@", "escape"]);
471 cx.simulate_keystrokes([":", "w", "enter"]);
472 assert!(cx.has_pending_prompt());
473 // "Cancel"
474 cx.simulate_prompt_answer(0);
475 assert_eq!(fs.load(&path).await.unwrap(), "oops\n");
476 assert!(!cx.has_pending_prompt());
477 // force overwrite
478 cx.simulate_keystrokes([":", "w", "!", "enter"]);
479 assert!(!cx.has_pending_prompt());
480 assert_eq!(fs.load(&path).await.unwrap(), "@@\n");
481 }
482
483 #[gpui::test]
484 async fn test_command_quit(cx: &mut TestAppContext) {
485 let mut cx = VimTestContext::new(cx, true).await;
486
487 cx.simulate_keystrokes([":", "n", "e", "w", "enter"]);
488 cx.workspace(|workspace, cx| assert_eq!(workspace.items(cx).count(), 2));
489 cx.simulate_keystrokes([":", "q", "enter"]);
490 cx.workspace(|workspace, cx| assert_eq!(workspace.items(cx).count(), 1));
491 cx.simulate_keystrokes([":", "n", "e", "w", "enter"]);
492 cx.workspace(|workspace, cx| assert_eq!(workspace.items(cx).count(), 2));
493 cx.simulate_keystrokes([":", "q", "a", "enter"]);
494 cx.workspace(|workspace, cx| assert_eq!(workspace.items(cx).count(), 0));
495 }
496}