command.rs

   1use anyhow::{Result, anyhow};
   2use collections::HashMap;
   3use command_palette_hooks::CommandInterceptResult;
   4use editor::{
   5    Bias, Editor, ToPoint,
   6    actions::{SortLinesCaseInsensitive, SortLinesCaseSensitive},
   7    display_map::ToDisplayPoint,
   8    scroll::Autoscroll,
   9};
  10use gpui::{Action, App, AppContext as _, Context, Global, Window, actions, impl_internal_actions};
  11use itertools::Itertools;
  12use language::Point;
  13use multi_buffer::MultiBufferRow;
  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    process::Stdio,
  23    str::Chars,
  24    sync::OnceLock,
  25    time::Instant,
  26};
  27use task::{HideStrategy, RevealStrategy, SpawnInTerminal, TaskId};
  28use ui::ActiveTheme;
  29use util::ResultExt;
  30use workspace::{SaveIntent, notifications::NotifyResultExt};
  31use zed_actions::RevealTarget;
  32
  33use crate::{
  34    ToggleMarksView, ToggleRegistersView, Vim,
  35    motion::{EndOfDocument, Motion, MotionKind, StartOfDocument},
  36    normal::{
  37        JoinLines,
  38        search::{FindCommand, ReplaceCommand, Replacement},
  39    },
  40    object::Object,
  41    state::{Mark, Mode},
  42    visual::VisualDeleteLine,
  43};
  44
  45#[derive(Clone, Debug, PartialEq)]
  46pub struct GoToLine {
  47    range: CommandRange,
  48}
  49
  50#[derive(Clone, Debug, PartialEq)]
  51pub struct YankCommand {
  52    range: CommandRange,
  53}
  54
  55#[derive(Clone, Debug, PartialEq)]
  56pub struct WithRange {
  57    restore_selection: bool,
  58    range: CommandRange,
  59    action: WrappedAction,
  60}
  61
  62#[derive(Clone, Debug, PartialEq)]
  63pub struct WithCount {
  64    count: u32,
  65    action: WrappedAction,
  66}
  67
  68#[derive(Clone, Deserialize, JsonSchema, PartialEq)]
  69pub enum VimOption {
  70    Wrap(bool),
  71    Number(bool),
  72    RelativeNumber(bool),
  73}
  74
  75impl VimOption {
  76    fn possible_commands(query: &str) -> Vec<CommandInterceptResult> {
  77        let mut prefix_of_options = Vec::new();
  78        let mut options = query.split(" ").collect::<Vec<_>>();
  79        let prefix = options.pop().unwrap_or_default();
  80        for option in options {
  81            if let Some(opt) = Self::from(option) {
  82                prefix_of_options.push(opt)
  83            } else {
  84                return vec![];
  85            }
  86        }
  87
  88        Self::possibilities(&prefix)
  89            .map(|possible| {
  90                let mut options = prefix_of_options.clone();
  91                options.push(possible);
  92
  93                CommandInterceptResult {
  94                    string: format!(
  95                        "set {}",
  96                        options.iter().map(|opt| opt.to_string()).join(" ")
  97                    ),
  98                    action: VimSet { options }.boxed_clone(),
  99                    positions: vec![],
 100                }
 101            })
 102            .collect()
 103    }
 104
 105    fn possibilities(query: &str) -> impl Iterator<Item = Self> + '_ {
 106        [
 107            (None, VimOption::Wrap(true)),
 108            (None, VimOption::Wrap(false)),
 109            (None, VimOption::Number(true)),
 110            (None, VimOption::Number(false)),
 111            (None, VimOption::RelativeNumber(true)),
 112            (None, VimOption::RelativeNumber(false)),
 113            (Some("rnu"), VimOption::RelativeNumber(true)),
 114            (Some("nornu"), VimOption::RelativeNumber(false)),
 115        ]
 116        .into_iter()
 117        .filter(move |(prefix, option)| prefix.unwrap_or(option.to_string()).starts_with(query))
 118        .map(|(_, option)| option)
 119    }
 120
 121    fn from(option: &str) -> Option<Self> {
 122        match option {
 123            "wrap" => Some(Self::Wrap(true)),
 124            "nowrap" => Some(Self::Wrap(false)),
 125
 126            "number" => Some(Self::Number(true)),
 127            "nu" => Some(Self::Number(true)),
 128            "nonumber" => Some(Self::Number(false)),
 129            "nonu" => Some(Self::Number(false)),
 130
 131            "relativenumber" => Some(Self::RelativeNumber(true)),
 132            "rnu" => Some(Self::RelativeNumber(true)),
 133            "norelativenumber" => Some(Self::RelativeNumber(false)),
 134            "nornu" => Some(Self::RelativeNumber(false)),
 135
 136            _ => None,
 137        }
 138    }
 139
 140    fn to_string(&self) -> &'static str {
 141        match self {
 142            VimOption::Wrap(true) => "wrap",
 143            VimOption::Wrap(false) => "nowrap",
 144            VimOption::Number(true) => "number",
 145            VimOption::Number(false) => "nonumber",
 146            VimOption::RelativeNumber(true) => "relativenumber",
 147            VimOption::RelativeNumber(false) => "norelativenumber",
 148        }
 149    }
 150}
 151
 152#[derive(Clone, Deserialize, JsonSchema, PartialEq)]
 153pub struct VimSet {
 154    options: Vec<VimOption>,
 155}
 156
 157#[derive(Debug)]
 158struct WrappedAction(Box<dyn Action>);
 159
 160actions!(vim, [VisualCommand, CountCommand, ShellCommand]);
 161impl_internal_actions!(
 162    vim,
 163    [
 164        GoToLine,
 165        YankCommand,
 166        WithRange,
 167        WithCount,
 168        OnMatchingLines,
 169        ShellExec,
 170        VimSet,
 171    ]
 172);
 173
 174impl PartialEq for WrappedAction {
 175    fn eq(&self, other: &Self) -> bool {
 176        self.0.partial_eq(&*other.0)
 177    }
 178}
 179
 180impl Clone for WrappedAction {
 181    fn clone(&self) -> Self {
 182        Self(self.0.boxed_clone())
 183    }
 184}
 185
 186impl Deref for WrappedAction {
 187    type Target = dyn Action;
 188    fn deref(&self) -> &dyn Action {
 189        &*self.0
 190    }
 191}
 192
 193pub fn register(editor: &mut Editor, cx: &mut Context<Vim>) {
 194    // Vim::action(editor, cx, |vim, action: &StartOfLine, window, cx| {
 195    Vim::action(editor, cx, |vim, action: &VimSet, window, cx| {
 196        for option in action.options.iter() {
 197            vim.update_editor(window, cx, |_, editor, _, cx| match option {
 198                VimOption::Wrap(true) => {
 199                    editor
 200                        .set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
 201                }
 202                VimOption::Wrap(false) => {
 203                    editor.set_soft_wrap_mode(language::language_settings::SoftWrap::None, cx);
 204                }
 205                VimOption::Number(enabled) => {
 206                    editor.set_show_line_numbers(*enabled, cx);
 207                }
 208                VimOption::RelativeNumber(enabled) => {
 209                    editor.set_relative_line_number(Some(*enabled), cx);
 210                }
 211            });
 212        }
 213    });
 214    Vim::action(editor, cx, |vim, _: &VisualCommand, window, cx| {
 215        let Some(workspace) = vim.workspace(window) else {
 216            return;
 217        };
 218        workspace.update(cx, |workspace, cx| {
 219            command_palette::CommandPalette::toggle(workspace, "'<,'>", window, cx);
 220        })
 221    });
 222
 223    Vim::action(editor, cx, |vim, _: &ShellCommand, window, cx| {
 224        let Some(workspace) = vim.workspace(window) else {
 225            return;
 226        };
 227        workspace.update(cx, |workspace, cx| {
 228            command_palette::CommandPalette::toggle(workspace, "'<,'>!", window, cx);
 229        })
 230    });
 231
 232    Vim::action(editor, cx, |vim, _: &CountCommand, window, cx| {
 233        let Some(workspace) = vim.workspace(window) else {
 234            return;
 235        };
 236        let count = Vim::take_count(cx).unwrap_or(1);
 237        let n = if count > 1 {
 238            format!(".,.+{}", count.saturating_sub(1))
 239        } else {
 240            ".".to_string()
 241        };
 242        workspace.update(cx, |workspace, cx| {
 243            command_palette::CommandPalette::toggle(workspace, &n, window, cx);
 244        })
 245    });
 246
 247    Vim::action(editor, cx, |vim, action: &GoToLine, window, cx| {
 248        vim.switch_mode(Mode::Normal, false, window, cx);
 249        let result = vim.update_editor(window, cx, |vim, editor, window, cx| {
 250            let snapshot = editor.snapshot(window, cx);
 251            let buffer_row = action.range.head().buffer_row(vim, editor, window, cx)?;
 252            let current = editor.selections.newest::<Point>(cx);
 253            let target = snapshot
 254                .buffer_snapshot
 255                .clip_point(Point::new(buffer_row.0, current.head().column), Bias::Left);
 256            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 257                s.select_ranges([target..target]);
 258            });
 259
 260            anyhow::Ok(())
 261        });
 262        if let Some(e @ Err(_)) = result {
 263            let Some(workspace) = vim.workspace(window) else {
 264                return;
 265            };
 266            workspace.update(cx, |workspace, cx| {
 267                e.notify_err(workspace, cx);
 268            });
 269            return;
 270        }
 271    });
 272
 273    Vim::action(editor, cx, |vim, action: &YankCommand, window, cx| {
 274        vim.update_editor(window, cx, |vim, editor, window, cx| {
 275            let snapshot = editor.snapshot(window, cx);
 276            if let Ok(range) = action.range.buffer_range(vim, editor, window, cx) {
 277                let end = if range.end < snapshot.buffer_snapshot.max_row() {
 278                    Point::new(range.end.0 + 1, 0)
 279                } else {
 280                    snapshot.buffer_snapshot.max_point()
 281                };
 282                vim.copy_ranges(
 283                    editor,
 284                    MotionKind::Linewise,
 285                    true,
 286                    vec![Point::new(range.start.0, 0)..end],
 287                    window,
 288                    cx,
 289                )
 290            }
 291        });
 292    });
 293
 294    Vim::action(editor, cx, |_, action: &WithCount, window, cx| {
 295        for _ in 0..action.count {
 296            window.dispatch_action(action.action.boxed_clone(), cx)
 297        }
 298    });
 299
 300    Vim::action(editor, cx, |vim, action: &WithRange, window, cx| {
 301        let result = vim.update_editor(window, cx, |vim, editor, window, cx| {
 302            action.range.buffer_range(vim, editor, window, cx)
 303        });
 304
 305        let range = match result {
 306            None => return,
 307            Some(e @ Err(_)) => {
 308                let Some(workspace) = vim.workspace(window) else {
 309                    return;
 310                };
 311                workspace.update(cx, |workspace, cx| {
 312                    e.notify_err(workspace, cx);
 313                });
 314                return;
 315            }
 316            Some(Ok(result)) => result,
 317        };
 318
 319        let previous_selections = vim
 320            .update_editor(window, cx, |_, editor, window, cx| {
 321                let selections = action.restore_selection.then(|| {
 322                    editor
 323                        .selections
 324                        .disjoint_anchor_ranges()
 325                        .collect::<Vec<_>>()
 326                });
 327                editor.change_selections(None, window, cx, |s| {
 328                    let end = Point::new(range.end.0, s.buffer().line_len(range.end));
 329                    s.select_ranges([end..Point::new(range.start.0, 0)]);
 330                });
 331                selections
 332            })
 333            .flatten();
 334        window.dispatch_action(action.action.boxed_clone(), cx);
 335        cx.defer_in(window, move |vim, window, cx| {
 336            vim.update_editor(window, cx, |_, editor, window, cx| {
 337                editor.change_selections(None, window, cx, |s| {
 338                    if let Some(previous_selections) = previous_selections {
 339                        s.select_ranges(previous_selections);
 340                    } else {
 341                        s.select_ranges([
 342                            Point::new(range.start.0, 0)..Point::new(range.start.0, 0)
 343                        ]);
 344                    }
 345                })
 346            });
 347        });
 348    });
 349
 350    Vim::action(editor, cx, |vim, action: &OnMatchingLines, window, cx| {
 351        action.run(vim, window, cx)
 352    });
 353
 354    Vim::action(editor, cx, |vim, action: &ShellExec, window, cx| {
 355        action.run(vim, window, cx)
 356    })
 357}
 358
 359#[derive(Default)]
 360struct VimCommand {
 361    prefix: &'static str,
 362    suffix: &'static str,
 363    action: Option<Box<dyn Action>>,
 364    action_name: Option<&'static str>,
 365    bang_action: Option<Box<dyn Action>>,
 366    range: Option<
 367        Box<
 368            dyn Fn(Box<dyn Action>, &CommandRange) -> Option<Box<dyn Action>>
 369                + Send
 370                + Sync
 371                + 'static,
 372        >,
 373    >,
 374    has_count: bool,
 375}
 376
 377impl VimCommand {
 378    fn new(pattern: (&'static str, &'static str), action: impl Action) -> Self {
 379        Self {
 380            prefix: pattern.0,
 381            suffix: pattern.1,
 382            action: Some(action.boxed_clone()),
 383            ..Default::default()
 384        }
 385    }
 386
 387    // from_str is used for actions in other crates.
 388    fn str(pattern: (&'static str, &'static str), action_name: &'static str) -> Self {
 389        Self {
 390            prefix: pattern.0,
 391            suffix: pattern.1,
 392            action_name: Some(action_name),
 393            ..Default::default()
 394        }
 395    }
 396
 397    fn bang(mut self, bang_action: impl Action) -> Self {
 398        self.bang_action = Some(bang_action.boxed_clone());
 399        self
 400    }
 401
 402    fn range(
 403        mut self,
 404        f: impl Fn(Box<dyn Action>, &CommandRange) -> Option<Box<dyn Action>> + Send + Sync + 'static,
 405    ) -> Self {
 406        self.range = Some(Box::new(f));
 407        self
 408    }
 409
 410    fn count(mut self) -> Self {
 411        self.has_count = true;
 412        self
 413    }
 414
 415    fn parse(
 416        &self,
 417        mut query: &str,
 418        range: &Option<CommandRange>,
 419        cx: &App,
 420    ) -> Option<Box<dyn Action>> {
 421        let has_bang = query.ends_with('!');
 422        if has_bang {
 423            query = &query[..query.len() - 1];
 424        }
 425
 426        let suffix = query.strip_prefix(self.prefix)?;
 427        if !self.suffix.starts_with(suffix) {
 428            return None;
 429        }
 430
 431        let action = if has_bang && self.bang_action.is_some() {
 432            self.bang_action.as_ref().unwrap().boxed_clone()
 433        } else if let Some(action) = self.action.as_ref() {
 434            action.boxed_clone()
 435        } else if let Some(action_name) = self.action_name {
 436            cx.build_action(action_name, None).log_err()?
 437        } else {
 438            return None;
 439        };
 440
 441        if let Some(range) = range {
 442            self.range.as_ref().and_then(|f| f(action, range))
 443        } else {
 444            Some(action)
 445        }
 446    }
 447
 448    // TODO: ranges with search queries
 449    fn parse_range(query: &str) -> (Option<CommandRange>, String) {
 450        let mut chars = query.chars().peekable();
 451
 452        match chars.peek() {
 453            Some('%') => {
 454                chars.next();
 455                return (
 456                    Some(CommandRange {
 457                        start: Position::Line { row: 1, offset: 0 },
 458                        end: Some(Position::LastLine { offset: 0 }),
 459                    }),
 460                    chars.collect(),
 461                );
 462            }
 463            Some('*') => {
 464                chars.next();
 465                return (
 466                    Some(CommandRange {
 467                        start: Position::Mark {
 468                            name: '<',
 469                            offset: 0,
 470                        },
 471                        end: Some(Position::Mark {
 472                            name: '>',
 473                            offset: 0,
 474                        }),
 475                    }),
 476                    chars.collect(),
 477                );
 478            }
 479            _ => {}
 480        }
 481
 482        let start = Self::parse_position(&mut chars);
 483
 484        match chars.peek() {
 485            Some(',' | ';') => {
 486                chars.next();
 487                (
 488                    Some(CommandRange {
 489                        start: start.unwrap_or(Position::CurrentLine { offset: 0 }),
 490                        end: Self::parse_position(&mut chars),
 491                    }),
 492                    chars.collect(),
 493                )
 494            }
 495            _ => (
 496                start.map(|start| CommandRange { start, end: None }),
 497                chars.collect(),
 498            ),
 499        }
 500    }
 501
 502    fn parse_position(chars: &mut Peekable<Chars>) -> Option<Position> {
 503        match chars.peek()? {
 504            '0'..='9' => {
 505                let row = Self::parse_u32(chars);
 506                Some(Position::Line {
 507                    row,
 508                    offset: Self::parse_offset(chars),
 509                })
 510            }
 511            '\'' => {
 512                chars.next();
 513                let name = chars.next()?;
 514                Some(Position::Mark {
 515                    name,
 516                    offset: Self::parse_offset(chars),
 517                })
 518            }
 519            '.' => {
 520                chars.next();
 521                Some(Position::CurrentLine {
 522                    offset: Self::parse_offset(chars),
 523                })
 524            }
 525            '+' | '-' => Some(Position::CurrentLine {
 526                offset: Self::parse_offset(chars),
 527            }),
 528            '$' => {
 529                chars.next();
 530                Some(Position::LastLine {
 531                    offset: Self::parse_offset(chars),
 532                })
 533            }
 534            _ => None,
 535        }
 536    }
 537
 538    fn parse_offset(chars: &mut Peekable<Chars>) -> i32 {
 539        let mut res: i32 = 0;
 540        while matches!(chars.peek(), Some('+' | '-')) {
 541            let sign = if chars.next().unwrap() == '+' { 1 } else { -1 };
 542            let amount = if matches!(chars.peek(), Some('0'..='9')) {
 543                (Self::parse_u32(chars) as i32).saturating_mul(sign)
 544            } else {
 545                sign
 546            };
 547            res = res.saturating_add(amount)
 548        }
 549        res
 550    }
 551
 552    fn parse_u32(chars: &mut Peekable<Chars>) -> u32 {
 553        let mut res: u32 = 0;
 554        while matches!(chars.peek(), Some('0'..='9')) {
 555            res = res
 556                .saturating_mul(10)
 557                .saturating_add(chars.next().unwrap() as u32 - '0' as u32);
 558        }
 559        res
 560    }
 561}
 562
 563#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq)]
 564enum Position {
 565    Line { row: u32, offset: i32 },
 566    Mark { name: char, offset: i32 },
 567    LastLine { offset: i32 },
 568    CurrentLine { offset: i32 },
 569}
 570
 571impl Position {
 572    fn buffer_row(
 573        &self,
 574        vim: &Vim,
 575        editor: &mut Editor,
 576        window: &mut Window,
 577        cx: &mut App,
 578    ) -> Result<MultiBufferRow> {
 579        let snapshot = editor.snapshot(window, cx);
 580        let target = match self {
 581            Position::Line { row, offset } => {
 582                if let Some(anchor) = editor.active_excerpt(cx).and_then(|(_, buffer, _)| {
 583                    editor.buffer().read(cx).buffer_point_to_anchor(
 584                        &buffer,
 585                        Point::new(row.saturating_sub(1), 0),
 586                        cx,
 587                    )
 588                }) {
 589                    anchor
 590                        .to_point(&snapshot.buffer_snapshot)
 591                        .row
 592                        .saturating_add_signed(*offset)
 593                } else {
 594                    row.saturating_add_signed(offset.saturating_sub(1))
 595                }
 596            }
 597            Position::Mark { name, offset } => {
 598                let Some(Mark::Local(anchors)) =
 599                    vim.get_mark(&name.to_string(), editor, window, cx)
 600                else {
 601                    return Err(anyhow!("mark {} not set", name));
 602                };
 603                let Some(mark) = anchors.last() else {
 604                    return Err(anyhow!("mark {} contains empty anchors", name));
 605                };
 606                mark.to_point(&snapshot.buffer_snapshot)
 607                    .row
 608                    .saturating_add_signed(*offset)
 609            }
 610            Position::LastLine { offset } => snapshot
 611                .buffer_snapshot
 612                .max_row()
 613                .0
 614                .saturating_add_signed(*offset),
 615            Position::CurrentLine { offset } => editor
 616                .selections
 617                .newest_anchor()
 618                .head()
 619                .to_point(&snapshot.buffer_snapshot)
 620                .row
 621                .saturating_add_signed(*offset),
 622        };
 623
 624        Ok(MultiBufferRow(target).min(snapshot.buffer_snapshot.max_row()))
 625    }
 626}
 627
 628#[derive(Clone, Debug, PartialEq)]
 629pub(crate) struct CommandRange {
 630    start: Position,
 631    end: Option<Position>,
 632}
 633
 634impl CommandRange {
 635    fn head(&self) -> &Position {
 636        self.end.as_ref().unwrap_or(&self.start)
 637    }
 638
 639    pub(crate) fn buffer_range(
 640        &self,
 641        vim: &Vim,
 642        editor: &mut Editor,
 643        window: &mut Window,
 644        cx: &mut App,
 645    ) -> Result<Range<MultiBufferRow>> {
 646        let start = self.start.buffer_row(vim, editor, window, cx)?;
 647        let end = if let Some(end) = self.end.as_ref() {
 648            end.buffer_row(vim, editor, window, cx)?
 649        } else {
 650            start
 651        };
 652        if end < start {
 653            anyhow::Ok(end..start)
 654        } else {
 655            anyhow::Ok(start..end)
 656        }
 657    }
 658
 659    pub fn as_count(&self) -> Option<u32> {
 660        if let CommandRange {
 661            start: Position::Line { row, offset: 0 },
 662            end: None,
 663        } = &self
 664        {
 665            Some(*row)
 666        } else {
 667            None
 668        }
 669    }
 670}
 671
 672fn generate_commands(_: &App) -> Vec<VimCommand> {
 673    vec![
 674        VimCommand::new(
 675            ("w", "rite"),
 676            workspace::Save {
 677                save_intent: Some(SaveIntent::Save),
 678            },
 679        )
 680        .bang(workspace::Save {
 681            save_intent: Some(SaveIntent::Overwrite),
 682        }),
 683        VimCommand::new(
 684            ("q", "uit"),
 685            workspace::CloseActiveItem {
 686                save_intent: Some(SaveIntent::Close),
 687                close_pinned: false,
 688            },
 689        )
 690        .bang(workspace::CloseActiveItem {
 691            save_intent: Some(SaveIntent::Skip),
 692            close_pinned: true,
 693        }),
 694        VimCommand::new(
 695            ("wq", ""),
 696            workspace::CloseActiveItem {
 697                save_intent: Some(SaveIntent::Save),
 698                close_pinned: false,
 699            },
 700        )
 701        .bang(workspace::CloseActiveItem {
 702            save_intent: Some(SaveIntent::Overwrite),
 703            close_pinned: true,
 704        }),
 705        VimCommand::new(
 706            ("x", "it"),
 707            workspace::CloseActiveItem {
 708                save_intent: Some(SaveIntent::SaveAll),
 709                close_pinned: false,
 710            },
 711        )
 712        .bang(workspace::CloseActiveItem {
 713            save_intent: Some(SaveIntent::Overwrite),
 714            close_pinned: true,
 715        }),
 716        VimCommand::new(
 717            ("exi", "t"),
 718            workspace::CloseActiveItem {
 719                save_intent: Some(SaveIntent::SaveAll),
 720                close_pinned: false,
 721            },
 722        )
 723        .bang(workspace::CloseActiveItem {
 724            save_intent: Some(SaveIntent::Overwrite),
 725            close_pinned: true,
 726        }),
 727        VimCommand::new(
 728            ("up", "date"),
 729            workspace::Save {
 730                save_intent: Some(SaveIntent::SaveAll),
 731            },
 732        ),
 733        VimCommand::new(
 734            ("wa", "ll"),
 735            workspace::SaveAll {
 736                save_intent: Some(SaveIntent::SaveAll),
 737            },
 738        )
 739        .bang(workspace::SaveAll {
 740            save_intent: Some(SaveIntent::Overwrite),
 741        }),
 742        VimCommand::new(
 743            ("qa", "ll"),
 744            workspace::CloseAllItemsAndPanes {
 745                save_intent: Some(SaveIntent::Close),
 746            },
 747        )
 748        .bang(workspace::CloseAllItemsAndPanes {
 749            save_intent: Some(SaveIntent::Skip),
 750        }),
 751        VimCommand::new(
 752            ("quita", "ll"),
 753            workspace::CloseAllItemsAndPanes {
 754                save_intent: Some(SaveIntent::Close),
 755            },
 756        )
 757        .bang(workspace::CloseAllItemsAndPanes {
 758            save_intent: Some(SaveIntent::Skip),
 759        }),
 760        VimCommand::new(
 761            ("xa", "ll"),
 762            workspace::CloseAllItemsAndPanes {
 763                save_intent: Some(SaveIntent::SaveAll),
 764            },
 765        )
 766        .bang(workspace::CloseAllItemsAndPanes {
 767            save_intent: Some(SaveIntent::Overwrite),
 768        }),
 769        VimCommand::new(
 770            ("wqa", "ll"),
 771            workspace::CloseAllItemsAndPanes {
 772                save_intent: Some(SaveIntent::SaveAll),
 773            },
 774        )
 775        .bang(workspace::CloseAllItemsAndPanes {
 776            save_intent: Some(SaveIntent::Overwrite),
 777        }),
 778        VimCommand::new(("cq", "uit"), zed_actions::Quit),
 779        VimCommand::new(("sp", "lit"), workspace::SplitHorizontal),
 780        VimCommand::new(("vs", "plit"), workspace::SplitVertical),
 781        VimCommand::new(
 782            ("bd", "elete"),
 783            workspace::CloseActiveItem {
 784                save_intent: Some(SaveIntent::Close),
 785                close_pinned: false,
 786            },
 787        )
 788        .bang(workspace::CloseActiveItem {
 789            save_intent: Some(SaveIntent::Skip),
 790            close_pinned: true,
 791        }),
 792        VimCommand::new(("bn", "ext"), workspace::ActivateNextItem).count(),
 793        VimCommand::new(("bN", "ext"), workspace::ActivatePreviousItem).count(),
 794        VimCommand::new(("bp", "revious"), workspace::ActivatePreviousItem).count(),
 795        VimCommand::new(("bf", "irst"), workspace::ActivateItem(0)),
 796        VimCommand::new(("br", "ewind"), workspace::ActivateItem(0)),
 797        VimCommand::new(("bl", "ast"), workspace::ActivateLastItem),
 798        VimCommand::new(("new", ""), workspace::NewFileSplitHorizontal),
 799        VimCommand::new(("vne", "w"), workspace::NewFileSplitVertical),
 800        VimCommand::new(("tabe", "dit"), workspace::NewFile),
 801        VimCommand::new(("tabnew", ""), workspace::NewFile),
 802        VimCommand::new(("tabn", "ext"), workspace::ActivateNextItem).count(),
 803        VimCommand::new(("tabp", "revious"), workspace::ActivatePreviousItem).count(),
 804        VimCommand::new(("tabN", "ext"), workspace::ActivatePreviousItem).count(),
 805        VimCommand::new(
 806            ("tabc", "lose"),
 807            workspace::CloseActiveItem {
 808                save_intent: Some(SaveIntent::Close),
 809                close_pinned: false,
 810            },
 811        ),
 812        VimCommand::new(
 813            ("tabo", "nly"),
 814            workspace::CloseInactiveItems {
 815                save_intent: Some(SaveIntent::Close),
 816                close_pinned: false,
 817            },
 818        )
 819        .bang(workspace::CloseInactiveItems {
 820            save_intent: Some(SaveIntent::Skip),
 821            close_pinned: false,
 822        }),
 823        VimCommand::new(
 824            ("on", "ly"),
 825            workspace::CloseInactiveTabsAndPanes {
 826                save_intent: Some(SaveIntent::Close),
 827            },
 828        )
 829        .bang(workspace::CloseInactiveTabsAndPanes {
 830            save_intent: Some(SaveIntent::Skip),
 831        }),
 832        VimCommand::str(("cl", "ist"), "diagnostics::Deploy"),
 833        VimCommand::new(("cc", ""), editor::actions::Hover),
 834        VimCommand::new(("ll", ""), editor::actions::Hover),
 835        VimCommand::new(("cn", "ext"), editor::actions::GoToDiagnostic).range(wrap_count),
 836        VimCommand::new(("cp", "revious"), editor::actions::GoToPreviousDiagnostic)
 837            .range(wrap_count),
 838        VimCommand::new(("cN", "ext"), editor::actions::GoToPreviousDiagnostic).range(wrap_count),
 839        VimCommand::new(("lp", "revious"), editor::actions::GoToPreviousDiagnostic)
 840            .range(wrap_count),
 841        VimCommand::new(("lN", "ext"), editor::actions::GoToPreviousDiagnostic).range(wrap_count),
 842        VimCommand::new(("j", "oin"), JoinLines).range(select_range),
 843        VimCommand::new(("fo", "ld"), editor::actions::FoldSelectedRanges).range(act_on_range),
 844        VimCommand::new(("foldo", "pen"), editor::actions::UnfoldLines)
 845            .bang(editor::actions::UnfoldRecursive)
 846            .range(act_on_range),
 847        VimCommand::new(("foldc", "lose"), editor::actions::Fold)
 848            .bang(editor::actions::FoldRecursive)
 849            .range(act_on_range),
 850        VimCommand::new(("dif", "fupdate"), editor::actions::ToggleSelectedDiffHunks)
 851            .range(act_on_range),
 852        VimCommand::str(("rev", "ert"), "git::Restore").range(act_on_range),
 853        VimCommand::new(("d", "elete"), VisualDeleteLine).range(select_range),
 854        VimCommand::new(("y", "ank"), gpui::NoAction).range(|_, range| {
 855            Some(
 856                YankCommand {
 857                    range: range.clone(),
 858                }
 859                .boxed_clone(),
 860            )
 861        }),
 862        VimCommand::new(("reg", "isters"), ToggleRegistersView).bang(ToggleRegistersView),
 863        VimCommand::new(("marks", ""), ToggleMarksView).bang(ToggleMarksView),
 864        VimCommand::new(("sor", "t"), SortLinesCaseSensitive).range(select_range),
 865        VimCommand::new(("sort i", ""), SortLinesCaseInsensitive).range(select_range),
 866        VimCommand::str(("E", "xplore"), "project_panel::ToggleFocus"),
 867        VimCommand::str(("H", "explore"), "project_panel::ToggleFocus"),
 868        VimCommand::str(("L", "explore"), "project_panel::ToggleFocus"),
 869        VimCommand::str(("S", "explore"), "project_panel::ToggleFocus"),
 870        VimCommand::str(("Ve", "xplore"), "project_panel::ToggleFocus"),
 871        VimCommand::str(("te", "rm"), "terminal_panel::ToggleFocus"),
 872        VimCommand::str(("T", "erm"), "terminal_panel::ToggleFocus"),
 873        VimCommand::str(("C", "ollab"), "collab_panel::ToggleFocus"),
 874        VimCommand::str(("Ch", "at"), "chat_panel::ToggleFocus"),
 875        VimCommand::str(("No", "tifications"), "notification_panel::ToggleFocus"),
 876        VimCommand::str(("A", "I"), "assistant::ToggleFocus"),
 877        VimCommand::new(("noh", "lsearch"), search::buffer_search::Dismiss),
 878        VimCommand::new(("$", ""), EndOfDocument),
 879        VimCommand::new(("%", ""), EndOfDocument),
 880        VimCommand::new(("0", ""), StartOfDocument),
 881        VimCommand::new(("e", "dit"), editor::actions::ReloadFile)
 882            .bang(editor::actions::ReloadFile),
 883        VimCommand::new(("ex", ""), editor::actions::ReloadFile).bang(editor::actions::ReloadFile),
 884        VimCommand::new(("cpp", "link"), editor::actions::CopyPermalinkToLine).range(act_on_range),
 885    ]
 886}
 887
 888struct VimCommands(Vec<VimCommand>);
 889// safety: we only ever access this from the main thread (as ensured by the cx argument)
 890// actions are not Sync so we can't otherwise use a OnceLock.
 891unsafe impl Sync for VimCommands {}
 892impl Global for VimCommands {}
 893
 894fn commands(cx: &App) -> &Vec<VimCommand> {
 895    static COMMANDS: OnceLock<VimCommands> = OnceLock::new();
 896    &COMMANDS
 897        .get_or_init(|| VimCommands(generate_commands(cx)))
 898        .0
 899}
 900
 901fn act_on_range(action: Box<dyn Action>, range: &CommandRange) -> Option<Box<dyn Action>> {
 902    Some(
 903        WithRange {
 904            restore_selection: true,
 905            range: range.clone(),
 906            action: WrappedAction(action),
 907        }
 908        .boxed_clone(),
 909    )
 910}
 911
 912fn select_range(action: Box<dyn Action>, range: &CommandRange) -> Option<Box<dyn Action>> {
 913    Some(
 914        WithRange {
 915            restore_selection: false,
 916            range: range.clone(),
 917            action: WrappedAction(action),
 918        }
 919        .boxed_clone(),
 920    )
 921}
 922
 923fn wrap_count(action: Box<dyn Action>, range: &CommandRange) -> Option<Box<dyn Action>> {
 924    range.as_count().map(|count| {
 925        WithCount {
 926            count,
 927            action: WrappedAction(action),
 928        }
 929        .boxed_clone()
 930    })
 931}
 932
 933pub fn command_interceptor(mut input: &str, cx: &App) -> Vec<CommandInterceptResult> {
 934    // NOTE: We also need to support passing arguments to commands like :w
 935    // (ideally with filename autocompletion).
 936    while input.starts_with(':') {
 937        input = &input[1..];
 938    }
 939
 940    let (range, query) = VimCommand::parse_range(input);
 941    let range_prefix = input[0..(input.len() - query.len())].to_string();
 942    let query = query.as_str().trim();
 943
 944    let action = if range.is_some() && query.is_empty() {
 945        Some(
 946            GoToLine {
 947                range: range.clone().unwrap(),
 948            }
 949            .boxed_clone(),
 950        )
 951    } else if query.starts_with('/') || query.starts_with('?') {
 952        Some(
 953            FindCommand {
 954                query: query[1..].to_string(),
 955                backwards: query.starts_with('?'),
 956            }
 957            .boxed_clone(),
 958        )
 959    } else if query.starts_with("se ") || query.starts_with("set ") {
 960        return VimOption::possible_commands(query.split_once(" ").unwrap().1);
 961    } else if query.starts_with('s') {
 962        let mut substitute = "substitute".chars().peekable();
 963        let mut query = query.chars().peekable();
 964        while substitute
 965            .peek()
 966            .is_some_and(|char| Some(char) == query.peek())
 967        {
 968            substitute.next();
 969            query.next();
 970        }
 971        if let Some(replacement) = Replacement::parse(query) {
 972            let range = range.clone().unwrap_or(CommandRange {
 973                start: Position::CurrentLine { offset: 0 },
 974                end: None,
 975            });
 976            Some(ReplaceCommand { replacement, range }.boxed_clone())
 977        } else {
 978            None
 979        }
 980    } else if query.starts_with('g') || query.starts_with('v') {
 981        let mut global = "global".chars().peekable();
 982        let mut query = query.chars().peekable();
 983        let mut invert = false;
 984        if query.peek() == Some(&'v') {
 985            invert = true;
 986            query.next();
 987        }
 988        while global.peek().is_some_and(|char| Some(char) == query.peek()) {
 989            global.next();
 990            query.next();
 991        }
 992        if !invert && query.peek() == Some(&'!') {
 993            invert = true;
 994            query.next();
 995        }
 996        let range = range.clone().unwrap_or(CommandRange {
 997            start: Position::Line { row: 0, offset: 0 },
 998            end: Some(Position::LastLine { offset: 0 }),
 999        });
1000        if let Some(action) = OnMatchingLines::parse(query, invert, range, cx) {
1001            Some(action.boxed_clone())
1002        } else {
1003            None
1004        }
1005    } else if query.contains('!') {
1006        ShellExec::parse(query, range.clone())
1007    } else {
1008        None
1009    };
1010    if let Some(action) = action {
1011        let string = input.to_string();
1012        let positions = generate_positions(&string, &(range_prefix + query));
1013        return vec![CommandInterceptResult {
1014            action,
1015            string,
1016            positions,
1017        }];
1018    }
1019
1020    for command in commands(cx).iter() {
1021        if let Some(action) = command.parse(query, &range, cx) {
1022            let mut string = ":".to_owned() + &range_prefix + command.prefix + command.suffix;
1023            if query.ends_with('!') {
1024                string.push('!');
1025            }
1026            let positions = generate_positions(&string, &(range_prefix + query));
1027
1028            return vec![CommandInterceptResult {
1029                action,
1030                string,
1031                positions,
1032            }];
1033        }
1034    }
1035    return Vec::default();
1036}
1037
1038fn generate_positions(string: &str, query: &str) -> Vec<usize> {
1039    let mut positions = Vec::new();
1040    let mut chars = query.chars();
1041
1042    let Some(mut current) = chars.next() else {
1043        return positions;
1044    };
1045
1046    for (i, c) in string.char_indices() {
1047        if c == current {
1048            positions.push(i);
1049            if let Some(c) = chars.next() {
1050                current = c;
1051            } else {
1052                break;
1053            }
1054        }
1055    }
1056
1057    positions
1058}
1059
1060#[derive(Debug, PartialEq, Clone)]
1061pub(crate) struct OnMatchingLines {
1062    range: CommandRange,
1063    search: String,
1064    action: WrappedAction,
1065    invert: bool,
1066}
1067
1068impl OnMatchingLines {
1069    // convert a vim query into something more usable by zed.
1070    // we don't attempt to fully convert between the two regex syntaxes,
1071    // but we do flip \( and \) to ( and ) (and vice-versa) in the pattern,
1072    // and convert \0..\9 to $0..$9 in the replacement so that common idioms work.
1073    pub(crate) fn parse(
1074        mut chars: Peekable<Chars>,
1075        invert: bool,
1076        range: CommandRange,
1077        cx: &App,
1078    ) -> Option<Self> {
1079        let delimiter = chars.next().filter(|c| {
1080            !c.is_alphanumeric() && *c != '"' && *c != '|' && *c != '\'' && *c != '!'
1081        })?;
1082
1083        let mut search = String::new();
1084        let mut escaped = false;
1085
1086        while let Some(c) = chars.next() {
1087            if escaped {
1088                escaped = false;
1089                // unescape escaped parens
1090                if c != '(' && c != ')' && c != delimiter {
1091                    search.push('\\')
1092                }
1093                search.push(c)
1094            } else if c == '\\' {
1095                escaped = true;
1096            } else if c == delimiter {
1097                break;
1098            } else {
1099                // escape unescaped parens
1100                if c == '(' || c == ')' {
1101                    search.push('\\')
1102                }
1103                search.push(c)
1104            }
1105        }
1106
1107        let command: String = chars.collect();
1108
1109        let action = WrappedAction(
1110            command_interceptor(&command, cx)
1111                .first()?
1112                .action
1113                .boxed_clone(),
1114        );
1115
1116        Some(Self {
1117            range,
1118            search,
1119            invert,
1120            action,
1121        })
1122    }
1123
1124    pub fn run(&self, vim: &mut Vim, window: &mut Window, cx: &mut Context<Vim>) {
1125        let result = vim.update_editor(window, cx, |vim, editor, window, cx| {
1126            self.range.buffer_range(vim, editor, window, cx)
1127        });
1128
1129        let range = match result {
1130            None => return,
1131            Some(e @ Err(_)) => {
1132                let Some(workspace) = vim.workspace(window) else {
1133                    return;
1134                };
1135                workspace.update(cx, |workspace, cx| {
1136                    e.notify_err(workspace, cx);
1137                });
1138                return;
1139            }
1140            Some(Ok(result)) => result,
1141        };
1142
1143        let mut action = self.action.boxed_clone();
1144        let mut last_pattern = self.search.clone();
1145
1146        let mut regexes = match Regex::new(&self.search) {
1147            Ok(regex) => vec![(regex, !self.invert)],
1148            e @ Err(_) => {
1149                let Some(workspace) = vim.workspace(window) else {
1150                    return;
1151                };
1152                workspace.update(cx, |workspace, cx| {
1153                    e.notify_err(workspace, cx);
1154                });
1155                return;
1156            }
1157        };
1158        while let Some(inner) = action
1159            .boxed_clone()
1160            .as_any()
1161            .downcast_ref::<OnMatchingLines>()
1162        {
1163            let Some(regex) = Regex::new(&inner.search).ok() else {
1164                break;
1165            };
1166            last_pattern = inner.search.clone();
1167            action = inner.action.boxed_clone();
1168            regexes.push((regex, !inner.invert))
1169        }
1170
1171        if let Some(pane) = vim.pane(window, cx) {
1172            pane.update(cx, |pane, cx| {
1173                if let Some(search_bar) = pane.toolbar().read(cx).item_of_type::<BufferSearchBar>()
1174                {
1175                    search_bar.update(cx, |search_bar, cx| {
1176                        if search_bar.show(window, cx) {
1177                            let _ = search_bar.search(
1178                                &last_pattern,
1179                                Some(SearchOptions::REGEX | SearchOptions::CASE_SENSITIVE),
1180                                window,
1181                                cx,
1182                            );
1183                        }
1184                    });
1185                }
1186            });
1187        };
1188
1189        vim.update_editor(window, cx, |_, editor, window, cx| {
1190            let snapshot = editor.snapshot(window, cx);
1191            let mut row = range.start.0;
1192
1193            let point_range = Point::new(range.start.0, 0)
1194                ..snapshot
1195                    .buffer_snapshot
1196                    .clip_point(Point::new(range.end.0 + 1, 0), Bias::Left);
1197            cx.spawn_in(window, async move |editor, cx| {
1198                let new_selections = cx
1199                    .background_spawn(async move {
1200                        let mut line = String::new();
1201                        let mut new_selections = Vec::new();
1202                        let chunks = snapshot
1203                            .buffer_snapshot
1204                            .text_for_range(point_range)
1205                            .chain(["\n"]);
1206
1207                        for chunk in chunks {
1208                            for (newline_ix, text) in chunk.split('\n').enumerate() {
1209                                if newline_ix > 0 {
1210                                    if regexes.iter().all(|(regex, should_match)| {
1211                                        regex.is_match(&line) == *should_match
1212                                    }) {
1213                                        new_selections
1214                                            .push(Point::new(row, 0).to_display_point(&snapshot))
1215                                    }
1216                                    row += 1;
1217                                    line.clear();
1218                                }
1219                                line.push_str(text)
1220                            }
1221                        }
1222
1223                        new_selections
1224                    })
1225                    .await;
1226
1227                if new_selections.is_empty() {
1228                    return;
1229                }
1230                editor
1231                    .update_in(cx, |editor, window, cx| {
1232                        editor.start_transaction_at(Instant::now(), window, cx);
1233                        editor.change_selections(None, window, cx, |s| {
1234                            s.replace_cursors_with(|_| new_selections);
1235                        });
1236                        window.dispatch_action(action, cx);
1237                        cx.defer_in(window, move |editor, window, cx| {
1238                            let newest = editor.selections.newest::<Point>(cx).clone();
1239                            editor.change_selections(None, window, cx, |s| {
1240                                s.select(vec![newest]);
1241                            });
1242                            editor.end_transaction_at(Instant::now(), cx);
1243                        })
1244                    })
1245                    .ok();
1246            })
1247            .detach();
1248        });
1249    }
1250}
1251
1252#[derive(Clone, Debug, PartialEq)]
1253pub struct ShellExec {
1254    command: String,
1255    range: Option<CommandRange>,
1256    is_read: bool,
1257}
1258
1259impl Vim {
1260    pub fn cancel_running_command(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1261        if self.running_command.take().is_some() {
1262            self.update_editor(window, cx, |_, editor, window, cx| {
1263                editor.transact(window, cx, |editor, _window, _cx| {
1264                    editor.clear_row_highlights::<ShellExec>();
1265                })
1266            });
1267        }
1268    }
1269
1270    fn prepare_shell_command(
1271        &mut self,
1272        command: &str,
1273        window: &mut Window,
1274        cx: &mut Context<Self>,
1275    ) -> String {
1276        let mut ret = String::new();
1277        // N.B. non-standard escaping rules:
1278        // * !echo % => "echo README.md"
1279        // * !echo \% => "echo %"
1280        // * !echo \\% => echo \%
1281        // * !echo \\\% => echo \\%
1282        for c in command.chars() {
1283            if c != '%' && c != '!' {
1284                ret.push(c);
1285                continue;
1286            } else if ret.chars().last() == Some('\\') {
1287                ret.pop();
1288                ret.push(c);
1289                continue;
1290            }
1291            match c {
1292                '%' => {
1293                    self.update_editor(window, cx, |_, editor, _window, cx| {
1294                        if let Some((_, buffer, _)) = editor.active_excerpt(cx) {
1295                            if let Some(file) = buffer.read(cx).file() {
1296                                if let Some(local) = file.as_local() {
1297                                    if let Some(str) = local.path().to_str() {
1298                                        ret.push_str(str)
1299                                    }
1300                                }
1301                            }
1302                        }
1303                    });
1304                }
1305                '!' => {
1306                    if let Some(command) = &self.last_command {
1307                        ret.push_str(command)
1308                    }
1309                }
1310                _ => {}
1311            }
1312        }
1313        self.last_command = Some(ret.clone());
1314        ret
1315    }
1316
1317    pub fn shell_command_motion(
1318        &mut self,
1319        motion: Motion,
1320        times: Option<usize>,
1321        window: &mut Window,
1322        cx: &mut Context<Vim>,
1323    ) {
1324        self.stop_recording(cx);
1325        let Some(workspace) = self.workspace(window) else {
1326            return;
1327        };
1328        let command = self.update_editor(window, cx, |_, editor, window, cx| {
1329            let snapshot = editor.snapshot(window, cx);
1330            let start = editor.selections.newest_display(cx);
1331            let text_layout_details = editor.text_layout_details(window);
1332            let (mut range, _) = motion
1333                .range(&snapshot, start.clone(), times, &text_layout_details)
1334                .unwrap_or((start.range(), MotionKind::Exclusive));
1335            if range.start != start.start {
1336                editor.change_selections(None, window, cx, |s| {
1337                    s.select_ranges([
1338                        range.start.to_point(&snapshot)..range.start.to_point(&snapshot)
1339                    ]);
1340                })
1341            }
1342            if range.end.row() > range.start.row() && range.end.column() != 0 {
1343                *range.end.row_mut() -= 1
1344            }
1345            if range.end.row() == range.start.row() {
1346                ".!".to_string()
1347            } else {
1348                format!(".,.+{}!", (range.end.row() - range.start.row()).0)
1349            }
1350        });
1351        if let Some(command) = command {
1352            workspace.update(cx, |workspace, cx| {
1353                command_palette::CommandPalette::toggle(workspace, &command, window, cx);
1354            });
1355        }
1356    }
1357
1358    pub fn shell_command_object(
1359        &mut self,
1360        object: Object,
1361        around: bool,
1362        window: &mut Window,
1363        cx: &mut Context<Vim>,
1364    ) {
1365        self.stop_recording(cx);
1366        let Some(workspace) = self.workspace(window) else {
1367            return;
1368        };
1369        let command = self.update_editor(window, cx, |_, editor, window, cx| {
1370            let snapshot = editor.snapshot(window, cx);
1371            let start = editor.selections.newest_display(cx);
1372            let range = object
1373                .range(&snapshot, start.clone(), around)
1374                .unwrap_or(start.range());
1375            if range.start != start.start {
1376                editor.change_selections(None, window, cx, |s| {
1377                    s.select_ranges([
1378                        range.start.to_point(&snapshot)..range.start.to_point(&snapshot)
1379                    ]);
1380                })
1381            }
1382            if range.end.row() == range.start.row() {
1383                ".!".to_string()
1384            } else {
1385                format!(".,.+{}!", (range.end.row() - range.start.row()).0)
1386            }
1387        });
1388        if let Some(command) = command {
1389            workspace.update(cx, |workspace, cx| {
1390                command_palette::CommandPalette::toggle(workspace, &command, window, cx);
1391            });
1392        }
1393    }
1394}
1395
1396impl ShellExec {
1397    pub fn parse(query: &str, range: Option<CommandRange>) -> Option<Box<dyn Action>> {
1398        let (before, after) = query.split_once('!')?;
1399        let before = before.trim();
1400
1401        if !"read".starts_with(before) {
1402            return None;
1403        }
1404
1405        Some(
1406            ShellExec {
1407                command: after.trim().to_string(),
1408                range,
1409                is_read: !before.is_empty(),
1410            }
1411            .boxed_clone(),
1412        )
1413    }
1414
1415    pub fn run(&self, vim: &mut Vim, window: &mut Window, cx: &mut Context<Vim>) {
1416        let Some(workspace) = vim.workspace(window) else {
1417            return;
1418        };
1419
1420        let project = workspace.read(cx).project().clone();
1421        let command = vim.prepare_shell_command(&self.command, window, cx);
1422
1423        if self.range.is_none() && !self.is_read {
1424            workspace.update(cx, |workspace, cx| {
1425                let project = workspace.project().read(cx);
1426                let cwd = project.first_project_directory(cx);
1427                let shell = project.terminal_settings(&cwd, cx).shell.clone();
1428                cx.emit(workspace::Event::SpawnTask {
1429                    action: Box::new(SpawnInTerminal {
1430                        id: TaskId("vim".to_string()),
1431                        full_label: command.clone(),
1432                        label: command.clone(),
1433                        command: command.clone(),
1434                        args: Vec::new(),
1435                        command_label: command.clone(),
1436                        cwd,
1437                        env: HashMap::default(),
1438                        use_new_terminal: true,
1439                        allow_concurrent_runs: true,
1440                        reveal: RevealStrategy::NoFocus,
1441                        reveal_target: RevealTarget::Dock,
1442                        hide: HideStrategy::Never,
1443                        shell,
1444                        show_summary: false,
1445                        show_command: false,
1446                        show_rerun: false,
1447                    }),
1448                });
1449            });
1450            return;
1451        };
1452
1453        let mut input_snapshot = None;
1454        let mut input_range = None;
1455        let mut needs_newline_prefix = false;
1456        vim.update_editor(window, cx, |vim, editor, window, cx| {
1457            let snapshot = editor.buffer().read(cx).snapshot(cx);
1458            let range = if let Some(range) = self.range.clone() {
1459                let Some(range) = range.buffer_range(vim, editor, window, cx).log_err() else {
1460                    return;
1461                };
1462                Point::new(range.start.0, 0)
1463                    ..snapshot.clip_point(Point::new(range.end.0 + 1, 0), Bias::Right)
1464            } else {
1465                let mut end = editor.selections.newest::<Point>(cx).range().end;
1466                end = snapshot.clip_point(Point::new(end.row + 1, 0), Bias::Right);
1467                needs_newline_prefix = end == snapshot.max_point();
1468                end..end
1469            };
1470            if self.is_read {
1471                input_range =
1472                    Some(snapshot.anchor_after(range.end)..snapshot.anchor_after(range.end));
1473            } else {
1474                input_range =
1475                    Some(snapshot.anchor_before(range.start)..snapshot.anchor_after(range.end));
1476            }
1477            editor.highlight_rows::<ShellExec>(
1478                input_range.clone().unwrap(),
1479                cx.theme().status().unreachable_background,
1480                false,
1481                cx,
1482            );
1483
1484            if !self.is_read {
1485                input_snapshot = Some(snapshot)
1486            }
1487        });
1488
1489        let Some(range) = input_range else { return };
1490
1491        let mut process = project.read(cx).exec_in_shell(command, cx);
1492        process.stdout(Stdio::piped());
1493        process.stderr(Stdio::piped());
1494
1495        if input_snapshot.is_some() {
1496            process.stdin(Stdio::piped());
1497        } else {
1498            process.stdin(Stdio::null());
1499        };
1500
1501        // https://registerspill.thorstenball.com/p/how-to-lose-control-of-your-shell
1502        //
1503        // safety: code in pre_exec should be signal safe.
1504        // https://man7.org/linux/man-pages/man7/signal-safety.7.html
1505        #[cfg(not(target_os = "windows"))]
1506        unsafe {
1507            use std::os::unix::process::CommandExt;
1508            process.pre_exec(|| {
1509                libc::setsid();
1510                Ok(())
1511            });
1512        };
1513        let is_read = self.is_read;
1514
1515        let task = cx.spawn_in(window, async move |vim, cx| {
1516            let Some(mut running) = process.spawn().log_err() else {
1517                vim.update_in(cx, |vim, window, cx| {
1518                    vim.cancel_running_command(window, cx);
1519                })
1520                .log_err();
1521                return;
1522            };
1523
1524            if let Some(mut stdin) = running.stdin.take() {
1525                if let Some(snapshot) = input_snapshot {
1526                    let range = range.clone();
1527                    cx.background_spawn(async move {
1528                        for chunk in snapshot.text_for_range(range) {
1529                            if stdin.write_all(chunk.as_bytes()).log_err().is_none() {
1530                                return;
1531                            }
1532                        }
1533                        stdin.flush().log_err();
1534                    })
1535                    .detach();
1536                }
1537            };
1538
1539            let output = cx
1540                .background_spawn(async move { running.wait_with_output() })
1541                .await;
1542
1543            let Some(output) = output.log_err() else {
1544                vim.update_in(cx, |vim, window, cx| {
1545                    vim.cancel_running_command(window, cx);
1546                })
1547                .log_err();
1548                return;
1549            };
1550            let mut text = String::new();
1551            if needs_newline_prefix {
1552                text.push('\n');
1553            }
1554            text.push_str(&String::from_utf8_lossy(&output.stdout));
1555            text.push_str(&String::from_utf8_lossy(&output.stderr));
1556            if !text.is_empty() && text.chars().last() != Some('\n') {
1557                text.push('\n');
1558            }
1559
1560            vim.update_in(cx, |vim, window, cx| {
1561                vim.update_editor(window, cx, |_, editor, window, cx| {
1562                    editor.transact(window, cx, |editor, window, cx| {
1563                        editor.edit([(range.clone(), text)], cx);
1564                        let snapshot = editor.buffer().read(cx).snapshot(cx);
1565                        editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
1566                            let point = if is_read {
1567                                let point = range.end.to_point(&snapshot);
1568                                Point::new(point.row.saturating_sub(1), 0)
1569                            } else {
1570                                let point = range.start.to_point(&snapshot);
1571                                Point::new(point.row, 0)
1572                            };
1573                            s.select_ranges([point..point]);
1574                        })
1575                    })
1576                });
1577                vim.cancel_running_command(window, cx);
1578            })
1579            .log_err();
1580        });
1581        vim.running_command.replace(task);
1582    }
1583}
1584
1585#[cfg(test)]
1586mod test {
1587    use std::path::Path;
1588
1589    use crate::{
1590        state::Mode,
1591        test::{NeovimBackedTestContext, VimTestContext},
1592    };
1593    use editor::Editor;
1594    use gpui::{Context, TestAppContext};
1595    use indoc::indoc;
1596    use util::path;
1597    use workspace::Workspace;
1598
1599    #[gpui::test]
1600    async fn test_command_basics(cx: &mut TestAppContext) {
1601        let mut cx = NeovimBackedTestContext::new(cx).await;
1602
1603        cx.set_shared_state(indoc! {"
1604            ˇa
1605            b
1606            c"})
1607            .await;
1608
1609        cx.simulate_shared_keystrokes(": j enter").await;
1610
1611        // hack: our cursor positioning after a join command is wrong
1612        cx.simulate_shared_keystrokes("^").await;
1613        cx.shared_state().await.assert_eq(indoc! {
1614            "ˇa b
1615            c"
1616        });
1617    }
1618
1619    #[gpui::test]
1620    async fn test_command_goto(cx: &mut TestAppContext) {
1621        let mut cx = NeovimBackedTestContext::new(cx).await;
1622
1623        cx.set_shared_state(indoc! {"
1624            ˇa
1625            b
1626            c"})
1627            .await;
1628        cx.simulate_shared_keystrokes(": 3 enter").await;
1629        cx.shared_state().await.assert_eq(indoc! {"
1630            a
1631            b
1632            ˇc"});
1633    }
1634
1635    #[gpui::test]
1636    async fn test_command_replace(cx: &mut TestAppContext) {
1637        let mut cx = NeovimBackedTestContext::new(cx).await;
1638
1639        cx.set_shared_state(indoc! {"
1640            ˇa
1641            b
1642            b
1643            c"})
1644            .await;
1645        cx.simulate_shared_keystrokes(": % s / b / d enter").await;
1646        cx.shared_state().await.assert_eq(indoc! {"
1647            a
1648            d
1649            ˇd
1650            c"});
1651        cx.simulate_shared_keystrokes(": % s : . : \\ 0 \\ 0 enter")
1652            .await;
1653        cx.shared_state().await.assert_eq(indoc! {"
1654            aa
1655            dd
1656            dd
1657            ˇcc"});
1658        cx.simulate_shared_keystrokes("k : s / d d / e e enter")
1659            .await;
1660        cx.shared_state().await.assert_eq(indoc! {"
1661            aa
1662            dd
1663            ˇee
1664            cc"});
1665    }
1666
1667    #[gpui::test]
1668    async fn test_command_search(cx: &mut TestAppContext) {
1669        let mut cx = NeovimBackedTestContext::new(cx).await;
1670
1671        cx.set_shared_state(indoc! {"
1672                ˇa
1673                b
1674                a
1675                c"})
1676            .await;
1677        cx.simulate_shared_keystrokes(": / b enter").await;
1678        cx.shared_state().await.assert_eq(indoc! {"
1679                a
1680                ˇb
1681                a
1682                c"});
1683        cx.simulate_shared_keystrokes(": ? a enter").await;
1684        cx.shared_state().await.assert_eq(indoc! {"
1685                ˇa
1686                b
1687                a
1688                c"});
1689    }
1690
1691    #[gpui::test]
1692    async fn test_command_write(cx: &mut TestAppContext) {
1693        let mut cx = VimTestContext::new(cx, true).await;
1694        let path = Path::new(path!("/root/dir/file.rs"));
1695        let fs = cx.workspace(|workspace, _, cx| workspace.project().read(cx).fs().clone());
1696
1697        cx.simulate_keystrokes("i @ escape");
1698        cx.simulate_keystrokes(": w enter");
1699
1700        assert_eq!(fs.load(path).await.unwrap().replace("\r\n", "\n"), "@\n");
1701
1702        fs.as_fake().insert_file(path, b"oops\n".to_vec()).await;
1703
1704        // conflict!
1705        cx.simulate_keystrokes("i @ escape");
1706        cx.simulate_keystrokes(": w enter");
1707        cx.simulate_prompt_answer("Cancel");
1708
1709        assert_eq!(fs.load(path).await.unwrap().replace("\r\n", "\n"), "oops\n");
1710        assert!(!cx.has_pending_prompt());
1711        cx.simulate_keystrokes(": w ! enter");
1712        assert!(!cx.has_pending_prompt());
1713        assert_eq!(fs.load(path).await.unwrap().replace("\r\n", "\n"), "@@\n");
1714    }
1715
1716    #[gpui::test]
1717    async fn test_command_quit(cx: &mut TestAppContext) {
1718        let mut cx = VimTestContext::new(cx, true).await;
1719
1720        cx.simulate_keystrokes(": n e w enter");
1721        cx.workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 2));
1722        cx.simulate_keystrokes(": q enter");
1723        cx.workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 1));
1724        cx.simulate_keystrokes(": n e w enter");
1725        cx.workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 2));
1726        cx.simulate_keystrokes(": q a enter");
1727        cx.workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 0));
1728    }
1729
1730    #[gpui::test]
1731    async fn test_offsets(cx: &mut TestAppContext) {
1732        let mut cx = NeovimBackedTestContext::new(cx).await;
1733
1734        cx.set_shared_state("ˇ1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n")
1735            .await;
1736
1737        cx.simulate_shared_keystrokes(": + enter").await;
1738        cx.shared_state()
1739            .await
1740            .assert_eq("1\nˇ2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n");
1741
1742        cx.simulate_shared_keystrokes(": 1 0 - enter").await;
1743        cx.shared_state()
1744            .await
1745            .assert_eq("1\n2\n3\n4\n5\n6\n7\n8\nˇ9\n10\n11\n");
1746
1747        cx.simulate_shared_keystrokes(": . - 2 enter").await;
1748        cx.shared_state()
1749            .await
1750            .assert_eq("1\n2\n3\n4\n5\n6\nˇ7\n8\n9\n10\n11\n");
1751
1752        cx.simulate_shared_keystrokes(": % enter").await;
1753        cx.shared_state()
1754            .await
1755            .assert_eq("1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\nˇ");
1756    }
1757
1758    #[gpui::test]
1759    async fn test_command_ranges(cx: &mut TestAppContext) {
1760        let mut cx = NeovimBackedTestContext::new(cx).await;
1761
1762        cx.set_shared_state("ˇ1\n2\n3\n4\n4\n3\n2\n1").await;
1763
1764        cx.simulate_shared_keystrokes(": 2 , 4 d enter").await;
1765        cx.shared_state().await.assert_eq("1\nˇ4\n3\n2\n1");
1766
1767        cx.simulate_shared_keystrokes(": 2 , 4 s o r t enter").await;
1768        cx.shared_state().await.assert_eq("1\nˇ2\n3\n4\n1");
1769
1770        cx.simulate_shared_keystrokes(": 2 , 4 j o i n enter").await;
1771        cx.shared_state().await.assert_eq("1\nˇ2 3 4\n1");
1772    }
1773
1774    #[gpui::test]
1775    async fn test_command_visual_replace(cx: &mut TestAppContext) {
1776        let mut cx = NeovimBackedTestContext::new(cx).await;
1777
1778        cx.set_shared_state("ˇ1\n2\n3\n4\n4\n3\n2\n1").await;
1779
1780        cx.simulate_shared_keystrokes("v 2 j : s / . / k enter")
1781            .await;
1782        cx.shared_state().await.assert_eq("k\nk\nˇk\n4\n4\n3\n2\n1");
1783    }
1784
1785    fn assert_active_item(
1786        workspace: &mut Workspace,
1787        expected_path: &str,
1788        expected_text: &str,
1789        cx: &mut Context<Workspace>,
1790    ) {
1791        let active_editor = workspace.active_item_as::<Editor>(cx).unwrap();
1792
1793        let buffer = active_editor
1794            .read(cx)
1795            .buffer()
1796            .read(cx)
1797            .as_singleton()
1798            .unwrap();
1799
1800        let text = buffer.read(cx).text();
1801        let file = buffer.read(cx).file().unwrap();
1802        let file_path = file.as_local().unwrap().abs_path(cx);
1803
1804        assert_eq!(text, expected_text);
1805        assert_eq!(file_path, Path::new(expected_path));
1806    }
1807
1808    #[gpui::test]
1809    async fn test_command_gf(cx: &mut TestAppContext) {
1810        let mut cx = VimTestContext::new(cx, true).await;
1811
1812        // Assert base state, that we're in /root/dir/file.rs
1813        cx.workspace(|workspace, _, cx| {
1814            assert_active_item(workspace, path!("/root/dir/file.rs"), "", cx);
1815        });
1816
1817        // Insert a new file
1818        let fs = cx.workspace(|workspace, _, cx| workspace.project().read(cx).fs().clone());
1819        fs.as_fake()
1820            .insert_file(
1821                path!("/root/dir/file2.rs"),
1822                "This is file2.rs".as_bytes().to_vec(),
1823            )
1824            .await;
1825        fs.as_fake()
1826            .insert_file(
1827                path!("/root/dir/file3.rs"),
1828                "go to file3".as_bytes().to_vec(),
1829            )
1830            .await;
1831
1832        // Put the path to the second file into the currently open buffer
1833        cx.set_state(indoc! {"go to fiˇle2.rs"}, Mode::Normal);
1834
1835        // Go to file2.rs
1836        cx.simulate_keystrokes("g f");
1837
1838        // We now have two items
1839        cx.workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 2));
1840        cx.workspace(|workspace, _, cx| {
1841            assert_active_item(
1842                workspace,
1843                path!("/root/dir/file2.rs"),
1844                "This is file2.rs",
1845                cx,
1846            );
1847        });
1848
1849        // Update editor to point to `file2.rs`
1850        cx.editor =
1851            cx.workspace(|workspace, _, cx| workspace.active_item_as::<Editor>(cx).unwrap());
1852
1853        // Put the path to the third file into the currently open buffer,
1854        // but remove its suffix, because we want that lookup to happen automatically.
1855        cx.set_state(indoc! {"go to fiˇle3"}, Mode::Normal);
1856
1857        // Go to file3.rs
1858        cx.simulate_keystrokes("g f");
1859
1860        // We now have three items
1861        cx.workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 3));
1862        cx.workspace(|workspace, _, cx| {
1863            assert_active_item(workspace, path!("/root/dir/file3.rs"), "go to file3", cx);
1864        });
1865    }
1866
1867    #[gpui::test]
1868    async fn test_command_matching_lines(cx: &mut TestAppContext) {
1869        let mut cx = NeovimBackedTestContext::new(cx).await;
1870
1871        cx.set_shared_state(indoc! {"
1872            ˇa
1873            b
1874            a
1875            b
1876            a
1877        "})
1878            .await;
1879
1880        cx.simulate_shared_keystrokes(":").await;
1881        cx.simulate_shared_keystrokes("g / a / d").await;
1882        cx.simulate_shared_keystrokes("enter").await;
1883
1884        cx.shared_state().await.assert_eq(indoc! {"
1885            b
1886            b
1887            ˇ"});
1888
1889        cx.simulate_shared_keystrokes("u").await;
1890
1891        cx.shared_state().await.assert_eq(indoc! {"
1892            ˇa
1893            b
1894            a
1895            b
1896            a
1897        "});
1898
1899        cx.simulate_shared_keystrokes(":").await;
1900        cx.simulate_shared_keystrokes("v / a / d").await;
1901        cx.simulate_shared_keystrokes("enter").await;
1902
1903        cx.shared_state().await.assert_eq(indoc! {"
1904            a
1905            a
1906            ˇa"});
1907    }
1908}