1use anyhow::Result;
2use collections::{HashMap, HashSet};
3use command_palette_hooks::CommandInterceptResult;
4use editor::{
5 Bias, Editor, SelectionEffects, ToPoint,
6 actions::{SortLinesCaseInsensitive, SortLinesCaseSensitive},
7 display_map::ToDisplayPoint,
8};
9use gpui::{Action, App, AppContext as _, Context, Global, Keystroke, Window, actions};
10use itertools::Itertools;
11use language::Point;
12use multi_buffer::MultiBufferRow;
13use project::ProjectPath;
14use regex::Regex;
15use schemars::JsonSchema;
16use search::{BufferSearchBar, SearchOptions};
17use serde::Deserialize;
18use std::{
19 io::Write,
20 iter::Peekable,
21 ops::{Deref, Range},
22 path::Path,
23 process::Stdio,
24 str::Chars,
25 sync::{Arc, OnceLock},
26 time::Instant,
27};
28use task::{HideStrategy, RevealStrategy, SpawnInTerminal, TaskId};
29use ui::ActiveTheme;
30use util::ResultExt;
31use workspace::{Item, SaveIntent, notifications::NotifyResultExt};
32use workspace::{SplitDirection, notifications::DetachAndPromptErr};
33use zed_actions::{OpenDocs, RevealTarget};
34
35use crate::{
36 ToggleMarksView, ToggleRegistersView, Vim,
37 motion::{EndOfDocument, Motion, MotionKind, StartOfDocument},
38 normal::{
39 JoinLines,
40 search::{FindCommand, ReplaceCommand, Replacement},
41 },
42 object::Object,
43 state::{Mark, Mode},
44 visual::VisualDeleteLine,
45};
46
47/// Goes to the specified line number in the editor.
48#[derive(Clone, Debug, PartialEq, Action)]
49#[action(namespace = vim, no_json, no_register)]
50pub struct GoToLine {
51 range: CommandRange,
52}
53
54/// Yanks (copies) text based on the specified range.
55#[derive(Clone, Debug, PartialEq, Action)]
56#[action(namespace = vim, no_json, no_register)]
57pub struct YankCommand {
58 range: CommandRange,
59}
60
61/// Executes a command with the specified range.
62#[derive(Clone, Debug, PartialEq, Action)]
63#[action(namespace = vim, no_json, no_register)]
64pub struct WithRange {
65 restore_selection: bool,
66 range: CommandRange,
67 action: WrappedAction,
68}
69
70/// Executes a command with the specified count.
71#[derive(Clone, Debug, PartialEq, Action)]
72#[action(namespace = vim, no_json, no_register)]
73pub struct WithCount {
74 count: u32,
75 action: WrappedAction,
76}
77
78#[derive(Clone, Deserialize, JsonSchema, PartialEq)]
79pub enum VimOption {
80 Wrap(bool),
81 Number(bool),
82 RelativeNumber(bool),
83}
84
85impl VimOption {
86 fn possible_commands(query: &str) -> Vec<CommandInterceptResult> {
87 let mut prefix_of_options = Vec::new();
88 let mut options = query.split(" ").collect::<Vec<_>>();
89 let prefix = options.pop().unwrap_or_default();
90 for option in options {
91 if let Some(opt) = Self::from(option) {
92 prefix_of_options.push(opt)
93 } else {
94 return vec![];
95 }
96 }
97
98 Self::possibilities(&prefix)
99 .map(|possible| {
100 let mut options = prefix_of_options.clone();
101 options.push(possible);
102
103 CommandInterceptResult {
104 string: format!(
105 ":set {}",
106 options.iter().map(|opt| opt.to_string()).join(" ")
107 ),
108 action: VimSet { options }.boxed_clone(),
109 positions: vec![],
110 }
111 })
112 .collect()
113 }
114
115 fn possibilities(query: &str) -> impl Iterator<Item = Self> + '_ {
116 [
117 (None, VimOption::Wrap(true)),
118 (None, VimOption::Wrap(false)),
119 (None, VimOption::Number(true)),
120 (None, VimOption::Number(false)),
121 (None, VimOption::RelativeNumber(true)),
122 (None, VimOption::RelativeNumber(false)),
123 (Some("rnu"), VimOption::RelativeNumber(true)),
124 (Some("nornu"), VimOption::RelativeNumber(false)),
125 ]
126 .into_iter()
127 .filter(move |(prefix, option)| prefix.unwrap_or(option.to_string()).starts_with(query))
128 .map(|(_, option)| option)
129 }
130
131 fn from(option: &str) -> Option<Self> {
132 match option {
133 "wrap" => Some(Self::Wrap(true)),
134 "nowrap" => Some(Self::Wrap(false)),
135
136 "number" => Some(Self::Number(true)),
137 "nu" => Some(Self::Number(true)),
138 "nonumber" => Some(Self::Number(false)),
139 "nonu" => Some(Self::Number(false)),
140
141 "relativenumber" => Some(Self::RelativeNumber(true)),
142 "rnu" => Some(Self::RelativeNumber(true)),
143 "norelativenumber" => Some(Self::RelativeNumber(false)),
144 "nornu" => Some(Self::RelativeNumber(false)),
145
146 _ => None,
147 }
148 }
149
150 fn to_string(&self) -> &'static str {
151 match self {
152 VimOption::Wrap(true) => "wrap",
153 VimOption::Wrap(false) => "nowrap",
154 VimOption::Number(true) => "number",
155 VimOption::Number(false) => "nonumber",
156 VimOption::RelativeNumber(true) => "relativenumber",
157 VimOption::RelativeNumber(false) => "norelativenumber",
158 }
159 }
160}
161
162/// Sets vim options and configuration values.
163#[derive(Clone, PartialEq, Action)]
164#[action(namespace = vim, no_json, no_register)]
165pub struct VimSet {
166 options: Vec<VimOption>,
167}
168
169/// Saves the current file with optional save intent.
170#[derive(Clone, PartialEq, Action)]
171#[action(namespace = vim, no_json, no_register)]
172struct VimSave {
173 pub save_intent: Option<SaveIntent>,
174 pub filename: String,
175}
176
177/// Deletes the specified marks from the editor.
178#[derive(Clone, PartialEq, Action)]
179#[action(namespace = vim, no_json, no_register)]
180struct VimSplit {
181 pub vertical: bool,
182 pub filename: String,
183}
184
185#[derive(Clone, PartialEq, Action)]
186#[action(namespace = vim, no_json, no_register)]
187enum DeleteMarks {
188 Marks(String),
189 AllLocal,
190}
191
192actions!(
193 vim,
194 [
195 /// Executes a command in visual mode.
196 VisualCommand,
197 /// Executes a command with a count prefix.
198 CountCommand,
199 /// Executes a shell command.
200 ShellCommand,
201 /// Indicates that an argument is required for the command.
202 ArgumentRequired
203 ]
204);
205
206/// Opens the specified file for editing.
207#[derive(Clone, PartialEq, Action)]
208#[action(namespace = vim, no_json, no_register)]
209struct VimEdit {
210 pub filename: String,
211}
212
213#[derive(Clone, PartialEq, Action)]
214#[action(namespace = vim, no_json, no_register)]
215struct VimNorm {
216 pub range: Option<CommandRange>,
217 pub command: String,
218}
219
220#[derive(Debug)]
221struct WrappedAction(Box<dyn Action>);
222
223impl PartialEq for WrappedAction {
224 fn eq(&self, other: &Self) -> bool {
225 self.0.partial_eq(&*other.0)
226 }
227}
228
229impl Clone for WrappedAction {
230 fn clone(&self) -> Self {
231 Self(self.0.boxed_clone())
232 }
233}
234
235impl Deref for WrappedAction {
236 type Target = dyn Action;
237 fn deref(&self) -> &dyn Action {
238 &*self.0
239 }
240}
241
242pub fn register(editor: &mut Editor, cx: &mut Context<Vim>) {
243 // Vim::action(editor, cx, |vim, action: &StartOfLine, window, cx| {
244 Vim::action(editor, cx, |vim, action: &VimSet, _, cx| {
245 for option in action.options.iter() {
246 vim.update_editor(cx, |_, editor, cx| match option {
247 VimOption::Wrap(true) => {
248 editor
249 .set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
250 }
251 VimOption::Wrap(false) => {
252 editor.set_soft_wrap_mode(language::language_settings::SoftWrap::None, cx);
253 }
254 VimOption::Number(enabled) => {
255 editor.set_show_line_numbers(*enabled, cx);
256 }
257 VimOption::RelativeNumber(enabled) => {
258 editor.set_relative_line_number(Some(*enabled), cx);
259 }
260 });
261 }
262 });
263 Vim::action(editor, cx, |vim, _: &VisualCommand, window, cx| {
264 let Some(workspace) = vim.workspace(window) else {
265 return;
266 };
267 workspace.update(cx, |workspace, cx| {
268 command_palette::CommandPalette::toggle(workspace, "'<,'>", window, cx);
269 })
270 });
271
272 Vim::action(editor, cx, |vim, _: &ShellCommand, window, cx| {
273 let Some(workspace) = vim.workspace(window) else {
274 return;
275 };
276 workspace.update(cx, |workspace, cx| {
277 command_palette::CommandPalette::toggle(workspace, "'<,'>!", window, cx);
278 })
279 });
280
281 Vim::action(editor, cx, |_, _: &ArgumentRequired, window, cx| {
282 let _ = window.prompt(
283 gpui::PromptLevel::Critical,
284 "Argument required",
285 None,
286 &["Cancel"],
287 cx,
288 );
289 });
290
291 Vim::action(editor, cx, |vim, _: &ShellCommand, window, cx| {
292 let Some(workspace) = vim.workspace(window) else {
293 return;
294 };
295 workspace.update(cx, |workspace, cx| {
296 command_palette::CommandPalette::toggle(workspace, "'<,'>!", window, cx);
297 })
298 });
299
300 Vim::action(editor, cx, |vim, action: &VimSave, window, cx| {
301 vim.update_editor(cx, |_, editor, cx| {
302 let Some(project) = editor.project.clone() else {
303 return;
304 };
305 let Some(worktree) = project.read(cx).visible_worktrees(cx).next() else {
306 return;
307 };
308 let project_path = ProjectPath {
309 worktree_id: worktree.read(cx).id(),
310 path: Arc::from(Path::new(&action.filename)),
311 };
312
313 if project.read(cx).entry_for_path(&project_path, cx).is_some() && action.save_intent != Some(SaveIntent::Overwrite) {
314 let answer = window.prompt(
315 gpui::PromptLevel::Critical,
316 &format!("{} already exists. Do you want to replace it?", project_path.path.to_string_lossy()),
317 Some(
318 "A file or folder with the same name already exists. Replacing it will overwrite its current contents.",
319 ),
320 &["Replace", "Cancel"],
321 cx);
322 cx.spawn_in(window, async move |editor, cx| {
323 if answer.await.ok() != Some(0) {
324 return;
325 }
326
327 let _ = editor.update_in(cx, |editor, window, cx|{
328 editor
329 .save_as(project, project_path, window, cx)
330 .detach_and_prompt_err("Failed to :w", window, cx, |_, _, _| None);
331 });
332 }).detach();
333 } else {
334 editor
335 .save_as(project, project_path, window, cx)
336 .detach_and_prompt_err("Failed to :w", window, cx, |_, _, _| None);
337 }
338 });
339 });
340
341 Vim::action(editor, cx, |vim, action: &VimSplit, window, cx| {
342 let Some(workspace) = vim.workspace(window) else {
343 return;
344 };
345
346 workspace.update(cx, |workspace, cx| {
347 let project = workspace.project().clone();
348 let Some(worktree) = project.read(cx).visible_worktrees(cx).next() else {
349 return;
350 };
351 let project_path = ProjectPath {
352 worktree_id: worktree.read(cx).id(),
353 path: Arc::from(Path::new(&action.filename)),
354 };
355
356 let direction = if action.vertical {
357 SplitDirection::vertical(cx)
358 } else {
359 SplitDirection::horizontal(cx)
360 };
361
362 workspace
363 .split_path_preview(project_path, false, Some(direction), window, cx)
364 .detach_and_log_err(cx);
365 })
366 });
367
368 Vim::action(editor, cx, |vim, action: &DeleteMarks, window, cx| {
369 fn err(s: String, window: &mut Window, cx: &mut Context<Editor>) {
370 let _ = window.prompt(
371 gpui::PromptLevel::Critical,
372 &format!("Invalid argument: {}", s),
373 None,
374 &["Cancel"],
375 cx,
376 );
377 }
378 vim.update_editor(cx, |vim, editor, cx| match action {
379 DeleteMarks::Marks(s) => {
380 if s.starts_with('-') || s.ends_with('-') || s.contains(['\'', '`']) {
381 err(s.clone(), window, cx);
382 return;
383 }
384
385 let to_delete = if s.len() < 3 {
386 Some(s.clone())
387 } else {
388 s.chars()
389 .tuple_windows::<(_, _, _)>()
390 .map(|(a, b, c)| {
391 if b == '-' {
392 if match a {
393 'a'..='z' => a <= c && c <= 'z',
394 'A'..='Z' => a <= c && c <= 'Z',
395 '0'..='9' => a <= c && c <= '9',
396 _ => false,
397 } {
398 Some((a..=c).collect_vec())
399 } else {
400 None
401 }
402 } else if a == '-' {
403 if c == '-' { None } else { Some(vec![c]) }
404 } else if c == '-' {
405 if a == '-' { None } else { Some(vec![a]) }
406 } else {
407 Some(vec![a, b, c])
408 }
409 })
410 .fold_options(HashSet::<char>::default(), |mut set, chars| {
411 set.extend(chars.iter().copied());
412 set
413 })
414 .map(|set| set.iter().collect::<String>())
415 };
416
417 let Some(to_delete) = to_delete else {
418 err(s.clone(), window, cx);
419 return;
420 };
421
422 for c in to_delete.chars().filter(|c| !c.is_whitespace()) {
423 vim.delete_mark(c.to_string(), editor, window, cx);
424 }
425 }
426 DeleteMarks::AllLocal => {
427 for s in 'a'..='z' {
428 vim.delete_mark(s.to_string(), editor, window, cx);
429 }
430 }
431 });
432 });
433
434 Vim::action(editor, cx, |vim, action: &VimEdit, window, cx| {
435 vim.update_editor(cx, |vim, editor, cx| {
436 let Some(workspace) = vim.workspace(window) else {
437 return;
438 };
439 let Some(project) = editor.project.clone() else {
440 return;
441 };
442 let Some(worktree) = project.read(cx).visible_worktrees(cx).next() else {
443 return;
444 };
445 let project_path = ProjectPath {
446 worktree_id: worktree.read(cx).id(),
447 path: Arc::from(Path::new(&action.filename)),
448 };
449
450 let _ = workspace.update(cx, |workspace, cx| {
451 workspace
452 .open_path(project_path, None, true, window, cx)
453 .detach_and_log_err(cx);
454 });
455 });
456 });
457
458 Vim::action(editor, cx, |vim, action: &VimNorm, window, cx| {
459 let keystrokes = action
460 .command
461 .chars()
462 .map(|c| Keystroke::parse(&c.to_string()).unwrap())
463 .collect();
464 vim.switch_mode(Mode::Normal, true, window, cx);
465 let initial_selections =
466 vim.update_editor(cx, |_, editor, _| editor.selections.disjoint_anchors());
467 if let Some(range) = &action.range {
468 let result = vim.update_editor(cx, |vim, editor, cx| {
469 let range = range.buffer_range(vim, editor, window, cx)?;
470 editor.change_selections(
471 SelectionEffects::no_scroll().nav_history(false),
472 window,
473 cx,
474 |s| {
475 s.select_ranges(
476 (range.start.0..=range.end.0)
477 .map(|line| Point::new(line, 0)..Point::new(line, 0)),
478 );
479 },
480 );
481 anyhow::Ok(())
482 });
483 if let Some(Err(err)) = result {
484 log::error!("Error selecting range: {}", err);
485 return;
486 }
487 };
488
489 let Some(workspace) = vim.workspace(window) else {
490 return;
491 };
492 let task = workspace.update(cx, |workspace, cx| {
493 workspace.send_keystrokes_impl(keystrokes, window, cx)
494 });
495 let had_range = action.range.is_some();
496
497 cx.spawn_in(window, async move |vim, cx| {
498 task.await;
499 vim.update_in(cx, |vim, window, cx| {
500 vim.update_editor(cx, |_, editor, cx| {
501 if had_range {
502 editor.change_selections(SelectionEffects::default(), window, cx, |s| {
503 s.select_anchor_ranges([s.newest_anchor().range()]);
504 })
505 }
506 });
507 if matches!(vim.mode, Mode::Insert | Mode::Replace) {
508 vim.normal_before(&Default::default(), window, cx);
509 } else {
510 vim.switch_mode(Mode::Normal, true, window, cx);
511 }
512 vim.update_editor(cx, |_, editor, cx| {
513 if let Some(first_sel) = initial_selections {
514 if let Some(tx_id) = editor
515 .buffer()
516 .update(cx, |multi, cx| multi.last_transaction_id(cx))
517 {
518 let last_sel = editor.selections.disjoint_anchors();
519 editor.modify_transaction_selection_history(tx_id, |old| {
520 old.0 = first_sel;
521 old.1 = Some(last_sel);
522 });
523 }
524 }
525 });
526 })
527 .ok();
528 })
529 .detach();
530 });
531
532 Vim::action(editor, cx, |vim, _: &CountCommand, window, cx| {
533 let Some(workspace) = vim.workspace(window) else {
534 return;
535 };
536 let count = Vim::take_count(cx).unwrap_or(1);
537 Vim::take_forced_motion(cx);
538 let n = if count > 1 {
539 format!(".,.+{}", count.saturating_sub(1))
540 } else {
541 ".".to_string()
542 };
543 workspace.update(cx, |workspace, cx| {
544 command_palette::CommandPalette::toggle(workspace, &n, window, cx);
545 })
546 });
547
548 Vim::action(editor, cx, |vim, action: &GoToLine, window, cx| {
549 vim.switch_mode(Mode::Normal, false, window, cx);
550 let result = vim.update_editor(cx, |vim, editor, cx| {
551 let snapshot = editor.snapshot(window, cx);
552 let buffer_row = action.range.head().buffer_row(vim, editor, window, cx)?;
553 let current = editor.selections.newest::<Point>(cx);
554 let target = snapshot
555 .buffer_snapshot
556 .clip_point(Point::new(buffer_row.0, current.head().column), Bias::Left);
557 editor.change_selections(Default::default(), window, cx, |s| {
558 s.select_ranges([target..target]);
559 });
560
561 anyhow::Ok(())
562 });
563 if let Some(e @ Err(_)) = result {
564 let Some(workspace) = vim.workspace(window) else {
565 return;
566 };
567 workspace.update(cx, |workspace, cx| {
568 e.notify_err(workspace, cx);
569 });
570 return;
571 }
572 });
573
574 Vim::action(editor, cx, |vim, action: &YankCommand, window, cx| {
575 vim.update_editor(cx, |vim, editor, cx| {
576 let snapshot = editor.snapshot(window, cx);
577 if let Ok(range) = action.range.buffer_range(vim, editor, window, cx) {
578 let end = if range.end < snapshot.buffer_snapshot.max_row() {
579 Point::new(range.end.0 + 1, 0)
580 } else {
581 snapshot.buffer_snapshot.max_point()
582 };
583 vim.copy_ranges(
584 editor,
585 MotionKind::Linewise,
586 true,
587 vec![Point::new(range.start.0, 0)..end],
588 window,
589 cx,
590 )
591 }
592 });
593 });
594
595 Vim::action(editor, cx, |_, action: &WithCount, window, cx| {
596 for _ in 0..action.count {
597 window.dispatch_action(action.action.boxed_clone(), cx)
598 }
599 });
600
601 Vim::action(editor, cx, |vim, action: &WithRange, window, cx| {
602 let result = vim.update_editor(cx, |vim, editor, cx| {
603 action.range.buffer_range(vim, editor, window, cx)
604 });
605
606 let range = match result {
607 None => return,
608 Some(e @ Err(_)) => {
609 let Some(workspace) = vim.workspace(window) else {
610 return;
611 };
612 workspace.update(cx, |workspace, cx| {
613 e.notify_err(workspace, cx);
614 });
615 return;
616 }
617 Some(Ok(result)) => result,
618 };
619
620 let previous_selections = vim
621 .update_editor(cx, |_, editor, cx| {
622 let selections = action.restore_selection.then(|| {
623 editor
624 .selections
625 .disjoint_anchor_ranges()
626 .collect::<Vec<_>>()
627 });
628 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
629 let end = Point::new(range.end.0, s.buffer().line_len(range.end));
630 s.select_ranges([end..Point::new(range.start.0, 0)]);
631 });
632 selections
633 })
634 .flatten();
635 window.dispatch_action(action.action.boxed_clone(), cx);
636 cx.defer_in(window, move |vim, window, cx| {
637 vim.update_editor(cx, |_, editor, cx| {
638 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
639 if let Some(previous_selections) = previous_selections {
640 s.select_ranges(previous_selections);
641 } else {
642 s.select_ranges([
643 Point::new(range.start.0, 0)..Point::new(range.start.0, 0)
644 ]);
645 }
646 })
647 });
648 });
649 });
650
651 Vim::action(editor, cx, |vim, action: &OnMatchingLines, window, cx| {
652 action.run(vim, window, cx)
653 });
654
655 Vim::action(editor, cx, |vim, action: &ShellExec, window, cx| {
656 action.run(vim, window, cx)
657 })
658}
659
660#[derive(Default)]
661struct VimCommand {
662 prefix: &'static str,
663 suffix: &'static str,
664 action: Option<Box<dyn Action>>,
665 action_name: Option<&'static str>,
666 bang_action: Option<Box<dyn Action>>,
667 args: Option<
668 Box<dyn Fn(Box<dyn Action>, String) -> Option<Box<dyn Action>> + Send + Sync + 'static>,
669 >,
670 range: Option<
671 Box<
672 dyn Fn(Box<dyn Action>, &CommandRange) -> Option<Box<dyn Action>>
673 + Send
674 + Sync
675 + 'static,
676 >,
677 >,
678 has_count: bool,
679}
680
681impl VimCommand {
682 fn new(pattern: (&'static str, &'static str), action: impl Action) -> Self {
683 Self {
684 prefix: pattern.0,
685 suffix: pattern.1,
686 action: Some(action.boxed_clone()),
687 ..Default::default()
688 }
689 }
690
691 // from_str is used for actions in other crates.
692 fn str(pattern: (&'static str, &'static str), action_name: &'static str) -> Self {
693 Self {
694 prefix: pattern.0,
695 suffix: pattern.1,
696 action_name: Some(action_name),
697 ..Default::default()
698 }
699 }
700
701 fn bang(mut self, bang_action: impl Action) -> Self {
702 self.bang_action = Some(bang_action.boxed_clone());
703 self
704 }
705
706 fn args(
707 mut self,
708 f: impl Fn(Box<dyn Action>, String) -> Option<Box<dyn Action>> + Send + Sync + 'static,
709 ) -> Self {
710 self.args = Some(Box::new(f));
711 self
712 }
713
714 fn range(
715 mut self,
716 f: impl Fn(Box<dyn Action>, &CommandRange) -> Option<Box<dyn Action>> + Send + Sync + 'static,
717 ) -> Self {
718 self.range = Some(Box::new(f));
719 self
720 }
721
722 fn count(mut self) -> Self {
723 self.has_count = true;
724 self
725 }
726
727 fn parse(
728 &self,
729 query: &str,
730 range: &Option<CommandRange>,
731 cx: &App,
732 ) -> Option<Box<dyn Action>> {
733 let rest = query
734 .to_string()
735 .strip_prefix(self.prefix)?
736 .to_string()
737 .chars()
738 .zip_longest(self.suffix.to_string().chars())
739 .skip_while(|e| e.clone().both().map(|(s, q)| s == q).unwrap_or(false))
740 .filter_map(|e| e.left())
741 .collect::<String>();
742 let has_bang = rest.starts_with('!');
743 let args = if has_bang {
744 rest.strip_prefix('!')?.trim().to_string()
745 } else if rest.is_empty() {
746 "".into()
747 } else {
748 rest.strip_prefix(' ')?.trim().to_string()
749 };
750
751 let action = if has_bang && self.bang_action.is_some() {
752 self.bang_action.as_ref().unwrap().boxed_clone()
753 } else if let Some(action) = self.action.as_ref() {
754 action.boxed_clone()
755 } else if let Some(action_name) = self.action_name {
756 cx.build_action(action_name, None).log_err()?
757 } else {
758 return None;
759 };
760
761 let action = if args.is_empty() {
762 action
763 } else {
764 // if command does not accept args and we have args then we should do no action
765 self.args.as_ref()?(action, args)?
766 };
767
768 if let Some(range) = range {
769 self.range.as_ref().and_then(|f| f(action, range))
770 } else {
771 Some(action)
772 }
773 }
774
775 // TODO: ranges with search queries
776 fn parse_range(query: &str) -> (Option<CommandRange>, String) {
777 let mut chars = query.chars().peekable();
778
779 match chars.peek() {
780 Some('%') => {
781 chars.next();
782 return (
783 Some(CommandRange {
784 start: Position::Line { row: 1, offset: 0 },
785 end: Some(Position::LastLine { offset: 0 }),
786 }),
787 chars.collect(),
788 );
789 }
790 Some('*') => {
791 chars.next();
792 return (
793 Some(CommandRange {
794 start: Position::Mark {
795 name: '<',
796 offset: 0,
797 },
798 end: Some(Position::Mark {
799 name: '>',
800 offset: 0,
801 }),
802 }),
803 chars.collect(),
804 );
805 }
806 _ => {}
807 }
808
809 let start = Self::parse_position(&mut chars);
810
811 match chars.peek() {
812 Some(',' | ';') => {
813 chars.next();
814 (
815 Some(CommandRange {
816 start: start.unwrap_or(Position::CurrentLine { offset: 0 }),
817 end: Self::parse_position(&mut chars),
818 }),
819 chars.collect(),
820 )
821 }
822 _ => (
823 start.map(|start| CommandRange { start, end: None }),
824 chars.collect(),
825 ),
826 }
827 }
828
829 fn parse_position(chars: &mut Peekable<Chars>) -> Option<Position> {
830 match chars.peek()? {
831 '0'..='9' => {
832 let row = Self::parse_u32(chars);
833 Some(Position::Line {
834 row,
835 offset: Self::parse_offset(chars),
836 })
837 }
838 '\'' => {
839 chars.next();
840 let name = chars.next()?;
841 Some(Position::Mark {
842 name,
843 offset: Self::parse_offset(chars),
844 })
845 }
846 '.' => {
847 chars.next();
848 Some(Position::CurrentLine {
849 offset: Self::parse_offset(chars),
850 })
851 }
852 '+' | '-' => Some(Position::CurrentLine {
853 offset: Self::parse_offset(chars),
854 }),
855 '$' => {
856 chars.next();
857 Some(Position::LastLine {
858 offset: Self::parse_offset(chars),
859 })
860 }
861 _ => None,
862 }
863 }
864
865 fn parse_offset(chars: &mut Peekable<Chars>) -> i32 {
866 let mut res: i32 = 0;
867 while matches!(chars.peek(), Some('+' | '-')) {
868 let sign = if chars.next().unwrap() == '+' { 1 } else { -1 };
869 let amount = if matches!(chars.peek(), Some('0'..='9')) {
870 (Self::parse_u32(chars) as i32).saturating_mul(sign)
871 } else {
872 sign
873 };
874 res = res.saturating_add(amount)
875 }
876 res
877 }
878
879 fn parse_u32(chars: &mut Peekable<Chars>) -> u32 {
880 let mut res: u32 = 0;
881 while matches!(chars.peek(), Some('0'..='9')) {
882 res = res
883 .saturating_mul(10)
884 .saturating_add(chars.next().unwrap() as u32 - '0' as u32);
885 }
886 res
887 }
888}
889
890#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq)]
891enum Position {
892 Line { row: u32, offset: i32 },
893 Mark { name: char, offset: i32 },
894 LastLine { offset: i32 },
895 CurrentLine { offset: i32 },
896}
897
898impl Position {
899 fn buffer_row(
900 &self,
901 vim: &Vim,
902 editor: &mut Editor,
903 window: &mut Window,
904 cx: &mut App,
905 ) -> Result<MultiBufferRow> {
906 let snapshot = editor.snapshot(window, cx);
907 let target = match self {
908 Position::Line { row, offset } => {
909 if let Some(anchor) = editor.active_excerpt(cx).and_then(|(_, buffer, _)| {
910 editor.buffer().read(cx).buffer_point_to_anchor(
911 &buffer,
912 Point::new(row.saturating_sub(1), 0),
913 cx,
914 )
915 }) {
916 anchor
917 .to_point(&snapshot.buffer_snapshot)
918 .row
919 .saturating_add_signed(*offset)
920 } else {
921 row.saturating_add_signed(offset.saturating_sub(1))
922 }
923 }
924 Position::Mark { name, offset } => {
925 let Some(Mark::Local(anchors)) =
926 vim.get_mark(&name.to_string(), editor, window, cx)
927 else {
928 anyhow::bail!("mark {name} not set");
929 };
930 let Some(mark) = anchors.last() else {
931 anyhow::bail!("mark {name} contains empty anchors");
932 };
933 mark.to_point(&snapshot.buffer_snapshot)
934 .row
935 .saturating_add_signed(*offset)
936 }
937 Position::LastLine { offset } => snapshot
938 .buffer_snapshot
939 .max_row()
940 .0
941 .saturating_add_signed(*offset),
942 Position::CurrentLine { offset } => editor
943 .selections
944 .newest_anchor()
945 .head()
946 .to_point(&snapshot.buffer_snapshot)
947 .row
948 .saturating_add_signed(*offset),
949 };
950
951 Ok(MultiBufferRow(target).min(snapshot.buffer_snapshot.max_row()))
952 }
953}
954
955#[derive(Clone, Debug, PartialEq)]
956pub(crate) struct CommandRange {
957 start: Position,
958 end: Option<Position>,
959}
960
961impl CommandRange {
962 fn head(&self) -> &Position {
963 self.end.as_ref().unwrap_or(&self.start)
964 }
965
966 pub(crate) fn buffer_range(
967 &self,
968 vim: &Vim,
969 editor: &mut Editor,
970 window: &mut Window,
971 cx: &mut App,
972 ) -> Result<Range<MultiBufferRow>> {
973 let start = self.start.buffer_row(vim, editor, window, cx)?;
974 let end = if let Some(end) = self.end.as_ref() {
975 end.buffer_row(vim, editor, window, cx)?
976 } else {
977 start
978 };
979 if end < start {
980 anyhow::Ok(end..start)
981 } else {
982 anyhow::Ok(start..end)
983 }
984 }
985
986 pub fn as_count(&self) -> Option<u32> {
987 if let CommandRange {
988 start: Position::Line { row, offset: 0 },
989 end: None,
990 } = &self
991 {
992 Some(*row)
993 } else {
994 None
995 }
996 }
997}
998
999fn generate_commands(_: &App) -> Vec<VimCommand> {
1000 vec![
1001 VimCommand::new(
1002 ("w", "rite"),
1003 workspace::Save {
1004 save_intent: Some(SaveIntent::Save),
1005 },
1006 )
1007 .bang(workspace::Save {
1008 save_intent: Some(SaveIntent::Overwrite),
1009 })
1010 .args(|action, args| {
1011 Some(
1012 VimSave {
1013 save_intent: action
1014 .as_any()
1015 .downcast_ref::<workspace::Save>()
1016 .and_then(|action| action.save_intent),
1017 filename: args,
1018 }
1019 .boxed_clone(),
1020 )
1021 }),
1022 VimCommand::new(
1023 ("q", "uit"),
1024 workspace::CloseActiveItem {
1025 save_intent: Some(SaveIntent::Close),
1026 close_pinned: false,
1027 },
1028 )
1029 .bang(workspace::CloseActiveItem {
1030 save_intent: Some(SaveIntent::Skip),
1031 close_pinned: true,
1032 }),
1033 VimCommand::new(
1034 ("wq", ""),
1035 workspace::CloseActiveItem {
1036 save_intent: Some(SaveIntent::Save),
1037 close_pinned: false,
1038 },
1039 )
1040 .bang(workspace::CloseActiveItem {
1041 save_intent: Some(SaveIntent::Overwrite),
1042 close_pinned: true,
1043 }),
1044 VimCommand::new(
1045 ("x", "it"),
1046 workspace::CloseActiveItem {
1047 save_intent: Some(SaveIntent::SaveAll),
1048 close_pinned: false,
1049 },
1050 )
1051 .bang(workspace::CloseActiveItem {
1052 save_intent: Some(SaveIntent::Overwrite),
1053 close_pinned: true,
1054 }),
1055 VimCommand::new(
1056 ("exi", "t"),
1057 workspace::CloseActiveItem {
1058 save_intent: Some(SaveIntent::SaveAll),
1059 close_pinned: false,
1060 },
1061 )
1062 .bang(workspace::CloseActiveItem {
1063 save_intent: Some(SaveIntent::Overwrite),
1064 close_pinned: true,
1065 }),
1066 VimCommand::new(
1067 ("up", "date"),
1068 workspace::Save {
1069 save_intent: Some(SaveIntent::SaveAll),
1070 },
1071 ),
1072 VimCommand::new(
1073 ("wa", "ll"),
1074 workspace::SaveAll {
1075 save_intent: Some(SaveIntent::SaveAll),
1076 },
1077 )
1078 .bang(workspace::SaveAll {
1079 save_intent: Some(SaveIntent::Overwrite),
1080 }),
1081 VimCommand::new(
1082 ("qa", "ll"),
1083 workspace::CloseAllItemsAndPanes {
1084 save_intent: Some(SaveIntent::Close),
1085 },
1086 )
1087 .bang(workspace::CloseAllItemsAndPanes {
1088 save_intent: Some(SaveIntent::Skip),
1089 }),
1090 VimCommand::new(
1091 ("quita", "ll"),
1092 workspace::CloseAllItemsAndPanes {
1093 save_intent: Some(SaveIntent::Close),
1094 },
1095 )
1096 .bang(workspace::CloseAllItemsAndPanes {
1097 save_intent: Some(SaveIntent::Skip),
1098 }),
1099 VimCommand::new(
1100 ("xa", "ll"),
1101 workspace::CloseAllItemsAndPanes {
1102 save_intent: Some(SaveIntent::SaveAll),
1103 },
1104 )
1105 .bang(workspace::CloseAllItemsAndPanes {
1106 save_intent: Some(SaveIntent::Overwrite),
1107 }),
1108 VimCommand::new(
1109 ("wqa", "ll"),
1110 workspace::CloseAllItemsAndPanes {
1111 save_intent: Some(SaveIntent::SaveAll),
1112 },
1113 )
1114 .bang(workspace::CloseAllItemsAndPanes {
1115 save_intent: Some(SaveIntent::Overwrite),
1116 }),
1117 VimCommand::new(("cq", "uit"), zed_actions::Quit),
1118 VimCommand::new(("sp", "lit"), workspace::SplitHorizontal).args(|_, args| {
1119 Some(
1120 VimSplit {
1121 vertical: false,
1122 filename: args,
1123 }
1124 .boxed_clone(),
1125 )
1126 }),
1127 VimCommand::new(("vs", "plit"), workspace::SplitVertical).args(|_, args| {
1128 Some(
1129 VimSplit {
1130 vertical: true,
1131 filename: args,
1132 }
1133 .boxed_clone(),
1134 )
1135 }),
1136 VimCommand::new(
1137 ("bd", "elete"),
1138 workspace::CloseActiveItem {
1139 save_intent: Some(SaveIntent::Close),
1140 close_pinned: false,
1141 },
1142 )
1143 .bang(workspace::CloseActiveItem {
1144 save_intent: Some(SaveIntent::Skip),
1145 close_pinned: true,
1146 }),
1147 VimCommand::new(
1148 ("norm", "al"),
1149 VimNorm {
1150 command: "".into(),
1151 range: None,
1152 },
1153 )
1154 .args(|_, args| {
1155 Some(
1156 VimNorm {
1157 command: args,
1158 range: None,
1159 }
1160 .boxed_clone(),
1161 )
1162 })
1163 .range(|action, range| {
1164 let mut action: VimNorm = action.as_any().downcast_ref::<VimNorm>().unwrap().clone();
1165 action.range.replace(range.clone());
1166 Some(Box::new(action))
1167 }),
1168 VimCommand::new(("bn", "ext"), workspace::ActivateNextItem).count(),
1169 VimCommand::new(("bN", "ext"), workspace::ActivatePreviousItem).count(),
1170 VimCommand::new(("bp", "revious"), workspace::ActivatePreviousItem).count(),
1171 VimCommand::new(("bf", "irst"), workspace::ActivateItem(0)),
1172 VimCommand::new(("br", "ewind"), workspace::ActivateItem(0)),
1173 VimCommand::new(("bl", "ast"), workspace::ActivateLastItem),
1174 VimCommand::str(("buffers", ""), "tab_switcher::ToggleAll"),
1175 VimCommand::str(("ls", ""), "tab_switcher::ToggleAll"),
1176 VimCommand::new(("new", ""), workspace::NewFileSplitHorizontal),
1177 VimCommand::new(("vne", "w"), workspace::NewFileSplitVertical),
1178 VimCommand::new(("tabe", "dit"), workspace::NewFile),
1179 VimCommand::new(("tabnew", ""), workspace::NewFile),
1180 VimCommand::new(("tabn", "ext"), workspace::ActivateNextItem).count(),
1181 VimCommand::new(("tabp", "revious"), workspace::ActivatePreviousItem).count(),
1182 VimCommand::new(("tabN", "ext"), workspace::ActivatePreviousItem).count(),
1183 VimCommand::new(
1184 ("tabc", "lose"),
1185 workspace::CloseActiveItem {
1186 save_intent: Some(SaveIntent::Close),
1187 close_pinned: false,
1188 },
1189 ),
1190 VimCommand::new(
1191 ("tabo", "nly"),
1192 workspace::CloseOtherItems {
1193 save_intent: Some(SaveIntent::Close),
1194 close_pinned: false,
1195 },
1196 )
1197 .bang(workspace::CloseOtherItems {
1198 save_intent: Some(SaveIntent::Skip),
1199 close_pinned: false,
1200 }),
1201 VimCommand::new(
1202 ("on", "ly"),
1203 workspace::CloseInactiveTabsAndPanes {
1204 save_intent: Some(SaveIntent::Close),
1205 },
1206 )
1207 .bang(workspace::CloseInactiveTabsAndPanes {
1208 save_intent: Some(SaveIntent::Skip),
1209 }),
1210 VimCommand::str(("cl", "ist"), "diagnostics::Deploy"),
1211 VimCommand::new(("cc", ""), editor::actions::Hover),
1212 VimCommand::new(("ll", ""), editor::actions::Hover),
1213 VimCommand::new(("cn", "ext"), editor::actions::GoToDiagnostic::default())
1214 .range(wrap_count),
1215 VimCommand::new(
1216 ("cp", "revious"),
1217 editor::actions::GoToPreviousDiagnostic::default(),
1218 )
1219 .range(wrap_count),
1220 VimCommand::new(
1221 ("cN", "ext"),
1222 editor::actions::GoToPreviousDiagnostic::default(),
1223 )
1224 .range(wrap_count),
1225 VimCommand::new(
1226 ("lp", "revious"),
1227 editor::actions::GoToPreviousDiagnostic::default(),
1228 )
1229 .range(wrap_count),
1230 VimCommand::new(
1231 ("lN", "ext"),
1232 editor::actions::GoToPreviousDiagnostic::default(),
1233 )
1234 .range(wrap_count),
1235 VimCommand::new(("j", "oin"), JoinLines).range(select_range),
1236 VimCommand::new(("fo", "ld"), editor::actions::FoldSelectedRanges).range(act_on_range),
1237 VimCommand::new(("foldo", "pen"), editor::actions::UnfoldLines)
1238 .bang(editor::actions::UnfoldRecursive)
1239 .range(act_on_range),
1240 VimCommand::new(("foldc", "lose"), editor::actions::Fold)
1241 .bang(editor::actions::FoldRecursive)
1242 .range(act_on_range),
1243 VimCommand::new(("dif", "fupdate"), editor::actions::ToggleSelectedDiffHunks)
1244 .range(act_on_range),
1245 VimCommand::str(("rev", "ert"), "git::Restore").range(act_on_range),
1246 VimCommand::new(("d", "elete"), VisualDeleteLine).range(select_range),
1247 VimCommand::new(("y", "ank"), gpui::NoAction).range(|_, range| {
1248 Some(
1249 YankCommand {
1250 range: range.clone(),
1251 }
1252 .boxed_clone(),
1253 )
1254 }),
1255 VimCommand::new(("reg", "isters"), ToggleRegistersView).bang(ToggleRegistersView),
1256 VimCommand::new(("di", "splay"), ToggleRegistersView).bang(ToggleRegistersView),
1257 VimCommand::new(("marks", ""), ToggleMarksView).bang(ToggleMarksView),
1258 VimCommand::new(("delm", "arks"), ArgumentRequired)
1259 .bang(DeleteMarks::AllLocal)
1260 .args(|_, args| Some(DeleteMarks::Marks(args).boxed_clone())),
1261 VimCommand::new(("sor", "t"), SortLinesCaseSensitive).range(select_range),
1262 VimCommand::new(("sort i", ""), SortLinesCaseInsensitive).range(select_range),
1263 VimCommand::str(("E", "xplore"), "project_panel::ToggleFocus"),
1264 VimCommand::str(("H", "explore"), "project_panel::ToggleFocus"),
1265 VimCommand::str(("L", "explore"), "project_panel::ToggleFocus"),
1266 VimCommand::str(("S", "explore"), "project_panel::ToggleFocus"),
1267 VimCommand::str(("Ve", "xplore"), "project_panel::ToggleFocus"),
1268 VimCommand::str(("te", "rm"), "terminal_panel::ToggleFocus"),
1269 VimCommand::str(("T", "erm"), "terminal_panel::ToggleFocus"),
1270 VimCommand::str(("C", "ollab"), "collab_panel::ToggleFocus"),
1271 VimCommand::str(("Ch", "at"), "chat_panel::ToggleFocus"),
1272 VimCommand::str(("No", "tifications"), "notification_panel::ToggleFocus"),
1273 VimCommand::str(("A", "I"), "agent::ToggleFocus"),
1274 VimCommand::str(("G", "it"), "git_panel::ToggleFocus"),
1275 VimCommand::str(("D", "ebug"), "debug_panel::ToggleFocus"),
1276 VimCommand::new(("noh", "lsearch"), search::buffer_search::Dismiss),
1277 VimCommand::new(("$", ""), EndOfDocument),
1278 VimCommand::new(("%", ""), EndOfDocument),
1279 VimCommand::new(("0", ""), StartOfDocument),
1280 VimCommand::new(("e", "dit"), editor::actions::ReloadFile)
1281 .bang(editor::actions::ReloadFile)
1282 .args(|_, args| Some(VimEdit { filename: args }.boxed_clone())),
1283 VimCommand::new(("ex", ""), editor::actions::ReloadFile).bang(editor::actions::ReloadFile),
1284 VimCommand::new(("cpp", "link"), editor::actions::CopyPermalinkToLine).range(act_on_range),
1285 VimCommand::str(("opt", "ions"), "zed::OpenDefaultSettings"),
1286 VimCommand::str(("map", ""), "vim::OpenDefaultKeymap"),
1287 VimCommand::new(("h", "elp"), OpenDocs),
1288 ]
1289}
1290
1291struct VimCommands(Vec<VimCommand>);
1292// safety: we only ever access this from the main thread (as ensured by the cx argument)
1293// actions are not Sync so we can't otherwise use a OnceLock.
1294unsafe impl Sync for VimCommands {}
1295impl Global for VimCommands {}
1296
1297fn commands(cx: &App) -> &Vec<VimCommand> {
1298 static COMMANDS: OnceLock<VimCommands> = OnceLock::new();
1299 &COMMANDS
1300 .get_or_init(|| VimCommands(generate_commands(cx)))
1301 .0
1302}
1303
1304fn act_on_range(action: Box<dyn Action>, range: &CommandRange) -> Option<Box<dyn Action>> {
1305 Some(
1306 WithRange {
1307 restore_selection: true,
1308 range: range.clone(),
1309 action: WrappedAction(action),
1310 }
1311 .boxed_clone(),
1312 )
1313}
1314
1315fn select_range(action: Box<dyn Action>, range: &CommandRange) -> Option<Box<dyn Action>> {
1316 Some(
1317 WithRange {
1318 restore_selection: false,
1319 range: range.clone(),
1320 action: WrappedAction(action),
1321 }
1322 .boxed_clone(),
1323 )
1324}
1325
1326fn wrap_count(action: Box<dyn Action>, range: &CommandRange) -> Option<Box<dyn Action>> {
1327 range.as_count().map(|count| {
1328 WithCount {
1329 count,
1330 action: WrappedAction(action),
1331 }
1332 .boxed_clone()
1333 })
1334}
1335
1336pub fn command_interceptor(mut input: &str, cx: &App) -> Vec<CommandInterceptResult> {
1337 // NOTE: We also need to support passing arguments to commands like :w
1338 // (ideally with filename autocompletion).
1339 while input.starts_with(':') {
1340 input = &input[1..];
1341 }
1342
1343 let (range, query) = VimCommand::parse_range(input);
1344 let range_prefix = input[0..(input.len() - query.len())].to_string();
1345 let query = query.as_str().trim();
1346
1347 let action = if range.is_some() && query.is_empty() {
1348 Some(
1349 GoToLine {
1350 range: range.clone().unwrap(),
1351 }
1352 .boxed_clone(),
1353 )
1354 } else if query.starts_with('/') || query.starts_with('?') {
1355 Some(
1356 FindCommand {
1357 query: query[1..].to_string(),
1358 backwards: query.starts_with('?'),
1359 }
1360 .boxed_clone(),
1361 )
1362 } else if query.starts_with("se ") || query.starts_with("set ") {
1363 let (prefix, option) = query.split_once(' ').unwrap();
1364 let mut commands = VimOption::possible_commands(option);
1365 if !commands.is_empty() {
1366 let query = prefix.to_string() + " " + option;
1367 for command in &mut commands {
1368 command.positions = generate_positions(&command.string, &query);
1369 }
1370 }
1371 return commands;
1372 } else if query.starts_with('s') {
1373 let mut substitute = "substitute".chars().peekable();
1374 let mut query = query.chars().peekable();
1375 while substitute
1376 .peek()
1377 .is_some_and(|char| Some(char) == query.peek())
1378 {
1379 substitute.next();
1380 query.next();
1381 }
1382 if let Some(replacement) = Replacement::parse(query) {
1383 let range = range.clone().unwrap_or(CommandRange {
1384 start: Position::CurrentLine { offset: 0 },
1385 end: None,
1386 });
1387 Some(ReplaceCommand { replacement, range }.boxed_clone())
1388 } else {
1389 None
1390 }
1391 } else if query.starts_with('g') || query.starts_with('v') {
1392 let mut global = "global".chars().peekable();
1393 let mut query = query.chars().peekable();
1394 let mut invert = false;
1395 if query.peek() == Some(&'v') {
1396 invert = true;
1397 query.next();
1398 }
1399 while global.peek().is_some_and(|char| Some(char) == query.peek()) {
1400 global.next();
1401 query.next();
1402 }
1403 if !invert && query.peek() == Some(&'!') {
1404 invert = true;
1405 query.next();
1406 }
1407 let range = range.clone().unwrap_or(CommandRange {
1408 start: Position::Line { row: 0, offset: 0 },
1409 end: Some(Position::LastLine { offset: 0 }),
1410 });
1411 if let Some(action) = OnMatchingLines::parse(query, invert, range, cx) {
1412 Some(action.boxed_clone())
1413 } else {
1414 None
1415 }
1416 } else if query.contains('!') {
1417 ShellExec::parse(query, range.clone())
1418 } else {
1419 None
1420 };
1421 if let Some(action) = action {
1422 let string = input.to_string();
1423 let positions = generate_positions(&string, &(range_prefix + query));
1424 return vec![CommandInterceptResult {
1425 action,
1426 string,
1427 positions,
1428 }];
1429 }
1430
1431 for command in commands(cx).iter() {
1432 if let Some(action) = command.parse(query, &range, cx) {
1433 let mut string = ":".to_owned() + &range_prefix + command.prefix + command.suffix;
1434 if query.contains('!') {
1435 string.push('!');
1436 }
1437 let positions = generate_positions(&string, &(range_prefix + query));
1438
1439 return vec![CommandInterceptResult {
1440 action,
1441 string,
1442 positions,
1443 }];
1444 }
1445 }
1446 return Vec::default();
1447}
1448
1449fn generate_positions(string: &str, query: &str) -> Vec<usize> {
1450 let mut positions = Vec::new();
1451 let mut chars = query.chars();
1452
1453 let Some(mut current) = chars.next() else {
1454 return positions;
1455 };
1456
1457 for (i, c) in string.char_indices() {
1458 if c == current {
1459 positions.push(i);
1460 if let Some(c) = chars.next() {
1461 current = c;
1462 } else {
1463 break;
1464 }
1465 }
1466 }
1467
1468 positions
1469}
1470
1471/// Applies a command to all lines matching a pattern.
1472#[derive(Debug, PartialEq, Clone, Action)]
1473#[action(namespace = vim, no_json, no_register)]
1474pub(crate) struct OnMatchingLines {
1475 range: CommandRange,
1476 search: String,
1477 action: WrappedAction,
1478 invert: bool,
1479}
1480
1481impl OnMatchingLines {
1482 // convert a vim query into something more usable by zed.
1483 // we don't attempt to fully convert between the two regex syntaxes,
1484 // but we do flip \( and \) to ( and ) (and vice-versa) in the pattern,
1485 // and convert \0..\9 to $0..$9 in the replacement so that common idioms work.
1486 pub(crate) fn parse(
1487 mut chars: Peekable<Chars>,
1488 invert: bool,
1489 range: CommandRange,
1490 cx: &App,
1491 ) -> Option<Self> {
1492 let delimiter = chars.next().filter(|c| {
1493 !c.is_alphanumeric() && *c != '"' && *c != '|' && *c != '\'' && *c != '!'
1494 })?;
1495
1496 let mut search = String::new();
1497 let mut escaped = false;
1498
1499 while let Some(c) = chars.next() {
1500 if escaped {
1501 escaped = false;
1502 // unescape escaped parens
1503 if c != '(' && c != ')' && c != delimiter {
1504 search.push('\\')
1505 }
1506 search.push(c)
1507 } else if c == '\\' {
1508 escaped = true;
1509 } else if c == delimiter {
1510 break;
1511 } else {
1512 // escape unescaped parens
1513 if c == '(' || c == ')' {
1514 search.push('\\')
1515 }
1516 search.push(c)
1517 }
1518 }
1519
1520 let command: String = chars.collect();
1521
1522 let action = WrappedAction(
1523 command_interceptor(&command, cx)
1524 .first()?
1525 .action
1526 .boxed_clone(),
1527 );
1528
1529 Some(Self {
1530 range,
1531 search,
1532 invert,
1533 action,
1534 })
1535 }
1536
1537 pub fn run(&self, vim: &mut Vim, window: &mut Window, cx: &mut Context<Vim>) {
1538 let result = vim.update_editor(cx, |vim, editor, cx| {
1539 self.range.buffer_range(vim, editor, window, cx)
1540 });
1541
1542 let range = match result {
1543 None => return,
1544 Some(e @ Err(_)) => {
1545 let Some(workspace) = vim.workspace(window) else {
1546 return;
1547 };
1548 workspace.update(cx, |workspace, cx| {
1549 e.notify_err(workspace, cx);
1550 });
1551 return;
1552 }
1553 Some(Ok(result)) => result,
1554 };
1555
1556 let mut action = self.action.boxed_clone();
1557 let mut last_pattern = self.search.clone();
1558
1559 let mut regexes = match Regex::new(&self.search) {
1560 Ok(regex) => vec![(regex, !self.invert)],
1561 e @ Err(_) => {
1562 let Some(workspace) = vim.workspace(window) else {
1563 return;
1564 };
1565 workspace.update(cx, |workspace, cx| {
1566 e.notify_err(workspace, cx);
1567 });
1568 return;
1569 }
1570 };
1571 while let Some(inner) = action
1572 .boxed_clone()
1573 .as_any()
1574 .downcast_ref::<OnMatchingLines>()
1575 {
1576 let Some(regex) = Regex::new(&inner.search).ok() else {
1577 break;
1578 };
1579 last_pattern = inner.search.clone();
1580 action = inner.action.boxed_clone();
1581 regexes.push((regex, !inner.invert))
1582 }
1583
1584 if let Some(pane) = vim.pane(window, cx) {
1585 pane.update(cx, |pane, cx| {
1586 if let Some(search_bar) = pane.toolbar().read(cx).item_of_type::<BufferSearchBar>()
1587 {
1588 search_bar.update(cx, |search_bar, cx| {
1589 if search_bar.show(window, cx) {
1590 let _ = search_bar.search(
1591 &last_pattern,
1592 Some(SearchOptions::REGEX | SearchOptions::CASE_SENSITIVE),
1593 window,
1594 cx,
1595 );
1596 }
1597 });
1598 }
1599 });
1600 };
1601
1602 vim.update_editor(cx, |_, editor, cx| {
1603 let snapshot = editor.snapshot(window, cx);
1604 let mut row = range.start.0;
1605
1606 let point_range = Point::new(range.start.0, 0)
1607 ..snapshot
1608 .buffer_snapshot
1609 .clip_point(Point::new(range.end.0 + 1, 0), Bias::Left);
1610 cx.spawn_in(window, async move |editor, cx| {
1611 let new_selections = cx
1612 .background_spawn(async move {
1613 let mut line = String::new();
1614 let mut new_selections = Vec::new();
1615 let chunks = snapshot
1616 .buffer_snapshot
1617 .text_for_range(point_range)
1618 .chain(["\n"]);
1619
1620 for chunk in chunks {
1621 for (newline_ix, text) in chunk.split('\n').enumerate() {
1622 if newline_ix > 0 {
1623 if regexes.iter().all(|(regex, should_match)| {
1624 regex.is_match(&line) == *should_match
1625 }) {
1626 new_selections
1627 .push(Point::new(row, 0).to_display_point(&snapshot))
1628 }
1629 row += 1;
1630 line.clear();
1631 }
1632 line.push_str(text)
1633 }
1634 }
1635
1636 new_selections
1637 })
1638 .await;
1639
1640 if new_selections.is_empty() {
1641 return;
1642 }
1643 editor
1644 .update_in(cx, |editor, window, cx| {
1645 editor.start_transaction_at(Instant::now(), window, cx);
1646 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1647 s.replace_cursors_with(|_| new_selections);
1648 });
1649 window.dispatch_action(action, cx);
1650 cx.defer_in(window, move |editor, window, cx| {
1651 let newest = editor.selections.newest::<Point>(cx).clone();
1652 editor.change_selections(
1653 SelectionEffects::no_scroll(),
1654 window,
1655 cx,
1656 |s| {
1657 s.select(vec![newest]);
1658 },
1659 );
1660 editor.end_transaction_at(Instant::now(), cx);
1661 })
1662 })
1663 .ok();
1664 })
1665 .detach();
1666 });
1667 }
1668}
1669
1670/// Executes a shell command and returns the output.
1671#[derive(Clone, Debug, PartialEq, Action)]
1672#[action(namespace = vim, no_json, no_register)]
1673pub struct ShellExec {
1674 command: String,
1675 range: Option<CommandRange>,
1676 is_read: bool,
1677}
1678
1679impl Vim {
1680 pub fn cancel_running_command(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1681 if self.running_command.take().is_some() {
1682 self.update_editor(cx, |_, editor, cx| {
1683 editor.transact(window, cx, |editor, _window, _cx| {
1684 editor.clear_row_highlights::<ShellExec>();
1685 })
1686 });
1687 }
1688 }
1689
1690 fn prepare_shell_command(
1691 &mut self,
1692 command: &str,
1693 _: &mut Window,
1694 cx: &mut Context<Self>,
1695 ) -> String {
1696 let mut ret = String::new();
1697 // N.B. non-standard escaping rules:
1698 // * !echo % => "echo README.md"
1699 // * !echo \% => "echo %"
1700 // * !echo \\% => echo \%
1701 // * !echo \\\% => echo \\%
1702 for c in command.chars() {
1703 if c != '%' && c != '!' {
1704 ret.push(c);
1705 continue;
1706 } else if ret.chars().last() == Some('\\') {
1707 ret.pop();
1708 ret.push(c);
1709 continue;
1710 }
1711 match c {
1712 '%' => {
1713 self.update_editor(cx, |_, editor, cx| {
1714 if let Some((_, buffer, _)) = editor.active_excerpt(cx) {
1715 if let Some(file) = buffer.read(cx).file() {
1716 if let Some(local) = file.as_local() {
1717 if let Some(str) = local.path().to_str() {
1718 ret.push_str(str)
1719 }
1720 }
1721 }
1722 }
1723 });
1724 }
1725 '!' => {
1726 if let Some(command) = &self.last_command {
1727 ret.push_str(command)
1728 }
1729 }
1730 _ => {}
1731 }
1732 }
1733 self.last_command = Some(ret.clone());
1734 ret
1735 }
1736
1737 pub fn shell_command_motion(
1738 &mut self,
1739 motion: Motion,
1740 times: Option<usize>,
1741 forced_motion: bool,
1742 window: &mut Window,
1743 cx: &mut Context<Vim>,
1744 ) {
1745 self.stop_recording(cx);
1746 let Some(workspace) = self.workspace(window) else {
1747 return;
1748 };
1749 let command = self.update_editor(cx, |_, editor, cx| {
1750 let snapshot = editor.snapshot(window, cx);
1751 let start = editor.selections.newest_display(cx);
1752 let text_layout_details = editor.text_layout_details(window);
1753 let (mut range, _) = motion
1754 .range(
1755 &snapshot,
1756 start.clone(),
1757 times,
1758 &text_layout_details,
1759 forced_motion,
1760 )
1761 .unwrap_or((start.range(), MotionKind::Exclusive));
1762 if range.start != start.start {
1763 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1764 s.select_ranges([
1765 range.start.to_point(&snapshot)..range.start.to_point(&snapshot)
1766 ]);
1767 })
1768 }
1769 if range.end.row() > range.start.row() && range.end.column() != 0 {
1770 *range.end.row_mut() -= 1
1771 }
1772 if range.end.row() == range.start.row() {
1773 ".!".to_string()
1774 } else {
1775 format!(".,.+{}!", (range.end.row() - range.start.row()).0)
1776 }
1777 });
1778 if let Some(command) = command {
1779 workspace.update(cx, |workspace, cx| {
1780 command_palette::CommandPalette::toggle(workspace, &command, window, cx);
1781 });
1782 }
1783 }
1784
1785 pub fn shell_command_object(
1786 &mut self,
1787 object: Object,
1788 around: bool,
1789 window: &mut Window,
1790 cx: &mut Context<Vim>,
1791 ) {
1792 self.stop_recording(cx);
1793 let Some(workspace) = self.workspace(window) else {
1794 return;
1795 };
1796 let command = self.update_editor(cx, |_, editor, cx| {
1797 let snapshot = editor.snapshot(window, cx);
1798 let start = editor.selections.newest_display(cx);
1799 let range = object
1800 .range(&snapshot, start.clone(), around, None)
1801 .unwrap_or(start.range());
1802 if range.start != start.start {
1803 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1804 s.select_ranges([
1805 range.start.to_point(&snapshot)..range.start.to_point(&snapshot)
1806 ]);
1807 })
1808 }
1809 if range.end.row() == range.start.row() {
1810 ".!".to_string()
1811 } else {
1812 format!(".,.+{}!", (range.end.row() - range.start.row()).0)
1813 }
1814 });
1815 if let Some(command) = command {
1816 workspace.update(cx, |workspace, cx| {
1817 command_palette::CommandPalette::toggle(workspace, &command, window, cx);
1818 });
1819 }
1820 }
1821}
1822
1823impl ShellExec {
1824 pub fn parse(query: &str, range: Option<CommandRange>) -> Option<Box<dyn Action>> {
1825 let (before, after) = query.split_once('!')?;
1826 let before = before.trim();
1827
1828 if !"read".starts_with(before) {
1829 return None;
1830 }
1831
1832 Some(
1833 ShellExec {
1834 command: after.trim().to_string(),
1835 range,
1836 is_read: !before.is_empty(),
1837 }
1838 .boxed_clone(),
1839 )
1840 }
1841
1842 pub fn run(&self, vim: &mut Vim, window: &mut Window, cx: &mut Context<Vim>) {
1843 let Some(workspace) = vim.workspace(window) else {
1844 return;
1845 };
1846
1847 let project = workspace.read(cx).project().clone();
1848 let command = vim.prepare_shell_command(&self.command, window, cx);
1849
1850 if self.range.is_none() && !self.is_read {
1851 workspace.update(cx, |workspace, cx| {
1852 let project = workspace.project().read(cx);
1853 let cwd = project.first_project_directory(cx);
1854 let shell = project.terminal_settings(&cwd, cx).shell.clone();
1855
1856 let spawn_in_terminal = SpawnInTerminal {
1857 id: TaskId("vim".to_string()),
1858 full_label: command.clone(),
1859 label: command.clone(),
1860 command: Some(command.clone()),
1861 args: Vec::new(),
1862 command_label: command.clone(),
1863 cwd,
1864 env: HashMap::default(),
1865 use_new_terminal: true,
1866 allow_concurrent_runs: true,
1867 reveal: RevealStrategy::NoFocus,
1868 reveal_target: RevealTarget::Dock,
1869 hide: HideStrategy::Never,
1870 shell,
1871 show_summary: false,
1872 show_command: false,
1873 show_rerun: false,
1874 };
1875
1876 let task_status = workspace.spawn_in_terminal(spawn_in_terminal, window, cx);
1877 cx.background_spawn(async move {
1878 match task_status.await {
1879 Some(Ok(status)) => {
1880 if status.success() {
1881 log::debug!("Vim shell exec succeeded");
1882 } else {
1883 log::debug!("Vim shell exec failed, code: {:?}", status.code());
1884 }
1885 }
1886 Some(Err(e)) => log::error!("Vim shell exec failed: {e}"),
1887 None => log::debug!("Vim shell exec got cancelled"),
1888 }
1889 })
1890 .detach();
1891 });
1892 return;
1893 };
1894
1895 let mut input_snapshot = None;
1896 let mut input_range = None;
1897 let mut needs_newline_prefix = false;
1898 vim.update_editor(cx, |vim, editor, cx| {
1899 let snapshot = editor.buffer().read(cx).snapshot(cx);
1900 let range = if let Some(range) = self.range.clone() {
1901 let Some(range) = range.buffer_range(vim, editor, window, cx).log_err() else {
1902 return;
1903 };
1904 Point::new(range.start.0, 0)
1905 ..snapshot.clip_point(Point::new(range.end.0 + 1, 0), Bias::Right)
1906 } else {
1907 let mut end = editor.selections.newest::<Point>(cx).range().end;
1908 end = snapshot.clip_point(Point::new(end.row + 1, 0), Bias::Right);
1909 needs_newline_prefix = end == snapshot.max_point();
1910 end..end
1911 };
1912 if self.is_read {
1913 input_range =
1914 Some(snapshot.anchor_after(range.end)..snapshot.anchor_after(range.end));
1915 } else {
1916 input_range =
1917 Some(snapshot.anchor_before(range.start)..snapshot.anchor_after(range.end));
1918 }
1919 editor.highlight_rows::<ShellExec>(
1920 input_range.clone().unwrap(),
1921 cx.theme().status().unreachable_background,
1922 Default::default(),
1923 cx,
1924 );
1925
1926 if !self.is_read {
1927 input_snapshot = Some(snapshot)
1928 }
1929 });
1930
1931 let Some(range) = input_range else { return };
1932
1933 let mut process = project.read(cx).exec_in_shell(command, cx);
1934 process.stdout(Stdio::piped());
1935 process.stderr(Stdio::piped());
1936
1937 if input_snapshot.is_some() {
1938 process.stdin(Stdio::piped());
1939 } else {
1940 process.stdin(Stdio::null());
1941 };
1942
1943 util::set_pre_exec_to_start_new_session(&mut process);
1944 let is_read = self.is_read;
1945
1946 let task = cx.spawn_in(window, async move |vim, cx| {
1947 let Some(mut running) = process.spawn().log_err() else {
1948 vim.update_in(cx, |vim, window, cx| {
1949 vim.cancel_running_command(window, cx);
1950 })
1951 .log_err();
1952 return;
1953 };
1954
1955 if let Some(mut stdin) = running.stdin.take() {
1956 if let Some(snapshot) = input_snapshot {
1957 let range = range.clone();
1958 cx.background_spawn(async move {
1959 for chunk in snapshot.text_for_range(range) {
1960 if stdin.write_all(chunk.as_bytes()).log_err().is_none() {
1961 return;
1962 }
1963 }
1964 stdin.flush().log_err();
1965 })
1966 .detach();
1967 }
1968 };
1969
1970 let output = cx
1971 .background_spawn(async move { running.wait_with_output() })
1972 .await;
1973
1974 let Some(output) = output.log_err() else {
1975 vim.update_in(cx, |vim, window, cx| {
1976 vim.cancel_running_command(window, cx);
1977 })
1978 .log_err();
1979 return;
1980 };
1981 let mut text = String::new();
1982 if needs_newline_prefix {
1983 text.push('\n');
1984 }
1985 text.push_str(&String::from_utf8_lossy(&output.stdout));
1986 text.push_str(&String::from_utf8_lossy(&output.stderr));
1987 if !text.is_empty() && text.chars().last() != Some('\n') {
1988 text.push('\n');
1989 }
1990
1991 vim.update_in(cx, |vim, window, cx| {
1992 vim.update_editor(cx, |_, editor, cx| {
1993 editor.transact(window, cx, |editor, window, cx| {
1994 editor.edit([(range.clone(), text)], cx);
1995 let snapshot = editor.buffer().read(cx).snapshot(cx);
1996 editor.change_selections(Default::default(), window, cx, |s| {
1997 let point = if is_read {
1998 let point = range.end.to_point(&snapshot);
1999 Point::new(point.row.saturating_sub(1), 0)
2000 } else {
2001 let point = range.start.to_point(&snapshot);
2002 Point::new(point.row, 0)
2003 };
2004 s.select_ranges([point..point]);
2005 })
2006 })
2007 });
2008 vim.cancel_running_command(window, cx);
2009 })
2010 .log_err();
2011 });
2012 vim.running_command.replace(task);
2013 }
2014}
2015
2016#[cfg(test)]
2017mod test {
2018 use std::path::Path;
2019
2020 use crate::{
2021 VimAddon,
2022 state::Mode,
2023 test::{NeovimBackedTestContext, VimTestContext},
2024 };
2025 use editor::Editor;
2026 use gpui::{Context, TestAppContext};
2027 use indoc::indoc;
2028 use util::path;
2029 use workspace::Workspace;
2030
2031 #[gpui::test]
2032 async fn test_command_basics(cx: &mut TestAppContext) {
2033 let mut cx = NeovimBackedTestContext::new(cx).await;
2034
2035 cx.set_shared_state(indoc! {"
2036 ˇa
2037 b
2038 c"})
2039 .await;
2040
2041 cx.simulate_shared_keystrokes(": j enter").await;
2042
2043 // hack: our cursor positioning after a join command is wrong
2044 cx.simulate_shared_keystrokes("^").await;
2045 cx.shared_state().await.assert_eq(indoc! {
2046 "ˇa b
2047 c"
2048 });
2049 }
2050
2051 #[gpui::test]
2052 async fn test_command_goto(cx: &mut TestAppContext) {
2053 let mut cx = NeovimBackedTestContext::new(cx).await;
2054
2055 cx.set_shared_state(indoc! {"
2056 ˇa
2057 b
2058 c"})
2059 .await;
2060 cx.simulate_shared_keystrokes(": 3 enter").await;
2061 cx.shared_state().await.assert_eq(indoc! {"
2062 a
2063 b
2064 ˇc"});
2065 }
2066
2067 #[gpui::test]
2068 async fn test_command_replace(cx: &mut TestAppContext) {
2069 let mut cx = NeovimBackedTestContext::new(cx).await;
2070
2071 cx.set_shared_state(indoc! {"
2072 ˇa
2073 b
2074 b
2075 c"})
2076 .await;
2077 cx.simulate_shared_keystrokes(": % s / b / d enter").await;
2078 cx.shared_state().await.assert_eq(indoc! {"
2079 a
2080 d
2081 ˇd
2082 c"});
2083 cx.simulate_shared_keystrokes(": % s : . : \\ 0 \\ 0 enter")
2084 .await;
2085 cx.shared_state().await.assert_eq(indoc! {"
2086 aa
2087 dd
2088 dd
2089 ˇcc"});
2090 cx.simulate_shared_keystrokes("k : s / d d / e e enter")
2091 .await;
2092 cx.shared_state().await.assert_eq(indoc! {"
2093 aa
2094 dd
2095 ˇee
2096 cc"});
2097 }
2098
2099 #[gpui::test]
2100 async fn test_command_search(cx: &mut TestAppContext) {
2101 let mut cx = NeovimBackedTestContext::new(cx).await;
2102
2103 cx.set_shared_state(indoc! {"
2104 ˇa
2105 b
2106 a
2107 c"})
2108 .await;
2109 cx.simulate_shared_keystrokes(": / b enter").await;
2110 cx.shared_state().await.assert_eq(indoc! {"
2111 a
2112 ˇb
2113 a
2114 c"});
2115 cx.simulate_shared_keystrokes(": ? a enter").await;
2116 cx.shared_state().await.assert_eq(indoc! {"
2117 ˇa
2118 b
2119 a
2120 c"});
2121 }
2122
2123 #[gpui::test]
2124 async fn test_command_write(cx: &mut TestAppContext) {
2125 let mut cx = VimTestContext::new(cx, true).await;
2126 let path = Path::new(path!("/root/dir/file.rs"));
2127 let fs = cx.workspace(|workspace, _, cx| workspace.project().read(cx).fs().clone());
2128
2129 cx.simulate_keystrokes("i @ escape");
2130 cx.simulate_keystrokes(": w enter");
2131
2132 assert_eq!(fs.load(path).await.unwrap().replace("\r\n", "\n"), "@\n");
2133
2134 fs.as_fake().insert_file(path, b"oops\n".to_vec()).await;
2135
2136 // conflict!
2137 cx.simulate_keystrokes("i @ escape");
2138 cx.simulate_keystrokes(": w enter");
2139 cx.simulate_prompt_answer("Cancel");
2140
2141 assert_eq!(fs.load(path).await.unwrap().replace("\r\n", "\n"), "oops\n");
2142 assert!(!cx.has_pending_prompt());
2143 cx.simulate_keystrokes(": w ! enter");
2144 assert!(!cx.has_pending_prompt());
2145 assert_eq!(fs.load(path).await.unwrap().replace("\r\n", "\n"), "@@\n");
2146 }
2147
2148 #[gpui::test]
2149 async fn test_command_quit(cx: &mut TestAppContext) {
2150 let mut cx = VimTestContext::new(cx, true).await;
2151
2152 cx.simulate_keystrokes(": n e w enter");
2153 cx.workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 2));
2154 cx.simulate_keystrokes(": q enter");
2155 cx.workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 1));
2156 cx.simulate_keystrokes(": n e w enter");
2157 cx.workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 2));
2158 cx.simulate_keystrokes(": q a enter");
2159 cx.workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 0));
2160 }
2161
2162 #[gpui::test]
2163 async fn test_offsets(cx: &mut TestAppContext) {
2164 let mut cx = NeovimBackedTestContext::new(cx).await;
2165
2166 cx.set_shared_state("ˇ1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n")
2167 .await;
2168
2169 cx.simulate_shared_keystrokes(": + enter").await;
2170 cx.shared_state()
2171 .await
2172 .assert_eq("1\nˇ2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n");
2173
2174 cx.simulate_shared_keystrokes(": 1 0 - enter").await;
2175 cx.shared_state()
2176 .await
2177 .assert_eq("1\n2\n3\n4\n5\n6\n7\n8\nˇ9\n10\n11\n");
2178
2179 cx.simulate_shared_keystrokes(": . - 2 enter").await;
2180 cx.shared_state()
2181 .await
2182 .assert_eq("1\n2\n3\n4\n5\n6\nˇ7\n8\n9\n10\n11\n");
2183
2184 cx.simulate_shared_keystrokes(": % enter").await;
2185 cx.shared_state()
2186 .await
2187 .assert_eq("1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\nˇ");
2188 }
2189
2190 #[gpui::test]
2191 async fn test_command_ranges(cx: &mut TestAppContext) {
2192 let mut cx = NeovimBackedTestContext::new(cx).await;
2193
2194 cx.set_shared_state("ˇ1\n2\n3\n4\n4\n3\n2\n1").await;
2195
2196 cx.simulate_shared_keystrokes(": 2 , 4 d enter").await;
2197 cx.shared_state().await.assert_eq("1\nˇ4\n3\n2\n1");
2198
2199 cx.simulate_shared_keystrokes(": 2 , 4 s o r t enter").await;
2200 cx.shared_state().await.assert_eq("1\nˇ2\n3\n4\n1");
2201
2202 cx.simulate_shared_keystrokes(": 2 , 4 j o i n enter").await;
2203 cx.shared_state().await.assert_eq("1\nˇ2 3 4\n1");
2204 }
2205
2206 #[gpui::test]
2207 async fn test_command_visual_replace(cx: &mut TestAppContext) {
2208 let mut cx = NeovimBackedTestContext::new(cx).await;
2209
2210 cx.set_shared_state("ˇ1\n2\n3\n4\n4\n3\n2\n1").await;
2211
2212 cx.simulate_shared_keystrokes("v 2 j : s / . / k enter")
2213 .await;
2214 cx.shared_state().await.assert_eq("k\nk\nˇk\n4\n4\n3\n2\n1");
2215 }
2216
2217 #[track_caller]
2218 fn assert_active_item(
2219 workspace: &mut Workspace,
2220 expected_path: &str,
2221 expected_text: &str,
2222 cx: &mut Context<Workspace>,
2223 ) {
2224 let active_editor = workspace.active_item_as::<Editor>(cx).unwrap();
2225
2226 let buffer = active_editor
2227 .read(cx)
2228 .buffer()
2229 .read(cx)
2230 .as_singleton()
2231 .unwrap();
2232
2233 let text = buffer.read(cx).text();
2234 let file = buffer.read(cx).file().unwrap();
2235 let file_path = file.as_local().unwrap().abs_path(cx);
2236
2237 assert_eq!(text, expected_text);
2238 assert_eq!(file_path, Path::new(expected_path));
2239 }
2240
2241 #[gpui::test]
2242 async fn test_command_gf(cx: &mut TestAppContext) {
2243 let mut cx = VimTestContext::new(cx, true).await;
2244
2245 // Assert base state, that we're in /root/dir/file.rs
2246 cx.workspace(|workspace, _, cx| {
2247 assert_active_item(workspace, path!("/root/dir/file.rs"), "", cx);
2248 });
2249
2250 // Insert a new file
2251 let fs = cx.workspace(|workspace, _, cx| workspace.project().read(cx).fs().clone());
2252 fs.as_fake()
2253 .insert_file(
2254 path!("/root/dir/file2.rs"),
2255 "This is file2.rs".as_bytes().to_vec(),
2256 )
2257 .await;
2258 fs.as_fake()
2259 .insert_file(
2260 path!("/root/dir/file3.rs"),
2261 "go to file3".as_bytes().to_vec(),
2262 )
2263 .await;
2264
2265 // Put the path to the second file into the currently open buffer
2266 cx.set_state(indoc! {"go to fiˇle2.rs"}, Mode::Normal);
2267
2268 // Go to file2.rs
2269 cx.simulate_keystrokes("g f");
2270
2271 // We now have two items
2272 cx.workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 2));
2273 cx.workspace(|workspace, _, cx| {
2274 assert_active_item(
2275 workspace,
2276 path!("/root/dir/file2.rs"),
2277 "This is file2.rs",
2278 cx,
2279 );
2280 });
2281
2282 // Update editor to point to `file2.rs`
2283 cx.editor =
2284 cx.workspace(|workspace, _, cx| workspace.active_item_as::<Editor>(cx).unwrap());
2285
2286 // Put the path to the third file into the currently open buffer,
2287 // but remove its suffix, because we want that lookup to happen automatically.
2288 cx.set_state(indoc! {"go to fiˇle3"}, Mode::Normal);
2289
2290 // Go to file3.rs
2291 cx.simulate_keystrokes("g f");
2292
2293 // We now have three items
2294 cx.workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 3));
2295 cx.workspace(|workspace, _, cx| {
2296 assert_active_item(workspace, path!("/root/dir/file3.rs"), "go to file3", cx);
2297 });
2298 }
2299
2300 #[gpui::test]
2301 async fn test_w_command(cx: &mut TestAppContext) {
2302 let mut cx = VimTestContext::new(cx, true).await;
2303
2304 cx.workspace(|workspace, _, cx| {
2305 assert_active_item(workspace, path!("/root/dir/file.rs"), "", cx);
2306 });
2307
2308 cx.simulate_keystrokes(": w space other.rs");
2309 cx.simulate_keystrokes("enter");
2310
2311 cx.workspace(|workspace, _, cx| {
2312 assert_active_item(workspace, path!("/root/other.rs"), "", cx);
2313 });
2314
2315 cx.simulate_keystrokes(": w space dir/file.rs");
2316 cx.simulate_keystrokes("enter");
2317
2318 cx.simulate_prompt_answer("Replace");
2319 cx.run_until_parked();
2320
2321 cx.workspace(|workspace, _, cx| {
2322 assert_active_item(workspace, path!("/root/dir/file.rs"), "", cx);
2323 });
2324
2325 cx.simulate_keystrokes(": w ! space other.rs");
2326 cx.simulate_keystrokes("enter");
2327
2328 cx.workspace(|workspace, _, cx| {
2329 assert_active_item(workspace, path!("/root/other.rs"), "", cx);
2330 });
2331 }
2332
2333 #[gpui::test]
2334 async fn test_command_matching_lines(cx: &mut TestAppContext) {
2335 let mut cx = NeovimBackedTestContext::new(cx).await;
2336
2337 cx.set_shared_state(indoc! {"
2338 ˇa
2339 b
2340 a
2341 b
2342 a
2343 "})
2344 .await;
2345
2346 cx.simulate_shared_keystrokes(":").await;
2347 cx.simulate_shared_keystrokes("g / a / d").await;
2348 cx.simulate_shared_keystrokes("enter").await;
2349
2350 cx.shared_state().await.assert_eq(indoc! {"
2351 b
2352 b
2353 ˇ"});
2354
2355 cx.simulate_shared_keystrokes("u").await;
2356
2357 cx.shared_state().await.assert_eq(indoc! {"
2358 ˇa
2359 b
2360 a
2361 b
2362 a
2363 "});
2364
2365 cx.simulate_shared_keystrokes(":").await;
2366 cx.simulate_shared_keystrokes("v / a / d").await;
2367 cx.simulate_shared_keystrokes("enter").await;
2368
2369 cx.shared_state().await.assert_eq(indoc! {"
2370 a
2371 a
2372 ˇa"});
2373 }
2374
2375 #[gpui::test]
2376 async fn test_del_marks(cx: &mut TestAppContext) {
2377 let mut cx = NeovimBackedTestContext::new(cx).await;
2378
2379 cx.set_shared_state(indoc! {"
2380 ˇa
2381 b
2382 a
2383 b
2384 a
2385 "})
2386 .await;
2387
2388 cx.simulate_shared_keystrokes("m a").await;
2389
2390 let mark = cx.update_editor(|editor, window, cx| {
2391 let vim = editor.addon::<VimAddon>().unwrap().entity.clone();
2392 vim.update(cx, |vim, cx| vim.get_mark("a", editor, window, cx))
2393 });
2394 assert!(mark.is_some());
2395
2396 cx.simulate_shared_keystrokes(": d e l m space a").await;
2397 cx.simulate_shared_keystrokes("enter").await;
2398
2399 let mark = cx.update_editor(|editor, window, cx| {
2400 let vim = editor.addon::<VimAddon>().unwrap().entity.clone();
2401 vim.update(cx, |vim, cx| vim.get_mark("a", editor, window, cx))
2402 });
2403 assert!(mark.is_none())
2404 }
2405
2406 #[gpui::test]
2407 async fn test_normal_command(cx: &mut TestAppContext) {
2408 let mut cx = NeovimBackedTestContext::new(cx).await;
2409
2410 cx.set_shared_state(indoc! {"
2411 The quick
2412 brown« fox
2413 jumpsˇ» over
2414 the lazy dog
2415 "})
2416 .await;
2417
2418 cx.simulate_shared_keystrokes(": n o r m space w C w o r d")
2419 .await;
2420 cx.simulate_shared_keystrokes("enter").await;
2421
2422 cx.shared_state().await.assert_eq(indoc! {"
2423 The quick
2424 brown word
2425 jumps worˇd
2426 the lazy dog
2427 "});
2428
2429 cx.simulate_shared_keystrokes(": n o r m space _ w c i w t e s t")
2430 .await;
2431 cx.simulate_shared_keystrokes("enter").await;
2432
2433 cx.shared_state().await.assert_eq(indoc! {"
2434 The quick
2435 brown word
2436 jumps tesˇt
2437 the lazy dog
2438 "});
2439
2440 cx.simulate_shared_keystrokes("_ l v l : n o r m space s l a")
2441 .await;
2442 cx.simulate_shared_keystrokes("enter").await;
2443
2444 cx.shared_state().await.assert_eq(indoc! {"
2445 The quick
2446 brown word
2447 lˇaumps test
2448 the lazy dog
2449 "});
2450
2451 cx.set_shared_state(indoc! {"
2452 ˇThe quick
2453 brown fox
2454 jumps over
2455 the lazy dog
2456 "})
2457 .await;
2458
2459 cx.simulate_shared_keystrokes("c i w M y escape").await;
2460
2461 cx.shared_state().await.assert_eq(indoc! {"
2462 Mˇy quick
2463 brown fox
2464 jumps over
2465 the lazy dog
2466 "});
2467
2468 cx.simulate_shared_keystrokes(": n o r m space u").await;
2469 cx.simulate_shared_keystrokes("enter").await;
2470
2471 cx.shared_state().await.assert_eq(indoc! {"
2472 ˇThe quick
2473 brown fox
2474 jumps over
2475 the lazy dog
2476 "});
2477 // Once ctrl-v to input character literals is added there should be a test for redo
2478 }
2479}