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