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},
  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        // goto (other ranges handled under _ => )
237        "$" => ("$", EndOfDocument.boxed_clone()),
238
239        _ => {
240            if query.starts_with("/") || query.starts_with("?") {
241                (
242                    query,
243                    FindCommand {
244                        query: query[1..].to_string(),
245                        backwards: query.starts_with("?"),
246                    }
247                    .boxed_clone(),
248                )
249            } else if query.starts_with("%") {
250                (
251                    query,
252                    ReplaceCommand {
253                        query: query.to_string(),
254                    }
255                    .boxed_clone(),
256                )
257            } else if let Ok(line) = query.parse::<u32>() {
258                (query, GoToLine { line }.boxed_clone())
259            } else {
260                return None;
261            }
262        }
263    };
264
265    let string = ":".to_owned() + name;
266    let positions = generate_positions(&string, query);
267
268    Some(CommandInterceptResult {
269        action,
270        string,
271        positions,
272    })
273}
274
275fn generate_positions(string: &str, query: &str) -> Vec<usize> {
276    let mut positions = Vec::new();
277    let mut chars = query.chars().into_iter();
278
279    let Some(mut current) = chars.next() else {
280        return positions;
281    };
282
283    for (i, c) in string.char_indices() {
284        if c == current {
285            positions.push(i);
286            if let Some(c) = chars.next() {
287                current = c;
288            } else {
289                break;
290            }
291        }
292    }
293
294    positions
295}
296
297#[cfg(test)]
298mod test {
299    use std::path::Path;
300
301    use crate::test::{NeovimBackedTestContext, VimTestContext};
302    use gpui::TestAppContext;
303    use indoc::indoc;
304
305    #[gpui::test]
306    async fn test_command_basics(cx: &mut TestAppContext) {
307        let mut cx = NeovimBackedTestContext::new(cx).await;
308
309        cx.set_shared_state(indoc! {"
310            ˇa
311            b
312            c"})
313            .await;
314
315        cx.simulate_shared_keystrokes([":", "j", "enter"]).await;
316
317        // hack: our cursor positionining after a join command is wrong
318        cx.simulate_shared_keystrokes(["^"]).await;
319        cx.assert_shared_state(indoc! {
320            "ˇa b
321            c"
322        })
323        .await;
324    }
325
326    #[gpui::test]
327    async fn test_command_goto(cx: &mut TestAppContext) {
328        let mut cx = NeovimBackedTestContext::new(cx).await;
329
330        cx.set_shared_state(indoc! {"
331            ˇa
332            b
333            c"})
334            .await;
335        cx.simulate_shared_keystrokes([":", "3", "enter"]).await;
336        cx.assert_shared_state(indoc! {"
337            a
338            b
339            ˇc"})
340            .await;
341    }
342
343    #[gpui::test]
344    async fn test_command_replace(cx: &mut TestAppContext) {
345        let mut cx = NeovimBackedTestContext::new(cx).await;
346
347        cx.set_shared_state(indoc! {"
348            ˇa
349            b
350            c"})
351            .await;
352        cx.simulate_shared_keystrokes([":", "%", "s", "/", "b", "/", "d", "enter"])
353            .await;
354        cx.assert_shared_state(indoc! {"
355            a
356            ˇd
357            c"})
358            .await;
359        cx.simulate_shared_keystrokes([
360            ":", "%", "s", ":", ".", ":", "\\", "0", "\\", "0", "enter",
361        ])
362        .await;
363        cx.assert_shared_state(indoc! {"
364            aa
365            dd
366            ˇcc"})
367            .await;
368    }
369
370    #[gpui::test]
371    async fn test_command_search(cx: &mut TestAppContext) {
372        let mut cx = NeovimBackedTestContext::new(cx).await;
373
374        cx.set_shared_state(indoc! {"
375                ˇa
376                b
377                a
378                c"})
379            .await;
380        cx.simulate_shared_keystrokes([":", "/", "b", "enter"])
381            .await;
382        cx.assert_shared_state(indoc! {"
383                a
384                ˇb
385                a
386                c"})
387            .await;
388        cx.simulate_shared_keystrokes([":", "?", "a", "enter"])
389            .await;
390        cx.assert_shared_state(indoc! {"
391                ˇa
392                b
393                a
394                c"})
395            .await;
396    }
397
398    #[gpui::test]
399    async fn test_command_write(cx: &mut TestAppContext) {
400        let mut cx = VimTestContext::new(cx, true).await;
401        let path = Path::new("/root/dir/file.rs");
402        let fs = cx.workspace(|workspace, cx| workspace.project().read(cx).fs().clone());
403
404        cx.simulate_keystrokes(["i", "@", "escape"]);
405        cx.simulate_keystrokes([":", "w", "enter"]);
406
407        assert_eq!(fs.load(&path).await.unwrap(), "@\n");
408
409        fs.as_fake()
410            .write_file_internal(path, "oops\n".to_string())
411            .unwrap();
412
413        // conflict!
414        cx.simulate_keystrokes(["i", "@", "escape"]);
415        cx.simulate_keystrokes([":", "w", "enter"]);
416        assert!(cx.has_pending_prompt());
417        // "Cancel"
418        cx.simulate_prompt_answer(0);
419        assert_eq!(fs.load(&path).await.unwrap(), "oops\n");
420        assert!(!cx.has_pending_prompt());
421        // force overwrite
422        cx.simulate_keystrokes([":", "w", "!", "enter"]);
423        assert!(!cx.has_pending_prompt());
424        assert_eq!(fs.load(&path).await.unwrap(), "@@\n");
425    }
426
427    #[gpui::test]
428    async fn test_command_quit(cx: &mut TestAppContext) {
429        let mut cx = VimTestContext::new(cx, true).await;
430
431        cx.simulate_keystrokes([":", "n", "e", "w", "enter"]);
432        cx.workspace(|workspace, cx| assert_eq!(workspace.items(cx).count(), 2));
433        cx.simulate_keystrokes([":", "q", "enter"]);
434        cx.workspace(|workspace, cx| assert_eq!(workspace.items(cx).count(), 1));
435        cx.simulate_keystrokes([":", "n", "e", "w", "enter"]);
436        cx.workspace(|workspace, cx| assert_eq!(workspace.items(cx).count(), 2));
437        cx.simulate_keystrokes([":", "q", "a", "enter"]);
438        cx.workspace(|workspace, cx| assert_eq!(workspace.items(cx).count(), 0));
439    }
440}