command.rs

  1use command_palette::CommandInterceptResult;
  2use editor::{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, cx: &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            todo!(); // Quit is no longer in zed actions :/
172        }
173
174        // pane management
175        "sp" | "spl" | "spli" | "split" => ("split", workspace::SplitUp.boxed_clone()),
176        "vs" | "vsp" | "vspl" | "vspli" | "vsplit" => {
177            ("vsplit", workspace::SplitLeft.boxed_clone())
178        }
179        "new" => (
180            "new",
181            workspace::NewFileInDirection(workspace::SplitDirection::Up).boxed_clone(),
182        ),
183        "vne" | "vnew" => (
184            "vnew",
185            workspace::NewFileInDirection(workspace::SplitDirection::Left).boxed_clone(),
186        ),
187        "tabe" | "tabed" | "tabedi" | "tabedit" => ("tabedit", workspace::NewFile.boxed_clone()),
188        "tabnew" => ("tabnew", workspace::NewFile.boxed_clone()),
189
190        "tabn" | "tabne" | "tabnex" | "tabnext" => {
191            ("tabnext", workspace::ActivateNextItem.boxed_clone())
192        }
193        "tabp" | "tabpr" | "tabpre" | "tabprev" | "tabprevi" | "tabprevio" | "tabpreviou"
194        | "tabprevious" => ("tabprevious", workspace::ActivatePrevItem.boxed_clone()),
195        "tabN" | "tabNe" | "tabNex" | "tabNext" => {
196            ("tabNext", workspace::ActivatePrevItem.boxed_clone())
197        }
198        "tabc" | "tabcl" | "tabclo" | "tabclos" | "tabclose" => (
199            "tabclose",
200            workspace::CloseActiveItem {
201                save_intent: Some(SaveIntent::Close),
202            }
203            .boxed_clone(),
204        ),
205
206        // quickfix / loclist (merged together for now)
207        "cl" | "cli" | "clis" | "clist" => ("clist", diagnostics::Deploy.boxed_clone()),
208        "cc" => ("cc", editor::Hover.boxed_clone()),
209        "ll" => ("ll", editor::Hover.boxed_clone()),
210        "cn" | "cne" | "cnex" | "cnext" => ("cnext", editor::GoToDiagnostic.boxed_clone()),
211        "lne" | "lnex" | "lnext" => ("cnext", editor::GoToDiagnostic.boxed_clone()),
212
213        "cpr" | "cpre" | "cprev" | "cprevi" | "cprevio" | "cpreviou" | "cprevious" => {
214            ("cprevious", editor::GoToPrevDiagnostic.boxed_clone())
215        }
216        "cN" | "cNe" | "cNex" | "cNext" => ("cNext", editor::GoToPrevDiagnostic.boxed_clone()),
217        "lp" | "lpr" | "lpre" | "lprev" | "lprevi" | "lprevio" | "lpreviou" | "lprevious" => {
218            ("lprevious", editor::GoToPrevDiagnostic.boxed_clone())
219        }
220        "lN" | "lNe" | "lNex" | "lNext" => ("lNext", editor::GoToPrevDiagnostic.boxed_clone()),
221
222        // modify the buffer (should accept [range])
223        "j" | "jo" | "joi" | "join" => ("join", JoinLines.boxed_clone()),
224        "d" | "de" | "del" | "dele" | "delet" | "delete" | "dl" | "dell" | "delel" | "deletl"
225        | "deletel" | "dp" | "dep" | "delp" | "delep" | "deletp" | "deletep" => {
226            ("delete", editor::DeleteLine.boxed_clone())
227        }
228        "sor" | "sor " | "sort" | "sort " => ("sort", SortLinesCaseSensitive.boxed_clone()),
229        "sor i" | "sort i" => ("sort i", SortLinesCaseInsensitive.boxed_clone()),
230
231        // goto (other ranges handled under _ => )
232        "$" => ("$", EndOfDocument.boxed_clone()),
233
234        _ => {
235            if query.starts_with("/") || query.starts_with("?") {
236                (
237                    query,
238                    FindCommand {
239                        query: query[1..].to_string(),
240                        backwards: query.starts_with("?"),
241                    }
242                    .boxed_clone(),
243                )
244            } else if query.starts_with("%") {
245                (
246                    query,
247                    ReplaceCommand {
248                        query: query.to_string(),
249                    }
250                    .boxed_clone(),
251                )
252            } else if let Ok(line) = query.parse::<u32>() {
253                (query, GoToLine { line }.boxed_clone())
254            } else {
255                return None;
256            }
257        }
258    };
259
260    let string = ":".to_owned() + name;
261    let positions = generate_positions(&string, query);
262
263    Some(CommandInterceptResult {
264        action,
265        string,
266        positions,
267    })
268}
269
270fn generate_positions(string: &str, query: &str) -> Vec<usize> {
271    let mut positions = Vec::new();
272    let mut chars = query.chars().into_iter();
273
274    let Some(mut current) = chars.next() else {
275        return positions;
276    };
277
278    for (i, c) in string.chars().enumerate() {
279        if c == current {
280            positions.push(i);
281            if let Some(c) = chars.next() {
282                current = c;
283            } else {
284                break;
285            }
286        }
287    }
288
289    positions
290}
291
292// #[cfg(test)]
293// mod test {
294//     use std::path::Path;
295
296//     use crate::test::{NeovimBackedTestContext, VimTestContext};
297//     use gpui::TestAppContext;
298//     use indoc::indoc;
299
300//     #[gpui::test]
301//     async fn test_command_basics(cx: &mut TestAppContext) {
302//         if let Foreground::Deterministic { cx_id: _, executor } = cx.foreground().as_ref() {
303//             executor.run_until_parked();
304//         }
305//         let mut cx = NeovimBackedTestContext::new(cx).await;
306
307//         cx.set_shared_state(indoc! {"
308//             ˇa
309//             b
310//             c"})
311//             .await;
312
313//         cx.simulate_shared_keystrokes([":", "j", "enter"]).await;
314
315//         // hack: our cursor positionining after a join command is wrong
316//         cx.simulate_shared_keystrokes(["^"]).await;
317//         cx.assert_shared_state(indoc! {
318//             "ˇa b
319//             c"
320//         })
321//         .await;
322//     }
323
324//     #[gpui::test]
325//     async fn test_command_goto(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//         cx.simulate_shared_keystrokes([":", "3", "enter"]).await;
334//         cx.assert_shared_state(indoc! {"
335//             a
336//             b
337//             ˇc"})
338//             .await;
339//     }
340
341//     #[gpui::test]
342//     async fn test_command_replace(cx: &mut TestAppContext) {
343//         let mut cx = NeovimBackedTestContext::new(cx).await;
344
345//         cx.set_shared_state(indoc! {"
346//             ˇa
347//             b
348//             c"})
349//             .await;
350//         cx.simulate_shared_keystrokes([":", "%", "s", "/", "b", "/", "d", "enter"])
351//             .await;
352//         cx.assert_shared_state(indoc! {"
353//             a
354//             ˇd
355//             c"})
356//             .await;
357//         cx.simulate_shared_keystrokes([
358//             ":", "%", "s", ":", ".", ":", "\\", "0", "\\", "0", "enter",
359//         ])
360//         .await;
361//         cx.assert_shared_state(indoc! {"
362//             aa
363//             dd
364//             ˇcc"})
365//             .await;
366//     }
367
368//     #[gpui::test]
369//     async fn test_command_search(cx: &mut TestAppContext) {
370//         let mut cx = NeovimBackedTestContext::new(cx).await;
371
372//         cx.set_shared_state(indoc! {"
373//                 ˇa
374//                 b
375//                 a
376//                 c"})
377//             .await;
378//         cx.simulate_shared_keystrokes([":", "/", "b", "enter"])
379//             .await;
380//         cx.assert_shared_state(indoc! {"
381//                 a
382//                 ˇb
383//                 a
384//                 c"})
385//             .await;
386//         cx.simulate_shared_keystrokes([":", "?", "a", "enter"])
387//             .await;
388//         cx.assert_shared_state(indoc! {"
389//                 ˇa
390//                 b
391//                 a
392//                 c"})
393//             .await;
394//     }
395
396//     #[gpui::test]
397//     async fn test_command_write(cx: &mut TestAppContext) {
398//         let mut cx = VimTestContext::new(cx, true).await;
399//         let path = Path::new("/root/dir/file.rs");
400//         let fs = cx.workspace(|workspace, cx| workspace.project().read(cx).fs().clone());
401
402//         cx.simulate_keystrokes(["i", "@", "escape"]);
403//         cx.simulate_keystrokes([":", "w", "enter"]);
404
405//         assert_eq!(fs.load(&path).await.unwrap(), "@\n");
406
407//         fs.as_fake()
408//             .write_file_internal(path, "oops\n".to_string())
409//             .unwrap();
410
411//         // conflict!
412//         cx.simulate_keystrokes(["i", "@", "escape"]);
413//         cx.simulate_keystrokes([":", "w", "enter"]);
414//         let window = cx.window;
415//         assert!(window.has_pending_prompt(cx.cx));
416//         // "Cancel"
417//         window.simulate_prompt_answer(0, cx.cx);
418//         assert_eq!(fs.load(&path).await.unwrap(), "oops\n");
419//         assert!(!window.has_pending_prompt(cx.cx));
420//         // force overwrite
421//         cx.simulate_keystrokes([":", "w", "!", "enter"]);
422//         assert!(!window.has_pending_prompt(cx.cx));
423//         assert_eq!(fs.load(&path).await.unwrap(), "@@\n");
424//     }
425
426//     #[gpui::test]
427//     async fn test_command_quit(cx: &mut TestAppContext) {
428//         let mut cx = VimTestContext::new(cx, true).await;
429
430//         cx.simulate_keystrokes([":", "n", "e", "w", "enter"]);
431//         cx.workspace(|workspace, cx| assert_eq!(workspace.items(cx).count(), 2));
432//         cx.simulate_keystrokes([":", "q", "enter"]);
433//         cx.workspace(|workspace, cx| assert_eq!(workspace.items(cx).count(), 1));
434//         cx.simulate_keystrokes([":", "n", "e", "w", "enter"]);
435//         cx.workspace(|workspace, cx| assert_eq!(workspace.items(cx).count(), 2));
436//         cx.simulate_keystrokes([":", "q", "a", "enter"]);
437//         cx.workspace(|workspace, cx| assert_eq!(workspace.items(cx).count(), 0));
438//     }
439// }