command.rs

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