command.rs

  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, _: &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" => ("clist", diagnostics::Deploy.boxed_clone()),
207        "cc" => ("cc", editor::actions::Hover.boxed_clone()),
208        "ll" => ("ll", editor::actions::Hover.boxed_clone()),
209        "cn" | "cne" | "cnex" | "cnext" => ("cnext", editor::actions::GoToDiagnostic.boxed_clone()),
210        "lne" | "lnex" | "lnext" => ("cnext", editor::actions::GoToDiagnostic.boxed_clone()),
211
212        "cpr" | "cpre" | "cprev" | "cprevi" | "cprevio" | "cpreviou" | "cprevious" => (
213            "cprevious",
214            editor::actions::GoToPrevDiagnostic.boxed_clone(),
215        ),
216        "cN" | "cNe" | "cNex" | "cNext" => {
217            ("cNext", editor::actions::GoToPrevDiagnostic.boxed_clone())
218        }
219        "lp" | "lpr" | "lpre" | "lprev" | "lprevi" | "lprevio" | "lpreviou" | "lprevious" => (
220            "lprevious",
221            editor::actions::GoToPrevDiagnostic.boxed_clone(),
222        ),
223        "lN" | "lNe" | "lNex" | "lNext" => {
224            ("lNext", editor::actions::GoToPrevDiagnostic.boxed_clone())
225        }
226
227        // modify the buffer (should accept [range])
228        "j" | "jo" | "joi" | "join" => ("join", JoinLines.boxed_clone()),
229        "d" | "de" | "del" | "dele" | "delet" | "delete" | "dl" | "dell" | "delel" | "deletl"
230        | "deletel" | "dp" | "dep" | "delp" | "delep" | "deletp" | "deletep" => {
231            ("delete", editor::actions::DeleteLine.boxed_clone())
232        }
233        "sor" | "sor " | "sort" | "sort " => ("sort", SortLinesCaseSensitive.boxed_clone()),
234        "sor i" | "sort i" => ("sort i", SortLinesCaseInsensitive.boxed_clone()),
235
236        // Explore, etc.
237        "E" | "Ex" | "Exp" | "Expl" | "Explo" | "Explor" | "Explore" => {
238            ("Explore", project_panel::ToggleFocus.boxed_clone())
239        }
240        "H" | "He" | "Hex" | "Hexp" | "Hexpl" | "Hexplo" | "Hexplor" | "Hexplore" => {
241            ("Hexplore", project_panel::ToggleFocus.boxed_clone())
242        }
243        "L" | "Le" | "Lex" | "Lexp" | "Lexpl" | "Lexplo" | "Lexplor" | "Lexplore" => {
244            ("Lexplore", project_panel::ToggleFocus.boxed_clone())
245        }
246        "S" | "Se" | "Sex" | "Sexp" | "Sexpl" | "Sexplo" | "Sexplor" | "Sexplore" => {
247            ("Sexplore", project_panel::ToggleFocus.boxed_clone())
248        }
249        "Ve" | "Vex" | "Vexp" | "Vexpl" | "Vexplo" | "Vexplor" | "Vexplore" => {
250            ("Vexplore", project_panel::ToggleFocus.boxed_clone())
251        }
252
253        // goto (other ranges handled under _ => )
254        "$" => ("$", EndOfDocument.boxed_clone()),
255        "%" => ("%", EndOfDocument.boxed_clone()),
256        "0" => ("0", StartOfDocument.boxed_clone()),
257
258        _ => {
259            if query.starts_with("/") || query.starts_with("?") {
260                (
261                    query,
262                    FindCommand {
263                        query: query[1..].to_string(),
264                        backwards: query.starts_with("?"),
265                    }
266                    .boxed_clone(),
267                )
268            } else if query.starts_with("%") {
269                (
270                    query,
271                    ReplaceCommand {
272                        query: query.to_string(),
273                    }
274                    .boxed_clone(),
275                )
276            } else if let Ok(line) = query.parse::<u32>() {
277                (query, GoToLine { line }.boxed_clone())
278            } else {
279                return None;
280            }
281        }
282    };
283
284    let string = ":".to_owned() + name;
285    let positions = generate_positions(&string, query);
286
287    Some(CommandInterceptResult {
288        action,
289        string,
290        positions,
291    })
292}
293
294fn generate_positions(string: &str, query: &str) -> Vec<usize> {
295    let mut positions = Vec::new();
296    let mut chars = query.chars().into_iter();
297
298    let Some(mut current) = chars.next() else {
299        return positions;
300    };
301
302    for (i, c) in string.char_indices() {
303        if c == current {
304            positions.push(i);
305            if let Some(c) = chars.next() {
306                current = c;
307            } else {
308                break;
309            }
310        }
311    }
312
313    positions
314}
315
316#[cfg(test)]
317mod test {
318    use std::path::Path;
319
320    use crate::test::{NeovimBackedTestContext, VimTestContext};
321    use gpui::TestAppContext;
322    use indoc::indoc;
323
324    #[gpui::test]
325    async fn test_command_basics(cx: &mut TestAppContext) {
326        let mut cx = NeovimBackedTestContext::new(cx).await;
327
328        cx.set_shared_state(indoc! {"
329            ˇa
330            b
331            c"})
332            .await;
333
334        cx.simulate_shared_keystrokes([":", "j", "enter"]).await;
335
336        // hack: our cursor positionining after a join command is wrong
337        cx.simulate_shared_keystrokes(["^"]).await;
338        cx.assert_shared_state(indoc! {
339            "ˇa b
340            c"
341        })
342        .await;
343    }
344
345    #[gpui::test]
346    async fn test_command_goto(cx: &mut TestAppContext) {
347        let mut cx = NeovimBackedTestContext::new(cx).await;
348
349        cx.set_shared_state(indoc! {"
350            ˇa
351            b
352            c"})
353            .await;
354        cx.simulate_shared_keystrokes([":", "3", "enter"]).await;
355        cx.assert_shared_state(indoc! {"
356            a
357            b
358            ˇc"})
359            .await;
360    }
361
362    #[gpui::test]
363    async fn test_command_replace(cx: &mut TestAppContext) {
364        let mut cx = NeovimBackedTestContext::new(cx).await;
365
366        cx.set_shared_state(indoc! {"
367            ˇa
368            b
369            c"})
370            .await;
371        cx.simulate_shared_keystrokes([":", "%", "s", "/", "b", "/", "d", "enter"])
372            .await;
373        cx.assert_shared_state(indoc! {"
374            a
375            ˇd
376            c"})
377            .await;
378        cx.simulate_shared_keystrokes([
379            ":", "%", "s", ":", ".", ":", "\\", "0", "\\", "0", "enter",
380        ])
381        .await;
382        cx.assert_shared_state(indoc! {"
383            aa
384            dd
385            ˇcc"})
386            .await;
387    }
388
389    #[gpui::test]
390    async fn test_command_search(cx: &mut TestAppContext) {
391        let mut cx = NeovimBackedTestContext::new(cx).await;
392
393        cx.set_shared_state(indoc! {"
394                ˇa
395                b
396                a
397                c"})
398            .await;
399        cx.simulate_shared_keystrokes([":", "/", "b", "enter"])
400            .await;
401        cx.assert_shared_state(indoc! {"
402                a
403                ˇb
404                a
405                c"})
406            .await;
407        cx.simulate_shared_keystrokes([":", "?", "a", "enter"])
408            .await;
409        cx.assert_shared_state(indoc! {"
410                ˇa
411                b
412                a
413                c"})
414            .await;
415    }
416
417    #[gpui::test]
418    async fn test_command_write(cx: &mut TestAppContext) {
419        let mut cx = VimTestContext::new(cx, true).await;
420        let path = Path::new("/root/dir/file.rs");
421        let fs = cx.workspace(|workspace, cx| workspace.project().read(cx).fs().clone());
422
423        cx.simulate_keystrokes(["i", "@", "escape"]);
424        cx.simulate_keystrokes([":", "w", "enter"]);
425
426        assert_eq!(fs.load(&path).await.unwrap(), "@\n");
427
428        fs.as_fake()
429            .write_file_internal(path, "oops\n".to_string())
430            .unwrap();
431
432        // conflict!
433        cx.simulate_keystrokes(["i", "@", "escape"]);
434        cx.simulate_keystrokes([":", "w", "enter"]);
435        assert!(cx.has_pending_prompt());
436        // "Cancel"
437        cx.simulate_prompt_answer(0);
438        assert_eq!(fs.load(&path).await.unwrap(), "oops\n");
439        assert!(!cx.has_pending_prompt());
440        // force overwrite
441        cx.simulate_keystrokes([":", "w", "!", "enter"]);
442        assert!(!cx.has_pending_prompt());
443        assert_eq!(fs.load(&path).await.unwrap(), "@@\n");
444    }
445
446    #[gpui::test]
447    async fn test_command_quit(cx: &mut TestAppContext) {
448        let mut cx = VimTestContext::new(cx, true).await;
449
450        cx.simulate_keystrokes([":", "n", "e", "w", "enter"]);
451        cx.workspace(|workspace, cx| assert_eq!(workspace.items(cx).count(), 2));
452        cx.simulate_keystrokes([":", "q", "enter"]);
453        cx.workspace(|workspace, cx| assert_eq!(workspace.items(cx).count(), 1));
454        cx.simulate_keystrokes([":", "n", "e", "w", "enter"]);
455        cx.workspace(|workspace, cx| assert_eq!(workspace.items(cx).count(), 2));
456        cx.simulate_keystrokes([":", "q", "a", "enter"]);
457        cx.workspace(|workspace, cx| assert_eq!(workspace.items(cx).count(), 0));
458    }
459}