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, 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().cloned() 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().cloned() 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                        && 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            .ok();
 527        })
 528        .detach();
 529    });
 530
 531    Vim::action(editor, cx, |vim, _: &CountCommand, window, cx| {
 532        let Some(workspace) = vim.workspace(window) else {
 533            return;
 534        };
 535        let count = Vim::take_count(cx).unwrap_or(1);
 536        Vim::take_forced_motion(cx);
 537        let n = if count > 1 {
 538            format!(".,.+{}", count.saturating_sub(1))
 539        } else {
 540            ".".to_string()
 541        };
 542        workspace.update(cx, |workspace, cx| {
 543            command_palette::CommandPalette::toggle(workspace, &n, window, cx);
 544        })
 545    });
 546
 547    Vim::action(editor, cx, |vim, action: &GoToLine, window, cx| {
 548        vim.switch_mode(Mode::Normal, false, window, cx);
 549        let result = vim.update_editor(cx, |vim, editor, cx| {
 550            let snapshot = editor.snapshot(window, cx);
 551            let buffer_row = action.range.head().buffer_row(vim, editor, window, cx)?;
 552            let current = editor.selections.newest::<Point>(cx);
 553            let target = snapshot
 554                .buffer_snapshot
 555                .clip_point(Point::new(buffer_row.0, current.head().column), Bias::Left);
 556            editor.change_selections(Default::default(), window, cx, |s| {
 557                s.select_ranges([target..target]);
 558            });
 559
 560            anyhow::Ok(())
 561        });
 562        if let Some(e @ Err(_)) = result {
 563            let Some(workspace) = vim.workspace(window) else {
 564                return;
 565            };
 566            workspace.update(cx, |workspace, cx| {
 567                e.notify_err(workspace, cx);
 568            });
 569        }
 570    });
 571
 572    Vim::action(editor, cx, |vim, action: &YankCommand, window, cx| {
 573        vim.update_editor(cx, |vim, editor, cx| {
 574            let snapshot = editor.snapshot(window, cx);
 575            if let Ok(range) = action.range.buffer_range(vim, editor, window, cx) {
 576                let end = if range.end < snapshot.buffer_snapshot.max_row() {
 577                    Point::new(range.end.0 + 1, 0)
 578                } else {
 579                    snapshot.buffer_snapshot.max_point()
 580                };
 581                vim.copy_ranges(
 582                    editor,
 583                    MotionKind::Linewise,
 584                    true,
 585                    vec![Point::new(range.start.0, 0)..end],
 586                    window,
 587                    cx,
 588                )
 589            }
 590        });
 591    });
 592
 593    Vim::action(editor, cx, |_, action: &WithCount, window, cx| {
 594        for _ in 0..action.count {
 595            window.dispatch_action(action.action.boxed_clone(), cx)
 596        }
 597    });
 598
 599    Vim::action(editor, cx, |vim, action: &WithRange, window, cx| {
 600        let result = vim.update_editor(cx, |vim, editor, cx| {
 601            action.range.buffer_range(vim, editor, window, cx)
 602        });
 603
 604        let range = match result {
 605            None => return,
 606            Some(e @ Err(_)) => {
 607                let Some(workspace) = vim.workspace(window) else {
 608                    return;
 609                };
 610                workspace.update(cx, |workspace, cx| {
 611                    e.notify_err(workspace, cx);
 612                });
 613                return;
 614            }
 615            Some(Ok(result)) => result,
 616        };
 617
 618        let previous_selections = vim
 619            .update_editor(cx, |_, editor, cx| {
 620                let selections = action.restore_selection.then(|| {
 621                    editor
 622                        .selections
 623                        .disjoint_anchor_ranges()
 624                        .collect::<Vec<_>>()
 625                });
 626                editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
 627                    let end = Point::new(range.end.0, s.buffer().line_len(range.end));
 628                    s.select_ranges([end..Point::new(range.start.0, 0)]);
 629                });
 630                selections
 631            })
 632            .flatten();
 633        window.dispatch_action(action.action.boxed_clone(), cx);
 634        cx.defer_in(window, move |vim, window, cx| {
 635            vim.update_editor(cx, |_, editor, cx| {
 636                editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
 637                    if let Some(previous_selections) = previous_selections {
 638                        s.select_ranges(previous_selections);
 639                    } else {
 640                        s.select_ranges([
 641                            Point::new(range.start.0, 0)..Point::new(range.start.0, 0)
 642                        ]);
 643                    }
 644                })
 645            });
 646        });
 647    });
 648
 649    Vim::action(editor, cx, |vim, action: &OnMatchingLines, window, cx| {
 650        action.run(vim, window, cx)
 651    });
 652
 653    Vim::action(editor, cx, |vim, action: &ShellExec, window, cx| {
 654        action.run(vim, window, cx)
 655    })
 656}
 657
 658#[derive(Default)]
 659struct VimCommand {
 660    prefix: &'static str,
 661    suffix: &'static str,
 662    action: Option<Box<dyn Action>>,
 663    action_name: Option<&'static str>,
 664    bang_action: Option<Box<dyn Action>>,
 665    args: Option<
 666        Box<dyn Fn(Box<dyn Action>, String) -> Option<Box<dyn Action>> + Send + Sync + 'static>,
 667    >,
 668    range: Option<
 669        Box<
 670            dyn Fn(Box<dyn Action>, &CommandRange) -> Option<Box<dyn Action>>
 671                + Send
 672                + Sync
 673                + 'static,
 674        >,
 675    >,
 676    has_count: bool,
 677}
 678
 679impl VimCommand {
 680    fn new(pattern: (&'static str, &'static str), action: impl Action) -> Self {
 681        Self {
 682            prefix: pattern.0,
 683            suffix: pattern.1,
 684            action: Some(action.boxed_clone()),
 685            ..Default::default()
 686        }
 687    }
 688
 689    // from_str is used for actions in other crates.
 690    fn str(pattern: (&'static str, &'static str), action_name: &'static str) -> Self {
 691        Self {
 692            prefix: pattern.0,
 693            suffix: pattern.1,
 694            action_name: Some(action_name),
 695            ..Default::default()
 696        }
 697    }
 698
 699    fn bang(mut self, bang_action: impl Action) -> Self {
 700        self.bang_action = Some(bang_action.boxed_clone());
 701        self
 702    }
 703
 704    fn args(
 705        mut self,
 706        f: impl Fn(Box<dyn Action>, String) -> Option<Box<dyn Action>> + Send + Sync + 'static,
 707    ) -> Self {
 708        self.args = Some(Box::new(f));
 709        self
 710    }
 711
 712    fn range(
 713        mut self,
 714        f: impl Fn(Box<dyn Action>, &CommandRange) -> Option<Box<dyn Action>> + Send + Sync + 'static,
 715    ) -> Self {
 716        self.range = Some(Box::new(f));
 717        self
 718    }
 719
 720    fn count(mut self) -> Self {
 721        self.has_count = true;
 722        self
 723    }
 724
 725    fn parse(
 726        &self,
 727        query: &str,
 728        range: &Option<CommandRange>,
 729        cx: &App,
 730    ) -> Option<Box<dyn Action>> {
 731        let rest = query
 732            .to_string()
 733            .strip_prefix(self.prefix)?
 734            .to_string()
 735            .chars()
 736            .zip_longest(self.suffix.to_string().chars())
 737            .skip_while(|e| e.clone().both().map(|(s, q)| s == q).unwrap_or(false))
 738            .filter_map(|e| e.left())
 739            .collect::<String>();
 740        let has_bang = rest.starts_with('!');
 741        let args = if has_bang {
 742            rest.strip_prefix('!')?.trim().to_string()
 743        } else if rest.is_empty() {
 744            "".into()
 745        } else {
 746            rest.strip_prefix(' ')?.trim().to_string()
 747        };
 748
 749        let action = if has_bang && self.bang_action.is_some() {
 750            self.bang_action.as_ref().unwrap().boxed_clone()
 751        } else if let Some(action) = self.action.as_ref() {
 752            action.boxed_clone()
 753        } else if let Some(action_name) = self.action_name {
 754            cx.build_action(action_name, None).log_err()?
 755        } else {
 756            return None;
 757        };
 758
 759        let action = if args.is_empty() {
 760            action
 761        } else {
 762            // if command does not accept args and we have args then we should do no action
 763            self.args.as_ref()?(action, args)?
 764        };
 765
 766        if let Some(range) = range {
 767            self.range.as_ref().and_then(|f| f(action, range))
 768        } else {
 769            Some(action)
 770        }
 771    }
 772
 773    // TODO: ranges with search queries
 774    fn parse_range(query: &str) -> (Option<CommandRange>, String) {
 775        let mut chars = query.chars().peekable();
 776
 777        match chars.peek() {
 778            Some('%') => {
 779                chars.next();
 780                return (
 781                    Some(CommandRange {
 782                        start: Position::Line { row: 1, offset: 0 },
 783                        end: Some(Position::LastLine { offset: 0 }),
 784                    }),
 785                    chars.collect(),
 786                );
 787            }
 788            Some('*') => {
 789                chars.next();
 790                return (
 791                    Some(CommandRange {
 792                        start: Position::Mark {
 793                            name: '<',
 794                            offset: 0,
 795                        },
 796                        end: Some(Position::Mark {
 797                            name: '>',
 798                            offset: 0,
 799                        }),
 800                    }),
 801                    chars.collect(),
 802                );
 803            }
 804            _ => {}
 805        }
 806
 807        let start = Self::parse_position(&mut chars);
 808
 809        match chars.peek() {
 810            Some(',' | ';') => {
 811                chars.next();
 812                (
 813                    Some(CommandRange {
 814                        start: start.unwrap_or(Position::CurrentLine { offset: 0 }),
 815                        end: Self::parse_position(&mut chars),
 816                    }),
 817                    chars.collect(),
 818                )
 819            }
 820            _ => (
 821                start.map(|start| CommandRange { start, end: None }),
 822                chars.collect(),
 823            ),
 824        }
 825    }
 826
 827    fn parse_position(chars: &mut Peekable<Chars>) -> Option<Position> {
 828        match chars.peek()? {
 829            '0'..='9' => {
 830                let row = Self::parse_u32(chars);
 831                Some(Position::Line {
 832                    row,
 833                    offset: Self::parse_offset(chars),
 834                })
 835            }
 836            '\'' => {
 837                chars.next();
 838                let name = chars.next()?;
 839                Some(Position::Mark {
 840                    name,
 841                    offset: Self::parse_offset(chars),
 842                })
 843            }
 844            '.' => {
 845                chars.next();
 846                Some(Position::CurrentLine {
 847                    offset: Self::parse_offset(chars),
 848                })
 849            }
 850            '+' | '-' => Some(Position::CurrentLine {
 851                offset: Self::parse_offset(chars),
 852            }),
 853            '$' => {
 854                chars.next();
 855                Some(Position::LastLine {
 856                    offset: Self::parse_offset(chars),
 857                })
 858            }
 859            _ => None,
 860        }
 861    }
 862
 863    fn parse_offset(chars: &mut Peekable<Chars>) -> i32 {
 864        let mut res: i32 = 0;
 865        while matches!(chars.peek(), Some('+' | '-')) {
 866            let sign = if chars.next().unwrap() == '+' { 1 } else { -1 };
 867            let amount = if matches!(chars.peek(), Some('0'..='9')) {
 868                (Self::parse_u32(chars) as i32).saturating_mul(sign)
 869            } else {
 870                sign
 871            };
 872            res = res.saturating_add(amount)
 873        }
 874        res
 875    }
 876
 877    fn parse_u32(chars: &mut Peekable<Chars>) -> u32 {
 878        let mut res: u32 = 0;
 879        while matches!(chars.peek(), Some('0'..='9')) {
 880            res = res
 881                .saturating_mul(10)
 882                .saturating_add(chars.next().unwrap() as u32 - '0' as u32);
 883        }
 884        res
 885    }
 886}
 887
 888#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq)]
 889enum Position {
 890    Line { row: u32, offset: i32 },
 891    Mark { name: char, offset: i32 },
 892    LastLine { offset: i32 },
 893    CurrentLine { offset: i32 },
 894}
 895
 896impl Position {
 897    fn buffer_row(
 898        &self,
 899        vim: &Vim,
 900        editor: &mut Editor,
 901        window: &mut Window,
 902        cx: &mut App,
 903    ) -> Result<MultiBufferRow> {
 904        let snapshot = editor.snapshot(window, cx);
 905        let target = match self {
 906            Position::Line { row, offset } => {
 907                if let Some(anchor) = editor.active_excerpt(cx).and_then(|(_, buffer, _)| {
 908                    editor.buffer().read(cx).buffer_point_to_anchor(
 909                        &buffer,
 910                        Point::new(row.saturating_sub(1), 0),
 911                        cx,
 912                    )
 913                }) {
 914                    anchor
 915                        .to_point(&snapshot.buffer_snapshot)
 916                        .row
 917                        .saturating_add_signed(*offset)
 918                } else {
 919                    row.saturating_add_signed(offset.saturating_sub(1))
 920                }
 921            }
 922            Position::Mark { name, offset } => {
 923                let Some(Mark::Local(anchors)) =
 924                    vim.get_mark(&name.to_string(), editor, window, cx)
 925                else {
 926                    anyhow::bail!("mark {name} not set");
 927                };
 928                let Some(mark) = anchors.last() else {
 929                    anyhow::bail!("mark {name} contains empty anchors");
 930                };
 931                mark.to_point(&snapshot.buffer_snapshot)
 932                    .row
 933                    .saturating_add_signed(*offset)
 934            }
 935            Position::LastLine { offset } => snapshot
 936                .buffer_snapshot
 937                .max_row()
 938                .0
 939                .saturating_add_signed(*offset),
 940            Position::CurrentLine { offset } => editor
 941                .selections
 942                .newest_anchor()
 943                .head()
 944                .to_point(&snapshot.buffer_snapshot)
 945                .row
 946                .saturating_add_signed(*offset),
 947        };
 948
 949        Ok(MultiBufferRow(target).min(snapshot.buffer_snapshot.max_row()))
 950    }
 951}
 952
 953#[derive(Clone, Debug, PartialEq)]
 954pub(crate) struct CommandRange {
 955    start: Position,
 956    end: Option<Position>,
 957}
 958
 959impl CommandRange {
 960    fn head(&self) -> &Position {
 961        self.end.as_ref().unwrap_or(&self.start)
 962    }
 963
 964    pub(crate) fn buffer_range(
 965        &self,
 966        vim: &Vim,
 967        editor: &mut Editor,
 968        window: &mut Window,
 969        cx: &mut App,
 970    ) -> Result<Range<MultiBufferRow>> {
 971        let start = self.start.buffer_row(vim, editor, window, cx)?;
 972        let end = if let Some(end) = self.end.as_ref() {
 973            end.buffer_row(vim, editor, window, cx)?
 974        } else {
 975            start
 976        };
 977        if end < start {
 978            anyhow::Ok(end..start)
 979        } else {
 980            anyhow::Ok(start..end)
 981        }
 982    }
 983
 984    pub fn as_count(&self) -> Option<u32> {
 985        if let CommandRange {
 986            start: Position::Line { row, offset: 0 },
 987            end: None,
 988        } = &self
 989        {
 990            Some(*row)
 991        } else {
 992            None
 993        }
 994    }
 995}
 996
 997fn generate_commands(_: &App) -> Vec<VimCommand> {
 998    vec![
 999        VimCommand::new(
1000            ("w", "rite"),
1001            workspace::Save {
1002                save_intent: Some(SaveIntent::Save),
1003            },
1004        )
1005        .bang(workspace::Save {
1006            save_intent: Some(SaveIntent::Overwrite),
1007        })
1008        .args(|action, args| {
1009            Some(
1010                VimSave {
1011                    save_intent: action
1012                        .as_any()
1013                        .downcast_ref::<workspace::Save>()
1014                        .and_then(|action| action.save_intent),
1015                    filename: args,
1016                }
1017                .boxed_clone(),
1018            )
1019        }),
1020        VimCommand::new(
1021            ("q", "uit"),
1022            workspace::CloseActiveItem {
1023                save_intent: Some(SaveIntent::Close),
1024                close_pinned: false,
1025            },
1026        )
1027        .bang(workspace::CloseActiveItem {
1028            save_intent: Some(SaveIntent::Skip),
1029            close_pinned: true,
1030        }),
1031        VimCommand::new(
1032            ("wq", ""),
1033            workspace::CloseActiveItem {
1034                save_intent: Some(SaveIntent::Save),
1035                close_pinned: false,
1036            },
1037        )
1038        .bang(workspace::CloseActiveItem {
1039            save_intent: Some(SaveIntent::Overwrite),
1040            close_pinned: true,
1041        }),
1042        VimCommand::new(
1043            ("x", "it"),
1044            workspace::CloseActiveItem {
1045                save_intent: Some(SaveIntent::SaveAll),
1046                close_pinned: false,
1047            },
1048        )
1049        .bang(workspace::CloseActiveItem {
1050            save_intent: Some(SaveIntent::Overwrite),
1051            close_pinned: true,
1052        }),
1053        VimCommand::new(
1054            ("exi", "t"),
1055            workspace::CloseActiveItem {
1056                save_intent: Some(SaveIntent::SaveAll),
1057                close_pinned: false,
1058            },
1059        )
1060        .bang(workspace::CloseActiveItem {
1061            save_intent: Some(SaveIntent::Overwrite),
1062            close_pinned: true,
1063        }),
1064        VimCommand::new(
1065            ("up", "date"),
1066            workspace::Save {
1067                save_intent: Some(SaveIntent::SaveAll),
1068            },
1069        ),
1070        VimCommand::new(
1071            ("wa", "ll"),
1072            workspace::SaveAll {
1073                save_intent: Some(SaveIntent::SaveAll),
1074            },
1075        )
1076        .bang(workspace::SaveAll {
1077            save_intent: Some(SaveIntent::Overwrite),
1078        }),
1079        VimCommand::new(
1080            ("qa", "ll"),
1081            workspace::CloseAllItemsAndPanes {
1082                save_intent: Some(SaveIntent::Close),
1083            },
1084        )
1085        .bang(workspace::CloseAllItemsAndPanes {
1086            save_intent: Some(SaveIntent::Skip),
1087        }),
1088        VimCommand::new(
1089            ("quita", "ll"),
1090            workspace::CloseAllItemsAndPanes {
1091                save_intent: Some(SaveIntent::Close),
1092            },
1093        )
1094        .bang(workspace::CloseAllItemsAndPanes {
1095            save_intent: Some(SaveIntent::Skip),
1096        }),
1097        VimCommand::new(
1098            ("xa", "ll"),
1099            workspace::CloseAllItemsAndPanes {
1100                save_intent: Some(SaveIntent::SaveAll),
1101            },
1102        )
1103        .bang(workspace::CloseAllItemsAndPanes {
1104            save_intent: Some(SaveIntent::Overwrite),
1105        }),
1106        VimCommand::new(
1107            ("wqa", "ll"),
1108            workspace::CloseAllItemsAndPanes {
1109                save_intent: Some(SaveIntent::SaveAll),
1110            },
1111        )
1112        .bang(workspace::CloseAllItemsAndPanes {
1113            save_intent: Some(SaveIntent::Overwrite),
1114        }),
1115        VimCommand::new(("cq", "uit"), zed_actions::Quit),
1116        VimCommand::new(("sp", "lit"), workspace::SplitHorizontal).args(|_, args| {
1117            Some(
1118                VimSplit {
1119                    vertical: false,
1120                    filename: args,
1121                }
1122                .boxed_clone(),
1123            )
1124        }),
1125        VimCommand::new(("vs", "plit"), workspace::SplitVertical).args(|_, args| {
1126            Some(
1127                VimSplit {
1128                    vertical: true,
1129                    filename: args,
1130                }
1131                .boxed_clone(),
1132            )
1133        }),
1134        VimCommand::new(
1135            ("bd", "elete"),
1136            workspace::CloseActiveItem {
1137                save_intent: Some(SaveIntent::Close),
1138                close_pinned: false,
1139            },
1140        )
1141        .bang(workspace::CloseActiveItem {
1142            save_intent: Some(SaveIntent::Skip),
1143            close_pinned: true,
1144        }),
1145        VimCommand::new(
1146            ("norm", "al"),
1147            VimNorm {
1148                command: "".into(),
1149                range: None,
1150            },
1151        )
1152        .args(|_, args| {
1153            Some(
1154                VimNorm {
1155                    command: args,
1156                    range: None,
1157                }
1158                .boxed_clone(),
1159            )
1160        })
1161        .range(|action, range| {
1162            let mut action: VimNorm = action.as_any().downcast_ref::<VimNorm>().unwrap().clone();
1163            action.range.replace(range.clone());
1164            Some(Box::new(action))
1165        }),
1166        VimCommand::new(("bn", "ext"), workspace::ActivateNextItem).count(),
1167        VimCommand::new(("bN", "ext"), workspace::ActivatePreviousItem).count(),
1168        VimCommand::new(("bp", "revious"), workspace::ActivatePreviousItem).count(),
1169        VimCommand::new(("bf", "irst"), workspace::ActivateItem(0)),
1170        VimCommand::new(("br", "ewind"), workspace::ActivateItem(0)),
1171        VimCommand::new(("bl", "ast"), workspace::ActivateLastItem),
1172        VimCommand::str(("buffers", ""), "tab_switcher::ToggleAll"),
1173        VimCommand::str(("ls", ""), "tab_switcher::ToggleAll"),
1174        VimCommand::new(("new", ""), workspace::NewFileSplitHorizontal),
1175        VimCommand::new(("vne", "w"), workspace::NewFileSplitVertical),
1176        VimCommand::new(("tabe", "dit"), workspace::NewFile)
1177            .args(|_action, args| Some(VimEdit { filename: args }.boxed_clone())),
1178        VimCommand::new(("tabnew", ""), workspace::NewFile)
1179            .args(|_action, args| Some(VimEdit { filename: args }.boxed_clone())),
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    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);
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                            && let Some(file) = buffer.read(cx).file()
1716                            && let Some(local) = file.as_local()
1717                            && let Some(str) = local.path().to_str()
1718                        {
1719                            ret.push_str(str)
1720                        }
1721                    });
1722                }
1723                '!' => {
1724                    if let Some(command) = &self.last_command {
1725                        ret.push_str(command)
1726                    }
1727                }
1728                _ => {}
1729            }
1730        }
1731        self.last_command = Some(ret.clone());
1732        ret
1733    }
1734
1735    pub fn shell_command_motion(
1736        &mut self,
1737        motion: Motion,
1738        times: Option<usize>,
1739        forced_motion: bool,
1740        window: &mut Window,
1741        cx: &mut Context<Vim>,
1742    ) {
1743        self.stop_recording(cx);
1744        let Some(workspace) = self.workspace(window) else {
1745            return;
1746        };
1747        let command = self.update_editor(cx, |_, editor, cx| {
1748            let snapshot = editor.snapshot(window, cx);
1749            let start = editor.selections.newest_display(cx);
1750            let text_layout_details = editor.text_layout_details(window);
1751            let (mut range, _) = motion
1752                .range(
1753                    &snapshot,
1754                    start.clone(),
1755                    times,
1756                    &text_layout_details,
1757                    forced_motion,
1758                )
1759                .unwrap_or((start.range(), MotionKind::Exclusive));
1760            if range.start != start.start {
1761                editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1762                    s.select_ranges([
1763                        range.start.to_point(&snapshot)..range.start.to_point(&snapshot)
1764                    ]);
1765                })
1766            }
1767            if range.end.row() > range.start.row() && range.end.column() != 0 {
1768                *range.end.row_mut() -= 1
1769            }
1770            if range.end.row() == range.start.row() {
1771                ".!".to_string()
1772            } else {
1773                format!(".,.+{}!", (range.end.row() - range.start.row()).0)
1774            }
1775        });
1776        if let Some(command) = command {
1777            workspace.update(cx, |workspace, cx| {
1778                command_palette::CommandPalette::toggle(workspace, &command, window, cx);
1779            });
1780        }
1781    }
1782
1783    pub fn shell_command_object(
1784        &mut self,
1785        object: Object,
1786        around: bool,
1787        window: &mut Window,
1788        cx: &mut Context<Vim>,
1789    ) {
1790        self.stop_recording(cx);
1791        let Some(workspace) = self.workspace(window) else {
1792            return;
1793        };
1794        let command = self.update_editor(cx, |_, editor, cx| {
1795            let snapshot = editor.snapshot(window, cx);
1796            let start = editor.selections.newest_display(cx);
1797            let range = object
1798                .range(&snapshot, start.clone(), around, None)
1799                .unwrap_or(start.range());
1800            if range.start != start.start {
1801                editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1802                    s.select_ranges([
1803                        range.start.to_point(&snapshot)..range.start.to_point(&snapshot)
1804                    ]);
1805                })
1806            }
1807            if range.end.row() == range.start.row() {
1808                ".!".to_string()
1809            } else {
1810                format!(".,.+{}!", (range.end.row() - range.start.row()).0)
1811            }
1812        });
1813        if let Some(command) = command {
1814            workspace.update(cx, |workspace, cx| {
1815                command_palette::CommandPalette::toggle(workspace, &command, window, cx);
1816            });
1817        }
1818    }
1819}
1820
1821impl ShellExec {
1822    pub fn parse(query: &str, range: Option<CommandRange>) -> Option<Box<dyn Action>> {
1823        let (before, after) = query.split_once('!')?;
1824        let before = before.trim();
1825
1826        if !"read".starts_with(before) {
1827            return None;
1828        }
1829
1830        Some(
1831            ShellExec {
1832                command: after.trim().to_string(),
1833                range,
1834                is_read: !before.is_empty(),
1835            }
1836            .boxed_clone(),
1837        )
1838    }
1839
1840    pub fn run(&self, vim: &mut Vim, window: &mut Window, cx: &mut Context<Vim>) {
1841        let Some(workspace) = vim.workspace(window) else {
1842            return;
1843        };
1844
1845        let project = workspace.read(cx).project().clone();
1846        let command = vim.prepare_shell_command(&self.command, window, cx);
1847
1848        if self.range.is_none() && !self.is_read {
1849            workspace.update(cx, |workspace, cx| {
1850                let project = workspace.project().read(cx);
1851                let cwd = project.first_project_directory(cx);
1852                let shell = project.terminal_settings(&cwd, cx).shell.clone();
1853
1854                let spawn_in_terminal = SpawnInTerminal {
1855                    id: TaskId("vim".to_string()),
1856                    full_label: command.clone(),
1857                    label: command.clone(),
1858                    command: Some(command.clone()),
1859                    args: Vec::new(),
1860                    command_label: command.clone(),
1861                    cwd,
1862                    env: HashMap::default(),
1863                    use_new_terminal: true,
1864                    allow_concurrent_runs: true,
1865                    reveal: RevealStrategy::NoFocus,
1866                    reveal_target: RevealTarget::Dock,
1867                    hide: HideStrategy::Never,
1868                    shell,
1869                    show_summary: false,
1870                    show_command: false,
1871                    show_rerun: false,
1872                };
1873
1874                let task_status = workspace.spawn_in_terminal(spawn_in_terminal, window, cx);
1875                cx.background_spawn(async move {
1876                    match task_status.await {
1877                        Some(Ok(status)) => {
1878                            if status.success() {
1879                                log::debug!("Vim shell exec succeeded");
1880                            } else {
1881                                log::debug!("Vim shell exec failed, code: {:?}", status.code());
1882                            }
1883                        }
1884                        Some(Err(e)) => log::error!("Vim shell exec failed: {e}"),
1885                        None => log::debug!("Vim shell exec got cancelled"),
1886                    }
1887                })
1888                .detach();
1889            });
1890            return;
1891        };
1892
1893        let mut input_snapshot = None;
1894        let mut input_range = None;
1895        let mut needs_newline_prefix = false;
1896        vim.update_editor(cx, |vim, editor, cx| {
1897            let snapshot = editor.buffer().read(cx).snapshot(cx);
1898            let range = if let Some(range) = self.range.clone() {
1899                let Some(range) = range.buffer_range(vim, editor, window, cx).log_err() else {
1900                    return;
1901                };
1902                Point::new(range.start.0, 0)
1903                    ..snapshot.clip_point(Point::new(range.end.0 + 1, 0), Bias::Right)
1904            } else {
1905                let mut end = editor.selections.newest::<Point>(cx).range().end;
1906                end = snapshot.clip_point(Point::new(end.row + 1, 0), Bias::Right);
1907                needs_newline_prefix = end == snapshot.max_point();
1908                end..end
1909            };
1910            if self.is_read {
1911                input_range =
1912                    Some(snapshot.anchor_after(range.end)..snapshot.anchor_after(range.end));
1913            } else {
1914                input_range =
1915                    Some(snapshot.anchor_before(range.start)..snapshot.anchor_after(range.end));
1916            }
1917            editor.highlight_rows::<ShellExec>(
1918                input_range.clone().unwrap(),
1919                cx.theme().status().unreachable_background,
1920                Default::default(),
1921                cx,
1922            );
1923
1924            if !self.is_read {
1925                input_snapshot = Some(snapshot)
1926            }
1927        });
1928
1929        let Some(range) = input_range else { return };
1930
1931        let mut process = project.read(cx).exec_in_shell(command, cx);
1932        process.stdout(Stdio::piped());
1933        process.stderr(Stdio::piped());
1934
1935        if input_snapshot.is_some() {
1936            process.stdin(Stdio::piped());
1937        } else {
1938            process.stdin(Stdio::null());
1939        };
1940
1941        util::set_pre_exec_to_start_new_session(&mut process);
1942        let is_read = self.is_read;
1943
1944        let task = cx.spawn_in(window, async move |vim, cx| {
1945            let Some(mut running) = process.spawn().log_err() else {
1946                vim.update_in(cx, |vim, window, cx| {
1947                    vim.cancel_running_command(window, cx);
1948                })
1949                .log_err();
1950                return;
1951            };
1952
1953            if let Some(mut stdin) = running.stdin.take()
1954                && let Some(snapshot) = input_snapshot
1955            {
1956                let range = range.clone();
1957                cx.background_spawn(async move {
1958                    for chunk in snapshot.text_for_range(range) {
1959                        if stdin.write_all(chunk.as_bytes()).log_err().is_none() {
1960                            return;
1961                        }
1962                    }
1963                    stdin.flush().log_err();
1964                })
1965                .detach();
1966            };
1967
1968            let output = cx
1969                .background_spawn(async move { running.wait_with_output() })
1970                .await;
1971
1972            let Some(output) = output.log_err() else {
1973                vim.update_in(cx, |vim, window, cx| {
1974                    vim.cancel_running_command(window, cx);
1975                })
1976                .log_err();
1977                return;
1978            };
1979            let mut text = String::new();
1980            if needs_newline_prefix {
1981                text.push('\n');
1982            }
1983            text.push_str(&String::from_utf8_lossy(&output.stdout));
1984            text.push_str(&String::from_utf8_lossy(&output.stderr));
1985            if !text.is_empty() && text.chars().last() != Some('\n') {
1986                text.push('\n');
1987            }
1988
1989            vim.update_in(cx, |vim, window, cx| {
1990                vim.update_editor(cx, |_, editor, cx| {
1991                    editor.transact(window, cx, |editor, window, cx| {
1992                        editor.edit([(range.clone(), text)], cx);
1993                        let snapshot = editor.buffer().read(cx).snapshot(cx);
1994                        editor.change_selections(Default::default(), window, cx, |s| {
1995                            let point = if is_read {
1996                                let point = range.end.to_point(&snapshot);
1997                                Point::new(point.row.saturating_sub(1), 0)
1998                            } else {
1999                                let point = range.start.to_point(&snapshot);
2000                                Point::new(point.row, 0)
2001                            };
2002                            s.select_ranges([point..point]);
2003                        })
2004                    })
2005                });
2006                vim.cancel_running_command(window, cx);
2007            })
2008            .log_err();
2009        });
2010        vim.running_command.replace(task);
2011    }
2012}
2013
2014#[cfg(test)]
2015mod test {
2016    use std::path::Path;
2017
2018    use crate::{
2019        VimAddon,
2020        state::Mode,
2021        test::{NeovimBackedTestContext, VimTestContext},
2022    };
2023    use editor::Editor;
2024    use gpui::{Context, TestAppContext};
2025    use indoc::indoc;
2026    use util::path;
2027    use workspace::Workspace;
2028
2029    #[gpui::test]
2030    async fn test_command_basics(cx: &mut TestAppContext) {
2031        let mut cx = NeovimBackedTestContext::new(cx).await;
2032
2033        cx.set_shared_state(indoc! {"
2034            ˇa
2035            b
2036            c"})
2037            .await;
2038
2039        cx.simulate_shared_keystrokes(": j enter").await;
2040
2041        // hack: our cursor positioning after a join command is wrong
2042        cx.simulate_shared_keystrokes("^").await;
2043        cx.shared_state().await.assert_eq(indoc! {
2044            "ˇa b
2045            c"
2046        });
2047    }
2048
2049    #[gpui::test]
2050    async fn test_command_goto(cx: &mut TestAppContext) {
2051        let mut cx = NeovimBackedTestContext::new(cx).await;
2052
2053        cx.set_shared_state(indoc! {"
2054            ˇa
2055            b
2056            c"})
2057            .await;
2058        cx.simulate_shared_keystrokes(": 3 enter").await;
2059        cx.shared_state().await.assert_eq(indoc! {"
2060            a
2061            b
2062            ˇc"});
2063    }
2064
2065    #[gpui::test]
2066    async fn test_command_replace(cx: &mut TestAppContext) {
2067        let mut cx = NeovimBackedTestContext::new(cx).await;
2068
2069        cx.set_shared_state(indoc! {"
2070            ˇa
2071            b
2072            b
2073            c"})
2074            .await;
2075        cx.simulate_shared_keystrokes(": % s / b / d enter").await;
2076        cx.shared_state().await.assert_eq(indoc! {"
2077            a
2078            d
2079            ˇd
2080            c"});
2081        cx.simulate_shared_keystrokes(": % s : . : \\ 0 \\ 0 enter")
2082            .await;
2083        cx.shared_state().await.assert_eq(indoc! {"
2084            aa
2085            dd
2086            dd
2087            ˇcc"});
2088        cx.simulate_shared_keystrokes("k : s / d d / e e enter")
2089            .await;
2090        cx.shared_state().await.assert_eq(indoc! {"
2091            aa
2092            dd
2093            ˇee
2094            cc"});
2095    }
2096
2097    #[gpui::test]
2098    async fn test_command_search(cx: &mut TestAppContext) {
2099        let mut cx = NeovimBackedTestContext::new(cx).await;
2100
2101        cx.set_shared_state(indoc! {"
2102                ˇa
2103                b
2104                a
2105                c"})
2106            .await;
2107        cx.simulate_shared_keystrokes(": / b enter").await;
2108        cx.shared_state().await.assert_eq(indoc! {"
2109                a
2110                ˇb
2111                a
2112                c"});
2113        cx.simulate_shared_keystrokes(": ? a enter").await;
2114        cx.shared_state().await.assert_eq(indoc! {"
2115                ˇa
2116                b
2117                a
2118                c"});
2119    }
2120
2121    #[gpui::test]
2122    async fn test_command_write(cx: &mut TestAppContext) {
2123        let mut cx = VimTestContext::new(cx, true).await;
2124        let path = Path::new(path!("/root/dir/file.rs"));
2125        let fs = cx.workspace(|workspace, _, cx| workspace.project().read(cx).fs().clone());
2126
2127        cx.simulate_keystrokes("i @ escape");
2128        cx.simulate_keystrokes(": w enter");
2129
2130        assert_eq!(fs.load(path).await.unwrap().replace("\r\n", "\n"), "@\n");
2131
2132        fs.as_fake().insert_file(path, b"oops\n".to_vec()).await;
2133
2134        // conflict!
2135        cx.simulate_keystrokes("i @ escape");
2136        cx.simulate_keystrokes(": w enter");
2137        cx.simulate_prompt_answer("Cancel");
2138
2139        assert_eq!(fs.load(path).await.unwrap().replace("\r\n", "\n"), "oops\n");
2140        assert!(!cx.has_pending_prompt());
2141        cx.simulate_keystrokes(": w ! enter");
2142        assert!(!cx.has_pending_prompt());
2143        assert_eq!(fs.load(path).await.unwrap().replace("\r\n", "\n"), "@@\n");
2144    }
2145
2146    #[gpui::test]
2147    async fn test_command_quit(cx: &mut TestAppContext) {
2148        let mut cx = VimTestContext::new(cx, true).await;
2149
2150        cx.simulate_keystrokes(": n e w enter");
2151        cx.workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 2));
2152        cx.simulate_keystrokes(": q enter");
2153        cx.workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 1));
2154        cx.simulate_keystrokes(": n e w enter");
2155        cx.workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 2));
2156        cx.simulate_keystrokes(": q a enter");
2157        cx.workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 0));
2158    }
2159
2160    #[gpui::test]
2161    async fn test_offsets(cx: &mut TestAppContext) {
2162        let mut cx = NeovimBackedTestContext::new(cx).await;
2163
2164        cx.set_shared_state("ˇ1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n")
2165            .await;
2166
2167        cx.simulate_shared_keystrokes(": + enter").await;
2168        cx.shared_state()
2169            .await
2170            .assert_eq("1\nˇ2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n");
2171
2172        cx.simulate_shared_keystrokes(": 1 0 - enter").await;
2173        cx.shared_state()
2174            .await
2175            .assert_eq("1\n2\n3\n4\n5\n6\n7\n8\nˇ9\n10\n11\n");
2176
2177        cx.simulate_shared_keystrokes(": . - 2 enter").await;
2178        cx.shared_state()
2179            .await
2180            .assert_eq("1\n2\n3\n4\n5\n6\nˇ7\n8\n9\n10\n11\n");
2181
2182        cx.simulate_shared_keystrokes(": % enter").await;
2183        cx.shared_state()
2184            .await
2185            .assert_eq("1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\nˇ");
2186    }
2187
2188    #[gpui::test]
2189    async fn test_command_ranges(cx: &mut TestAppContext) {
2190        let mut cx = NeovimBackedTestContext::new(cx).await;
2191
2192        cx.set_shared_state("ˇ1\n2\n3\n4\n4\n3\n2\n1").await;
2193
2194        cx.simulate_shared_keystrokes(": 2 , 4 d enter").await;
2195        cx.shared_state().await.assert_eq("1\nˇ4\n3\n2\n1");
2196
2197        cx.simulate_shared_keystrokes(": 2 , 4 s o r t enter").await;
2198        cx.shared_state().await.assert_eq("1\nˇ2\n3\n4\n1");
2199
2200        cx.simulate_shared_keystrokes(": 2 , 4 j o i n enter").await;
2201        cx.shared_state().await.assert_eq("1\nˇ2 3 4\n1");
2202    }
2203
2204    #[gpui::test]
2205    async fn test_command_visual_replace(cx: &mut TestAppContext) {
2206        let mut cx = NeovimBackedTestContext::new(cx).await;
2207
2208        cx.set_shared_state("ˇ1\n2\n3\n4\n4\n3\n2\n1").await;
2209
2210        cx.simulate_shared_keystrokes("v 2 j : s / . / k enter")
2211            .await;
2212        cx.shared_state().await.assert_eq("k\nk\nˇk\n4\n4\n3\n2\n1");
2213    }
2214
2215    #[track_caller]
2216    fn assert_active_item(
2217        workspace: &mut Workspace,
2218        expected_path: &str,
2219        expected_text: &str,
2220        cx: &mut Context<Workspace>,
2221    ) {
2222        let active_editor = workspace.active_item_as::<Editor>(cx).unwrap();
2223
2224        let buffer = active_editor
2225            .read(cx)
2226            .buffer()
2227            .read(cx)
2228            .as_singleton()
2229            .unwrap();
2230
2231        let text = buffer.read(cx).text();
2232        let file = buffer.read(cx).file().unwrap();
2233        let file_path = file.as_local().unwrap().abs_path(cx);
2234
2235        assert_eq!(text, expected_text);
2236        assert_eq!(file_path, Path::new(expected_path));
2237    }
2238
2239    #[gpui::test]
2240    async fn test_command_gf(cx: &mut TestAppContext) {
2241        let mut cx = VimTestContext::new(cx, true).await;
2242
2243        // Assert base state, that we're in /root/dir/file.rs
2244        cx.workspace(|workspace, _, cx| {
2245            assert_active_item(workspace, path!("/root/dir/file.rs"), "", cx);
2246        });
2247
2248        // Insert a new file
2249        let fs = cx.workspace(|workspace, _, cx| workspace.project().read(cx).fs().clone());
2250        fs.as_fake()
2251            .insert_file(
2252                path!("/root/dir/file2.rs"),
2253                "This is file2.rs".as_bytes().to_vec(),
2254            )
2255            .await;
2256        fs.as_fake()
2257            .insert_file(
2258                path!("/root/dir/file3.rs"),
2259                "go to file3".as_bytes().to_vec(),
2260            )
2261            .await;
2262
2263        // Put the path to the second file into the currently open buffer
2264        cx.set_state(indoc! {"go to fiˇle2.rs"}, Mode::Normal);
2265
2266        // Go to file2.rs
2267        cx.simulate_keystrokes("g f");
2268
2269        // We now have two items
2270        cx.workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 2));
2271        cx.workspace(|workspace, _, cx| {
2272            assert_active_item(
2273                workspace,
2274                path!("/root/dir/file2.rs"),
2275                "This is file2.rs",
2276                cx,
2277            );
2278        });
2279
2280        // Update editor to point to `file2.rs`
2281        cx.editor =
2282            cx.workspace(|workspace, _, cx| workspace.active_item_as::<Editor>(cx).unwrap());
2283
2284        // Put the path to the third file into the currently open buffer,
2285        // but remove its suffix, because we want that lookup to happen automatically.
2286        cx.set_state(indoc! {"go to fiˇle3"}, Mode::Normal);
2287
2288        // Go to file3.rs
2289        cx.simulate_keystrokes("g f");
2290
2291        // We now have three items
2292        cx.workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 3));
2293        cx.workspace(|workspace, _, cx| {
2294            assert_active_item(workspace, path!("/root/dir/file3.rs"), "go to file3", cx);
2295        });
2296    }
2297
2298    #[gpui::test]
2299    async fn test_w_command(cx: &mut TestAppContext) {
2300        let mut cx = VimTestContext::new(cx, true).await;
2301
2302        cx.workspace(|workspace, _, cx| {
2303            assert_active_item(workspace, path!("/root/dir/file.rs"), "", cx);
2304        });
2305
2306        cx.simulate_keystrokes(": w space other.rs");
2307        cx.simulate_keystrokes("enter");
2308
2309        cx.workspace(|workspace, _, cx| {
2310            assert_active_item(workspace, path!("/root/other.rs"), "", cx);
2311        });
2312
2313        cx.simulate_keystrokes(": w space dir/file.rs");
2314        cx.simulate_keystrokes("enter");
2315
2316        cx.simulate_prompt_answer("Replace");
2317        cx.run_until_parked();
2318
2319        cx.workspace(|workspace, _, cx| {
2320            assert_active_item(workspace, path!("/root/dir/file.rs"), "", cx);
2321        });
2322
2323        cx.simulate_keystrokes(": w ! space other.rs");
2324        cx.simulate_keystrokes("enter");
2325
2326        cx.workspace(|workspace, _, cx| {
2327            assert_active_item(workspace, path!("/root/other.rs"), "", cx);
2328        });
2329    }
2330
2331    #[gpui::test]
2332    async fn test_command_matching_lines(cx: &mut TestAppContext) {
2333        let mut cx = NeovimBackedTestContext::new(cx).await;
2334
2335        cx.set_shared_state(indoc! {"
2336            ˇa
2337            b
2338            a
2339            b
2340            a
2341        "})
2342            .await;
2343
2344        cx.simulate_shared_keystrokes(":").await;
2345        cx.simulate_shared_keystrokes("g / a / d").await;
2346        cx.simulate_shared_keystrokes("enter").await;
2347
2348        cx.shared_state().await.assert_eq(indoc! {"
2349            b
2350            b
2351            ˇ"});
2352
2353        cx.simulate_shared_keystrokes("u").await;
2354
2355        cx.shared_state().await.assert_eq(indoc! {"
2356            ˇa
2357            b
2358            a
2359            b
2360            a
2361        "});
2362
2363        cx.simulate_shared_keystrokes(":").await;
2364        cx.simulate_shared_keystrokes("v / a / d").await;
2365        cx.simulate_shared_keystrokes("enter").await;
2366
2367        cx.shared_state().await.assert_eq(indoc! {"
2368            a
2369            a
2370            ˇa"});
2371    }
2372
2373    #[gpui::test]
2374    async fn test_del_marks(cx: &mut TestAppContext) {
2375        let mut cx = NeovimBackedTestContext::new(cx).await;
2376
2377        cx.set_shared_state(indoc! {"
2378            ˇa
2379            b
2380            a
2381            b
2382            a
2383        "})
2384            .await;
2385
2386        cx.simulate_shared_keystrokes("m a").await;
2387
2388        let mark = cx.update_editor(|editor, window, cx| {
2389            let vim = editor.addon::<VimAddon>().unwrap().entity.clone();
2390            vim.update(cx, |vim, cx| vim.get_mark("a", editor, window, cx))
2391        });
2392        assert!(mark.is_some());
2393
2394        cx.simulate_shared_keystrokes(": d e l m space a").await;
2395        cx.simulate_shared_keystrokes("enter").await;
2396
2397        let mark = cx.update_editor(|editor, window, cx| {
2398            let vim = editor.addon::<VimAddon>().unwrap().entity.clone();
2399            vim.update(cx, |vim, cx| vim.get_mark("a", editor, window, cx))
2400        });
2401        assert!(mark.is_none())
2402    }
2403
2404    #[gpui::test]
2405    async fn test_normal_command(cx: &mut TestAppContext) {
2406        let mut cx = NeovimBackedTestContext::new(cx).await;
2407
2408        cx.set_shared_state(indoc! {"
2409            The quick
2410            brown« fox
2411            jumpsˇ» over
2412            the lazy dog
2413        "})
2414            .await;
2415
2416        cx.simulate_shared_keystrokes(": n o r m space w C w o r d")
2417            .await;
2418        cx.simulate_shared_keystrokes("enter").await;
2419
2420        cx.shared_state().await.assert_eq(indoc! {"
2421            The quick
2422            brown word
2423            jumps worˇd
2424            the lazy dog
2425        "});
2426
2427        cx.simulate_shared_keystrokes(": n o r m space _ w c i w t e s t")
2428            .await;
2429        cx.simulate_shared_keystrokes("enter").await;
2430
2431        cx.shared_state().await.assert_eq(indoc! {"
2432            The quick
2433            brown word
2434            jumps tesˇt
2435            the lazy dog
2436        "});
2437
2438        cx.simulate_shared_keystrokes("_ l v l : n o r m space s l a")
2439            .await;
2440        cx.simulate_shared_keystrokes("enter").await;
2441
2442        cx.shared_state().await.assert_eq(indoc! {"
2443            The quick
2444            brown word
2445            lˇaumps test
2446            the lazy dog
2447        "});
2448
2449        cx.set_shared_state(indoc! {"
2450            ˇThe quick
2451            brown fox
2452            jumps over
2453            the lazy dog
2454        "})
2455            .await;
2456
2457        cx.simulate_shared_keystrokes("c i w M y escape").await;
2458
2459        cx.shared_state().await.assert_eq(indoc! {"
2460            Mˇy quick
2461            brown fox
2462            jumps over
2463            the lazy dog
2464        "});
2465
2466        cx.simulate_shared_keystrokes(": n o r m space u").await;
2467        cx.simulate_shared_keystrokes("enter").await;
2468
2469        cx.shared_state().await.assert_eq(indoc! {"
2470            ˇThe quick
2471            brown fox
2472            jumps over
2473            the lazy dog
2474        "});
2475        // Once ctrl-v to input character literals is added there should be a test for redo
2476    }
2477
2478    #[gpui::test]
2479    async fn test_command_tabnew(cx: &mut TestAppContext) {
2480        let mut cx = VimTestContext::new(cx, true).await;
2481
2482        // Create a new file to ensure that, when the filename is used with
2483        // `:tabnew`, it opens the existing file in a new tab.
2484        let fs = cx.workspace(|workspace, _, cx| workspace.project().read(cx).fs().clone());
2485        fs.as_fake()
2486            .insert_file(path!("/root/dir/file_2.rs"), "file_2".as_bytes().to_vec())
2487            .await;
2488
2489        cx.simulate_keystrokes(": tabnew");
2490        cx.simulate_keystrokes("enter");
2491        cx.workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 2));
2492
2493        // Assert that the new tab is empty and not associated with any file, as
2494        // no file path was provided to the `:tabnew` command.
2495        cx.workspace(|workspace, _window, cx| {
2496            let active_editor = workspace.active_item_as::<Editor>(cx).unwrap();
2497            let buffer = active_editor
2498                .read(cx)
2499                .buffer()
2500                .read(cx)
2501                .as_singleton()
2502                .unwrap();
2503
2504            assert!(&buffer.read(cx).file().is_none());
2505        });
2506
2507        // Leverage the filename as an argument to the `:tabnew` command,
2508        // ensuring that the file, instead of an empty buffer, is opened in a
2509        // new tab.
2510        cx.simulate_keystrokes(": tabnew space dir/file_2.rs");
2511        cx.simulate_keystrokes("enter");
2512
2513        cx.workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 3));
2514        cx.workspace(|workspace, _, cx| {
2515            assert_active_item(workspace, path!("/root/dir/file_2.rs"), "file_2", cx);
2516        });
2517
2518        // If the `filename` argument provided to the `:tabnew` command is for a
2519        // file that doesn't yet exist, it should still associate the buffer
2520        // with that file path, so that when the buffer contents are saved, the
2521        // file is created.
2522        cx.simulate_keystrokes(": tabnew space dir/file_3.rs");
2523        cx.simulate_keystrokes("enter");
2524
2525        cx.workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 4));
2526        cx.workspace(|workspace, _, cx| {
2527            assert_active_item(workspace, path!("/root/dir/file_3.rs"), "", cx);
2528        });
2529    }
2530
2531    #[gpui::test]
2532    async fn test_command_tabedit(cx: &mut TestAppContext) {
2533        let mut cx = VimTestContext::new(cx, true).await;
2534
2535        // Create a new file to ensure that, when the filename is used with
2536        // `:tabedit`, it opens the existing file in a new tab.
2537        let fs = cx.workspace(|workspace, _, cx| workspace.project().read(cx).fs().clone());
2538        fs.as_fake()
2539            .insert_file(path!("/root/dir/file_2.rs"), "file_2".as_bytes().to_vec())
2540            .await;
2541
2542        cx.simulate_keystrokes(": tabedit");
2543        cx.simulate_keystrokes("enter");
2544        cx.workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 2));
2545
2546        // Assert that the new tab is empty and not associated with any file, as
2547        // no file path was provided to the `:tabedit` command.
2548        cx.workspace(|workspace, _window, cx| {
2549            let active_editor = workspace.active_item_as::<Editor>(cx).unwrap();
2550            let buffer = active_editor
2551                .read(cx)
2552                .buffer()
2553                .read(cx)
2554                .as_singleton()
2555                .unwrap();
2556
2557            assert!(&buffer.read(cx).file().is_none());
2558        });
2559
2560        // Leverage the filename as an argument to the `:tabedit` command,
2561        // ensuring that the file, instead of an empty buffer, is opened in a
2562        // new tab.
2563        cx.simulate_keystrokes(": tabedit space dir/file_2.rs");
2564        cx.simulate_keystrokes("enter");
2565
2566        cx.workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 3));
2567        cx.workspace(|workspace, _, cx| {
2568            assert_active_item(workspace, path!("/root/dir/file_2.rs"), "file_2", cx);
2569        });
2570
2571        // If the `filename` argument provided to the `:tabedit` command is for a
2572        // file that doesn't yet exist, it should still associate the buffer
2573        // with that file path, so that when the buffer contents are saved, the
2574        // file is created.
2575        cx.simulate_keystrokes(": tabedit space dir/file_3.rs");
2576        cx.simulate_keystrokes("enter");
2577
2578        cx.workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 4));
2579        cx.workspace(|workspace, _, cx| {
2580            assert_active_item(workspace, path!("/root/dir/file_3.rs"), "", cx);
2581        });
2582    }
2583}