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::str(("buffers", ""), "tab_switcher::Toggle"),
 799        VimCommand::str(("ls", ""), "tab_switcher::Toggle"),
 800        VimCommand::new(("new", ""), workspace::NewFileSplitHorizontal),
 801        VimCommand::new(("vne", "w"), workspace::NewFileSplitVertical),
 802        VimCommand::new(("tabe", "dit"), workspace::NewFile),
 803        VimCommand::new(("tabnew", ""), workspace::NewFile),
 804        VimCommand::new(("tabn", "ext"), workspace::ActivateNextItem).count(),
 805        VimCommand::new(("tabp", "revious"), workspace::ActivatePreviousItem).count(),
 806        VimCommand::new(("tabN", "ext"), workspace::ActivatePreviousItem).count(),
 807        VimCommand::new(
 808            ("tabc", "lose"),
 809            workspace::CloseActiveItem {
 810                save_intent: Some(SaveIntent::Close),
 811                close_pinned: false,
 812            },
 813        ),
 814        VimCommand::new(
 815            ("tabo", "nly"),
 816            workspace::CloseInactiveItems {
 817                save_intent: Some(SaveIntent::Close),
 818                close_pinned: false,
 819            },
 820        )
 821        .bang(workspace::CloseInactiveItems {
 822            save_intent: Some(SaveIntent::Skip),
 823            close_pinned: false,
 824        }),
 825        VimCommand::new(
 826            ("on", "ly"),
 827            workspace::CloseInactiveTabsAndPanes {
 828                save_intent: Some(SaveIntent::Close),
 829            },
 830        )
 831        .bang(workspace::CloseInactiveTabsAndPanes {
 832            save_intent: Some(SaveIntent::Skip),
 833        }),
 834        VimCommand::str(("cl", "ist"), "diagnostics::Deploy"),
 835        VimCommand::new(("cc", ""), editor::actions::Hover),
 836        VimCommand::new(("ll", ""), editor::actions::Hover),
 837        VimCommand::new(("cn", "ext"), editor::actions::GoToDiagnostic).range(wrap_count),
 838        VimCommand::new(("cp", "revious"), editor::actions::GoToPreviousDiagnostic)
 839            .range(wrap_count),
 840        VimCommand::new(("cN", "ext"), editor::actions::GoToPreviousDiagnostic).range(wrap_count),
 841        VimCommand::new(("lp", "revious"), editor::actions::GoToPreviousDiagnostic)
 842            .range(wrap_count),
 843        VimCommand::new(("lN", "ext"), editor::actions::GoToPreviousDiagnostic).range(wrap_count),
 844        VimCommand::new(("j", "oin"), JoinLines).range(select_range),
 845        VimCommand::new(("fo", "ld"), editor::actions::FoldSelectedRanges).range(act_on_range),
 846        VimCommand::new(("foldo", "pen"), editor::actions::UnfoldLines)
 847            .bang(editor::actions::UnfoldRecursive)
 848            .range(act_on_range),
 849        VimCommand::new(("foldc", "lose"), editor::actions::Fold)
 850            .bang(editor::actions::FoldRecursive)
 851            .range(act_on_range),
 852        VimCommand::new(("dif", "fupdate"), editor::actions::ToggleSelectedDiffHunks)
 853            .range(act_on_range),
 854        VimCommand::str(("rev", "ert"), "git::Restore").range(act_on_range),
 855        VimCommand::new(("d", "elete"), VisualDeleteLine).range(select_range),
 856        VimCommand::new(("y", "ank"), gpui::NoAction).range(|_, range| {
 857            Some(
 858                YankCommand {
 859                    range: range.clone(),
 860                }
 861                .boxed_clone(),
 862            )
 863        }),
 864        VimCommand::new(("reg", "isters"), ToggleRegistersView).bang(ToggleRegistersView),
 865        VimCommand::new(("marks", ""), ToggleMarksView).bang(ToggleMarksView),
 866        VimCommand::new(("sor", "t"), SortLinesCaseSensitive).range(select_range),
 867        VimCommand::new(("sort i", ""), SortLinesCaseInsensitive).range(select_range),
 868        VimCommand::str(("E", "xplore"), "project_panel::ToggleFocus"),
 869        VimCommand::str(("H", "explore"), "project_panel::ToggleFocus"),
 870        VimCommand::str(("L", "explore"), "project_panel::ToggleFocus"),
 871        VimCommand::str(("S", "explore"), "project_panel::ToggleFocus"),
 872        VimCommand::str(("Ve", "xplore"), "project_panel::ToggleFocus"),
 873        VimCommand::str(("te", "rm"), "terminal_panel::ToggleFocus"),
 874        VimCommand::str(("T", "erm"), "terminal_panel::ToggleFocus"),
 875        VimCommand::str(("C", "ollab"), "collab_panel::ToggleFocus"),
 876        VimCommand::str(("Ch", "at"), "chat_panel::ToggleFocus"),
 877        VimCommand::str(("No", "tifications"), "notification_panel::ToggleFocus"),
 878        VimCommand::str(("A", "I"), "assistant::ToggleFocus"),
 879        VimCommand::new(("noh", "lsearch"), search::buffer_search::Dismiss),
 880        VimCommand::new(("$", ""), EndOfDocument),
 881        VimCommand::new(("%", ""), EndOfDocument),
 882        VimCommand::new(("0", ""), StartOfDocument),
 883        VimCommand::new(("e", "dit"), editor::actions::ReloadFile)
 884            .bang(editor::actions::ReloadFile),
 885        VimCommand::new(("ex", ""), editor::actions::ReloadFile).bang(editor::actions::ReloadFile),
 886        VimCommand::new(("cpp", "link"), editor::actions::CopyPermalinkToLine).range(act_on_range),
 887        VimCommand::str(("opt", "ions"), "zed::OpenDefaultSettings"),
 888        VimCommand::str(("map", ""), "vim::OpenDefaultKeymap"),
 889    ]
 890}
 891
 892struct VimCommands(Vec<VimCommand>);
 893// safety: we only ever access this from the main thread (as ensured by the cx argument)
 894// actions are not Sync so we can't otherwise use a OnceLock.
 895unsafe impl Sync for VimCommands {}
 896impl Global for VimCommands {}
 897
 898fn commands(cx: &App) -> &Vec<VimCommand> {
 899    static COMMANDS: OnceLock<VimCommands> = OnceLock::new();
 900    &COMMANDS
 901        .get_or_init(|| VimCommands(generate_commands(cx)))
 902        .0
 903}
 904
 905fn act_on_range(action: Box<dyn Action>, range: &CommandRange) -> Option<Box<dyn Action>> {
 906    Some(
 907        WithRange {
 908            restore_selection: true,
 909            range: range.clone(),
 910            action: WrappedAction(action),
 911        }
 912        .boxed_clone(),
 913    )
 914}
 915
 916fn select_range(action: Box<dyn Action>, range: &CommandRange) -> Option<Box<dyn Action>> {
 917    Some(
 918        WithRange {
 919            restore_selection: false,
 920            range: range.clone(),
 921            action: WrappedAction(action),
 922        }
 923        .boxed_clone(),
 924    )
 925}
 926
 927fn wrap_count(action: Box<dyn Action>, range: &CommandRange) -> Option<Box<dyn Action>> {
 928    range.as_count().map(|count| {
 929        WithCount {
 930            count,
 931            action: WrappedAction(action),
 932        }
 933        .boxed_clone()
 934    })
 935}
 936
 937pub fn command_interceptor(mut input: &str, cx: &App) -> Vec<CommandInterceptResult> {
 938    // NOTE: We also need to support passing arguments to commands like :w
 939    // (ideally with filename autocompletion).
 940    while input.starts_with(':') {
 941        input = &input[1..];
 942    }
 943
 944    let (range, query) = VimCommand::parse_range(input);
 945    let range_prefix = input[0..(input.len() - query.len())].to_string();
 946    let query = query.as_str().trim();
 947
 948    let action = if range.is_some() && query.is_empty() {
 949        Some(
 950            GoToLine {
 951                range: range.clone().unwrap(),
 952            }
 953            .boxed_clone(),
 954        )
 955    } else if query.starts_with('/') || query.starts_with('?') {
 956        Some(
 957            FindCommand {
 958                query: query[1..].to_string(),
 959                backwards: query.starts_with('?'),
 960            }
 961            .boxed_clone(),
 962        )
 963    } else if query.starts_with("se ") || query.starts_with("set ") {
 964        return VimOption::possible_commands(query.split_once(" ").unwrap().1);
 965    } else if query.starts_with('s') {
 966        let mut substitute = "substitute".chars().peekable();
 967        let mut query = query.chars().peekable();
 968        while substitute
 969            .peek()
 970            .is_some_and(|char| Some(char) == query.peek())
 971        {
 972            substitute.next();
 973            query.next();
 974        }
 975        if let Some(replacement) = Replacement::parse(query) {
 976            let range = range.clone().unwrap_or(CommandRange {
 977                start: Position::CurrentLine { offset: 0 },
 978                end: None,
 979            });
 980            Some(ReplaceCommand { replacement, range }.boxed_clone())
 981        } else {
 982            None
 983        }
 984    } else if query.starts_with('g') || query.starts_with('v') {
 985        let mut global = "global".chars().peekable();
 986        let mut query = query.chars().peekable();
 987        let mut invert = false;
 988        if query.peek() == Some(&'v') {
 989            invert = true;
 990            query.next();
 991        }
 992        while global.peek().is_some_and(|char| Some(char) == query.peek()) {
 993            global.next();
 994            query.next();
 995        }
 996        if !invert && query.peek() == Some(&'!') {
 997            invert = true;
 998            query.next();
 999        }
1000        let range = range.clone().unwrap_or(CommandRange {
1001            start: Position::Line { row: 0, offset: 0 },
1002            end: Some(Position::LastLine { offset: 0 }),
1003        });
1004        if let Some(action) = OnMatchingLines::parse(query, invert, range, cx) {
1005            Some(action.boxed_clone())
1006        } else {
1007            None
1008        }
1009    } else if query.contains('!') {
1010        ShellExec::parse(query, range.clone())
1011    } else {
1012        None
1013    };
1014    if let Some(action) = action {
1015        let string = input.to_string();
1016        let positions = generate_positions(&string, &(range_prefix + query));
1017        return vec![CommandInterceptResult {
1018            action,
1019            string,
1020            positions,
1021        }];
1022    }
1023
1024    for command in commands(cx).iter() {
1025        if let Some(action) = command.parse(query, &range, cx) {
1026            let mut string = ":".to_owned() + &range_prefix + command.prefix + command.suffix;
1027            if query.ends_with('!') {
1028                string.push('!');
1029            }
1030            let positions = generate_positions(&string, &(range_prefix + query));
1031
1032            return vec![CommandInterceptResult {
1033                action,
1034                string,
1035                positions,
1036            }];
1037        }
1038    }
1039    return Vec::default();
1040}
1041
1042fn generate_positions(string: &str, query: &str) -> Vec<usize> {
1043    let mut positions = Vec::new();
1044    let mut chars = query.chars();
1045
1046    let Some(mut current) = chars.next() else {
1047        return positions;
1048    };
1049
1050    for (i, c) in string.char_indices() {
1051        if c == current {
1052            positions.push(i);
1053            if let Some(c) = chars.next() {
1054                current = c;
1055            } else {
1056                break;
1057            }
1058        }
1059    }
1060
1061    positions
1062}
1063
1064#[derive(Debug, PartialEq, Clone)]
1065pub(crate) struct OnMatchingLines {
1066    range: CommandRange,
1067    search: String,
1068    action: WrappedAction,
1069    invert: bool,
1070}
1071
1072impl OnMatchingLines {
1073    // convert a vim query into something more usable by zed.
1074    // we don't attempt to fully convert between the two regex syntaxes,
1075    // but we do flip \( and \) to ( and ) (and vice-versa) in the pattern,
1076    // and convert \0..\9 to $0..$9 in the replacement so that common idioms work.
1077    pub(crate) fn parse(
1078        mut chars: Peekable<Chars>,
1079        invert: bool,
1080        range: CommandRange,
1081        cx: &App,
1082    ) -> Option<Self> {
1083        let delimiter = chars.next().filter(|c| {
1084            !c.is_alphanumeric() && *c != '"' && *c != '|' && *c != '\'' && *c != '!'
1085        })?;
1086
1087        let mut search = String::new();
1088        let mut escaped = false;
1089
1090        while let Some(c) = chars.next() {
1091            if escaped {
1092                escaped = false;
1093                // unescape escaped parens
1094                if c != '(' && c != ')' && c != delimiter {
1095                    search.push('\\')
1096                }
1097                search.push(c)
1098            } else if c == '\\' {
1099                escaped = true;
1100            } else if c == delimiter {
1101                break;
1102            } else {
1103                // escape unescaped parens
1104                if c == '(' || c == ')' {
1105                    search.push('\\')
1106                }
1107                search.push(c)
1108            }
1109        }
1110
1111        let command: String = chars.collect();
1112
1113        let action = WrappedAction(
1114            command_interceptor(&command, cx)
1115                .first()?
1116                .action
1117                .boxed_clone(),
1118        );
1119
1120        Some(Self {
1121            range,
1122            search,
1123            invert,
1124            action,
1125        })
1126    }
1127
1128    pub fn run(&self, vim: &mut Vim, window: &mut Window, cx: &mut Context<Vim>) {
1129        let result = vim.update_editor(window, cx, |vim, editor, window, cx| {
1130            self.range.buffer_range(vim, editor, window, cx)
1131        });
1132
1133        let range = match result {
1134            None => return,
1135            Some(e @ Err(_)) => {
1136                let Some(workspace) = vim.workspace(window) else {
1137                    return;
1138                };
1139                workspace.update(cx, |workspace, cx| {
1140                    e.notify_err(workspace, cx);
1141                });
1142                return;
1143            }
1144            Some(Ok(result)) => result,
1145        };
1146
1147        let mut action = self.action.boxed_clone();
1148        let mut last_pattern = self.search.clone();
1149
1150        let mut regexes = match Regex::new(&self.search) {
1151            Ok(regex) => vec![(regex, !self.invert)],
1152            e @ Err(_) => {
1153                let Some(workspace) = vim.workspace(window) else {
1154                    return;
1155                };
1156                workspace.update(cx, |workspace, cx| {
1157                    e.notify_err(workspace, cx);
1158                });
1159                return;
1160            }
1161        };
1162        while let Some(inner) = action
1163            .boxed_clone()
1164            .as_any()
1165            .downcast_ref::<OnMatchingLines>()
1166        {
1167            let Some(regex) = Regex::new(&inner.search).ok() else {
1168                break;
1169            };
1170            last_pattern = inner.search.clone();
1171            action = inner.action.boxed_clone();
1172            regexes.push((regex, !inner.invert))
1173        }
1174
1175        if let Some(pane) = vim.pane(window, cx) {
1176            pane.update(cx, |pane, cx| {
1177                if let Some(search_bar) = pane.toolbar().read(cx).item_of_type::<BufferSearchBar>()
1178                {
1179                    search_bar.update(cx, |search_bar, cx| {
1180                        if search_bar.show(window, cx) {
1181                            let _ = search_bar.search(
1182                                &last_pattern,
1183                                Some(SearchOptions::REGEX | SearchOptions::CASE_SENSITIVE),
1184                                window,
1185                                cx,
1186                            );
1187                        }
1188                    });
1189                }
1190            });
1191        };
1192
1193        vim.update_editor(window, cx, |_, editor, window, cx| {
1194            let snapshot = editor.snapshot(window, cx);
1195            let mut row = range.start.0;
1196
1197            let point_range = Point::new(range.start.0, 0)
1198                ..snapshot
1199                    .buffer_snapshot
1200                    .clip_point(Point::new(range.end.0 + 1, 0), Bias::Left);
1201            cx.spawn_in(window, async move |editor, cx| {
1202                let new_selections = cx
1203                    .background_spawn(async move {
1204                        let mut line = String::new();
1205                        let mut new_selections = Vec::new();
1206                        let chunks = snapshot
1207                            .buffer_snapshot
1208                            .text_for_range(point_range)
1209                            .chain(["\n"]);
1210
1211                        for chunk in chunks {
1212                            for (newline_ix, text) in chunk.split('\n').enumerate() {
1213                                if newline_ix > 0 {
1214                                    if regexes.iter().all(|(regex, should_match)| {
1215                                        regex.is_match(&line) == *should_match
1216                                    }) {
1217                                        new_selections
1218                                            .push(Point::new(row, 0).to_display_point(&snapshot))
1219                                    }
1220                                    row += 1;
1221                                    line.clear();
1222                                }
1223                                line.push_str(text)
1224                            }
1225                        }
1226
1227                        new_selections
1228                    })
1229                    .await;
1230
1231                if new_selections.is_empty() {
1232                    return;
1233                }
1234                editor
1235                    .update_in(cx, |editor, window, cx| {
1236                        editor.start_transaction_at(Instant::now(), window, cx);
1237                        editor.change_selections(None, window, cx, |s| {
1238                            s.replace_cursors_with(|_| new_selections);
1239                        });
1240                        window.dispatch_action(action, cx);
1241                        cx.defer_in(window, move |editor, window, cx| {
1242                            let newest = editor.selections.newest::<Point>(cx).clone();
1243                            editor.change_selections(None, window, cx, |s| {
1244                                s.select(vec![newest]);
1245                            });
1246                            editor.end_transaction_at(Instant::now(), cx);
1247                        })
1248                    })
1249                    .ok();
1250            })
1251            .detach();
1252        });
1253    }
1254}
1255
1256#[derive(Clone, Debug, PartialEq)]
1257pub struct ShellExec {
1258    command: String,
1259    range: Option<CommandRange>,
1260    is_read: bool,
1261}
1262
1263impl Vim {
1264    pub fn cancel_running_command(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1265        if self.running_command.take().is_some() {
1266            self.update_editor(window, cx, |_, editor, window, cx| {
1267                editor.transact(window, cx, |editor, _window, _cx| {
1268                    editor.clear_row_highlights::<ShellExec>();
1269                })
1270            });
1271        }
1272    }
1273
1274    fn prepare_shell_command(
1275        &mut self,
1276        command: &str,
1277        window: &mut Window,
1278        cx: &mut Context<Self>,
1279    ) -> String {
1280        let mut ret = String::new();
1281        // N.B. non-standard escaping rules:
1282        // * !echo % => "echo README.md"
1283        // * !echo \% => "echo %"
1284        // * !echo \\% => echo \%
1285        // * !echo \\\% => echo \\%
1286        for c in command.chars() {
1287            if c != '%' && c != '!' {
1288                ret.push(c);
1289                continue;
1290            } else if ret.chars().last() == Some('\\') {
1291                ret.pop();
1292                ret.push(c);
1293                continue;
1294            }
1295            match c {
1296                '%' => {
1297                    self.update_editor(window, cx, |_, editor, _window, cx| {
1298                        if let Some((_, buffer, _)) = editor.active_excerpt(cx) {
1299                            if let Some(file) = buffer.read(cx).file() {
1300                                if let Some(local) = file.as_local() {
1301                                    if let Some(str) = local.path().to_str() {
1302                                        ret.push_str(str)
1303                                    }
1304                                }
1305                            }
1306                        }
1307                    });
1308                }
1309                '!' => {
1310                    if let Some(command) = &self.last_command {
1311                        ret.push_str(command)
1312                    }
1313                }
1314                _ => {}
1315            }
1316        }
1317        self.last_command = Some(ret.clone());
1318        ret
1319    }
1320
1321    pub fn shell_command_motion(
1322        &mut self,
1323        motion: Motion,
1324        times: Option<usize>,
1325        window: &mut Window,
1326        cx: &mut Context<Vim>,
1327    ) {
1328        self.stop_recording(cx);
1329        let Some(workspace) = self.workspace(window) else {
1330            return;
1331        };
1332        let command = self.update_editor(window, cx, |_, editor, window, cx| {
1333            let snapshot = editor.snapshot(window, cx);
1334            let start = editor.selections.newest_display(cx);
1335            let text_layout_details = editor.text_layout_details(window);
1336            let (mut range, _) = motion
1337                .range(&snapshot, start.clone(), times, &text_layout_details)
1338                .unwrap_or((start.range(), MotionKind::Exclusive));
1339            if range.start != start.start {
1340                editor.change_selections(None, window, cx, |s| {
1341                    s.select_ranges([
1342                        range.start.to_point(&snapshot)..range.start.to_point(&snapshot)
1343                    ]);
1344                })
1345            }
1346            if range.end.row() > range.start.row() && range.end.column() != 0 {
1347                *range.end.row_mut() -= 1
1348            }
1349            if range.end.row() == range.start.row() {
1350                ".!".to_string()
1351            } else {
1352                format!(".,.+{}!", (range.end.row() - range.start.row()).0)
1353            }
1354        });
1355        if let Some(command) = command {
1356            workspace.update(cx, |workspace, cx| {
1357                command_palette::CommandPalette::toggle(workspace, &command, window, cx);
1358            });
1359        }
1360    }
1361
1362    pub fn shell_command_object(
1363        &mut self,
1364        object: Object,
1365        around: bool,
1366        window: &mut Window,
1367        cx: &mut Context<Vim>,
1368    ) {
1369        self.stop_recording(cx);
1370        let Some(workspace) = self.workspace(window) else {
1371            return;
1372        };
1373        let command = self.update_editor(window, cx, |_, editor, window, cx| {
1374            let snapshot = editor.snapshot(window, cx);
1375            let start = editor.selections.newest_display(cx);
1376            let range = object
1377                .range(&snapshot, start.clone(), around)
1378                .unwrap_or(start.range());
1379            if range.start != start.start {
1380                editor.change_selections(None, window, cx, |s| {
1381                    s.select_ranges([
1382                        range.start.to_point(&snapshot)..range.start.to_point(&snapshot)
1383                    ]);
1384                })
1385            }
1386            if range.end.row() == range.start.row() {
1387                ".!".to_string()
1388            } else {
1389                format!(".,.+{}!", (range.end.row() - range.start.row()).0)
1390            }
1391        });
1392        if let Some(command) = command {
1393            workspace.update(cx, |workspace, cx| {
1394                command_palette::CommandPalette::toggle(workspace, &command, window, cx);
1395            });
1396        }
1397    }
1398}
1399
1400impl ShellExec {
1401    pub fn parse(query: &str, range: Option<CommandRange>) -> Option<Box<dyn Action>> {
1402        let (before, after) = query.split_once('!')?;
1403        let before = before.trim();
1404
1405        if !"read".starts_with(before) {
1406            return None;
1407        }
1408
1409        Some(
1410            ShellExec {
1411                command: after.trim().to_string(),
1412                range,
1413                is_read: !before.is_empty(),
1414            }
1415            .boxed_clone(),
1416        )
1417    }
1418
1419    pub fn run(&self, vim: &mut Vim, window: &mut Window, cx: &mut Context<Vim>) {
1420        let Some(workspace) = vim.workspace(window) else {
1421            return;
1422        };
1423
1424        let project = workspace.read(cx).project().clone();
1425        let command = vim.prepare_shell_command(&self.command, window, cx);
1426
1427        if self.range.is_none() && !self.is_read {
1428            workspace.update(cx, |workspace, cx| {
1429                let project = workspace.project().read(cx);
1430                let cwd = project.first_project_directory(cx);
1431                let shell = project.terminal_settings(&cwd, cx).shell.clone();
1432                cx.emit(workspace::Event::SpawnTask {
1433                    action: Box::new(SpawnInTerminal {
1434                        id: TaskId("vim".to_string()),
1435                        full_label: command.clone(),
1436                        label: command.clone(),
1437                        command: command.clone(),
1438                        args: Vec::new(),
1439                        command_label: command.clone(),
1440                        cwd,
1441                        env: HashMap::default(),
1442                        use_new_terminal: true,
1443                        allow_concurrent_runs: true,
1444                        reveal: RevealStrategy::NoFocus,
1445                        reveal_target: RevealTarget::Dock,
1446                        hide: HideStrategy::Never,
1447                        shell,
1448                        show_summary: false,
1449                        show_command: false,
1450                        show_rerun: false,
1451                    }),
1452                });
1453            });
1454            return;
1455        };
1456
1457        let mut input_snapshot = None;
1458        let mut input_range = None;
1459        let mut needs_newline_prefix = false;
1460        vim.update_editor(window, cx, |vim, editor, window, cx| {
1461            let snapshot = editor.buffer().read(cx).snapshot(cx);
1462            let range = if let Some(range) = self.range.clone() {
1463                let Some(range) = range.buffer_range(vim, editor, window, cx).log_err() else {
1464                    return;
1465                };
1466                Point::new(range.start.0, 0)
1467                    ..snapshot.clip_point(Point::new(range.end.0 + 1, 0), Bias::Right)
1468            } else {
1469                let mut end = editor.selections.newest::<Point>(cx).range().end;
1470                end = snapshot.clip_point(Point::new(end.row + 1, 0), Bias::Right);
1471                needs_newline_prefix = end == snapshot.max_point();
1472                end..end
1473            };
1474            if self.is_read {
1475                input_range =
1476                    Some(snapshot.anchor_after(range.end)..snapshot.anchor_after(range.end));
1477            } else {
1478                input_range =
1479                    Some(snapshot.anchor_before(range.start)..snapshot.anchor_after(range.end));
1480            }
1481            editor.highlight_rows::<ShellExec>(
1482                input_range.clone().unwrap(),
1483                cx.theme().status().unreachable_background,
1484                false,
1485                cx,
1486            );
1487
1488            if !self.is_read {
1489                input_snapshot = Some(snapshot)
1490            }
1491        });
1492
1493        let Some(range) = input_range else { return };
1494
1495        let mut process = project.read(cx).exec_in_shell(command, cx);
1496        process.stdout(Stdio::piped());
1497        process.stderr(Stdio::piped());
1498
1499        if input_snapshot.is_some() {
1500            process.stdin(Stdio::piped());
1501        } else {
1502            process.stdin(Stdio::null());
1503        };
1504
1505        // https://registerspill.thorstenball.com/p/how-to-lose-control-of-your-shell
1506        //
1507        // safety: code in pre_exec should be signal safe.
1508        // https://man7.org/linux/man-pages/man7/signal-safety.7.html
1509        #[cfg(not(target_os = "windows"))]
1510        unsafe {
1511            use std::os::unix::process::CommandExt;
1512            process.pre_exec(|| {
1513                libc::setsid();
1514                Ok(())
1515            });
1516        };
1517        let is_read = self.is_read;
1518
1519        let task = cx.spawn_in(window, async move |vim, cx| {
1520            let Some(mut running) = process.spawn().log_err() else {
1521                vim.update_in(cx, |vim, window, cx| {
1522                    vim.cancel_running_command(window, cx);
1523                })
1524                .log_err();
1525                return;
1526            };
1527
1528            if let Some(mut stdin) = running.stdin.take() {
1529                if let Some(snapshot) = input_snapshot {
1530                    let range = range.clone();
1531                    cx.background_spawn(async move {
1532                        for chunk in snapshot.text_for_range(range) {
1533                            if stdin.write_all(chunk.as_bytes()).log_err().is_none() {
1534                                return;
1535                            }
1536                        }
1537                        stdin.flush().log_err();
1538                    })
1539                    .detach();
1540                }
1541            };
1542
1543            let output = cx
1544                .background_spawn(async move { running.wait_with_output() })
1545                .await;
1546
1547            let Some(output) = output.log_err() else {
1548                vim.update_in(cx, |vim, window, cx| {
1549                    vim.cancel_running_command(window, cx);
1550                })
1551                .log_err();
1552                return;
1553            };
1554            let mut text = String::new();
1555            if needs_newline_prefix {
1556                text.push('\n');
1557            }
1558            text.push_str(&String::from_utf8_lossy(&output.stdout));
1559            text.push_str(&String::from_utf8_lossy(&output.stderr));
1560            if !text.is_empty() && text.chars().last() != Some('\n') {
1561                text.push('\n');
1562            }
1563
1564            vim.update_in(cx, |vim, window, cx| {
1565                vim.update_editor(window, cx, |_, editor, window, cx| {
1566                    editor.transact(window, cx, |editor, window, cx| {
1567                        editor.edit([(range.clone(), text)], cx);
1568                        let snapshot = editor.buffer().read(cx).snapshot(cx);
1569                        editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
1570                            let point = if is_read {
1571                                let point = range.end.to_point(&snapshot);
1572                                Point::new(point.row.saturating_sub(1), 0)
1573                            } else {
1574                                let point = range.start.to_point(&snapshot);
1575                                Point::new(point.row, 0)
1576                            };
1577                            s.select_ranges([point..point]);
1578                        })
1579                    })
1580                });
1581                vim.cancel_running_command(window, cx);
1582            })
1583            .log_err();
1584        });
1585        vim.running_command.replace(task);
1586    }
1587}
1588
1589#[cfg(test)]
1590mod test {
1591    use std::path::Path;
1592
1593    use crate::{
1594        state::Mode,
1595        test::{NeovimBackedTestContext, VimTestContext},
1596    };
1597    use editor::Editor;
1598    use gpui::{Context, TestAppContext};
1599    use indoc::indoc;
1600    use util::path;
1601    use workspace::Workspace;
1602
1603    #[gpui::test]
1604    async fn test_command_basics(cx: &mut TestAppContext) {
1605        let mut cx = NeovimBackedTestContext::new(cx).await;
1606
1607        cx.set_shared_state(indoc! {"
1608            ˇa
1609            b
1610            c"})
1611            .await;
1612
1613        cx.simulate_shared_keystrokes(": j enter").await;
1614
1615        // hack: our cursor positioning after a join command is wrong
1616        cx.simulate_shared_keystrokes("^").await;
1617        cx.shared_state().await.assert_eq(indoc! {
1618            "ˇa b
1619            c"
1620        });
1621    }
1622
1623    #[gpui::test]
1624    async fn test_command_goto(cx: &mut TestAppContext) {
1625        let mut cx = NeovimBackedTestContext::new(cx).await;
1626
1627        cx.set_shared_state(indoc! {"
1628            ˇa
1629            b
1630            c"})
1631            .await;
1632        cx.simulate_shared_keystrokes(": 3 enter").await;
1633        cx.shared_state().await.assert_eq(indoc! {"
1634            a
1635            b
1636            ˇc"});
1637    }
1638
1639    #[gpui::test]
1640    async fn test_command_replace(cx: &mut TestAppContext) {
1641        let mut cx = NeovimBackedTestContext::new(cx).await;
1642
1643        cx.set_shared_state(indoc! {"
1644            ˇa
1645            b
1646            b
1647            c"})
1648            .await;
1649        cx.simulate_shared_keystrokes(": % s / b / d enter").await;
1650        cx.shared_state().await.assert_eq(indoc! {"
1651            a
1652            d
1653            ˇd
1654            c"});
1655        cx.simulate_shared_keystrokes(": % s : . : \\ 0 \\ 0 enter")
1656            .await;
1657        cx.shared_state().await.assert_eq(indoc! {"
1658            aa
1659            dd
1660            dd
1661            ˇcc"});
1662        cx.simulate_shared_keystrokes("k : s / d d / e e enter")
1663            .await;
1664        cx.shared_state().await.assert_eq(indoc! {"
1665            aa
1666            dd
1667            ˇee
1668            cc"});
1669    }
1670
1671    #[gpui::test]
1672    async fn test_command_search(cx: &mut TestAppContext) {
1673        let mut cx = NeovimBackedTestContext::new(cx).await;
1674
1675        cx.set_shared_state(indoc! {"
1676                ˇa
1677                b
1678                a
1679                c"})
1680            .await;
1681        cx.simulate_shared_keystrokes(": / b enter").await;
1682        cx.shared_state().await.assert_eq(indoc! {"
1683                a
1684                ˇb
1685                a
1686                c"});
1687        cx.simulate_shared_keystrokes(": ? a enter").await;
1688        cx.shared_state().await.assert_eq(indoc! {"
1689                ˇa
1690                b
1691                a
1692                c"});
1693    }
1694
1695    #[gpui::test]
1696    async fn test_command_write(cx: &mut TestAppContext) {
1697        let mut cx = VimTestContext::new(cx, true).await;
1698        let path = Path::new(path!("/root/dir/file.rs"));
1699        let fs = cx.workspace(|workspace, _, cx| workspace.project().read(cx).fs().clone());
1700
1701        cx.simulate_keystrokes("i @ escape");
1702        cx.simulate_keystrokes(": w enter");
1703
1704        assert_eq!(fs.load(path).await.unwrap().replace("\r\n", "\n"), "@\n");
1705
1706        fs.as_fake().insert_file(path, b"oops\n".to_vec()).await;
1707
1708        // conflict!
1709        cx.simulate_keystrokes("i @ escape");
1710        cx.simulate_keystrokes(": w enter");
1711        cx.simulate_prompt_answer("Cancel");
1712
1713        assert_eq!(fs.load(path).await.unwrap().replace("\r\n", "\n"), "oops\n");
1714        assert!(!cx.has_pending_prompt());
1715        cx.simulate_keystrokes(": w ! enter");
1716        assert!(!cx.has_pending_prompt());
1717        assert_eq!(fs.load(path).await.unwrap().replace("\r\n", "\n"), "@@\n");
1718    }
1719
1720    #[gpui::test]
1721    async fn test_command_quit(cx: &mut TestAppContext) {
1722        let mut cx = VimTestContext::new(cx, true).await;
1723
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 enter");
1727        cx.workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 1));
1728        cx.simulate_keystrokes(": n e w enter");
1729        cx.workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 2));
1730        cx.simulate_keystrokes(": q a enter");
1731        cx.workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 0));
1732    }
1733
1734    #[gpui::test]
1735    async fn test_offsets(cx: &mut TestAppContext) {
1736        let mut cx = NeovimBackedTestContext::new(cx).await;
1737
1738        cx.set_shared_state("ˇ1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n")
1739            .await;
1740
1741        cx.simulate_shared_keystrokes(": + enter").await;
1742        cx.shared_state()
1743            .await
1744            .assert_eq("1\nˇ2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n");
1745
1746        cx.simulate_shared_keystrokes(": 1 0 - enter").await;
1747        cx.shared_state()
1748            .await
1749            .assert_eq("1\n2\n3\n4\n5\n6\n7\n8\nˇ9\n10\n11\n");
1750
1751        cx.simulate_shared_keystrokes(": . - 2 enter").await;
1752        cx.shared_state()
1753            .await
1754            .assert_eq("1\n2\n3\n4\n5\n6\nˇ7\n8\n9\n10\n11\n");
1755
1756        cx.simulate_shared_keystrokes(": % enter").await;
1757        cx.shared_state()
1758            .await
1759            .assert_eq("1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\nˇ");
1760    }
1761
1762    #[gpui::test]
1763    async fn test_command_ranges(cx: &mut TestAppContext) {
1764        let mut cx = NeovimBackedTestContext::new(cx).await;
1765
1766        cx.set_shared_state("ˇ1\n2\n3\n4\n4\n3\n2\n1").await;
1767
1768        cx.simulate_shared_keystrokes(": 2 , 4 d enter").await;
1769        cx.shared_state().await.assert_eq("1\nˇ4\n3\n2\n1");
1770
1771        cx.simulate_shared_keystrokes(": 2 , 4 s o r t enter").await;
1772        cx.shared_state().await.assert_eq("1\nˇ2\n3\n4\n1");
1773
1774        cx.simulate_shared_keystrokes(": 2 , 4 j o i n enter").await;
1775        cx.shared_state().await.assert_eq("1\nˇ2 3 4\n1");
1776    }
1777
1778    #[gpui::test]
1779    async fn test_command_visual_replace(cx: &mut TestAppContext) {
1780        let mut cx = NeovimBackedTestContext::new(cx).await;
1781
1782        cx.set_shared_state("ˇ1\n2\n3\n4\n4\n3\n2\n1").await;
1783
1784        cx.simulate_shared_keystrokes("v 2 j : s / . / k enter")
1785            .await;
1786        cx.shared_state().await.assert_eq("k\nk\nˇk\n4\n4\n3\n2\n1");
1787    }
1788
1789    fn assert_active_item(
1790        workspace: &mut Workspace,
1791        expected_path: &str,
1792        expected_text: &str,
1793        cx: &mut Context<Workspace>,
1794    ) {
1795        let active_editor = workspace.active_item_as::<Editor>(cx).unwrap();
1796
1797        let buffer = active_editor
1798            .read(cx)
1799            .buffer()
1800            .read(cx)
1801            .as_singleton()
1802            .unwrap();
1803
1804        let text = buffer.read(cx).text();
1805        let file = buffer.read(cx).file().unwrap();
1806        let file_path = file.as_local().unwrap().abs_path(cx);
1807
1808        assert_eq!(text, expected_text);
1809        assert_eq!(file_path, Path::new(expected_path));
1810    }
1811
1812    #[gpui::test]
1813    async fn test_command_gf(cx: &mut TestAppContext) {
1814        let mut cx = VimTestContext::new(cx, true).await;
1815
1816        // Assert base state, that we're in /root/dir/file.rs
1817        cx.workspace(|workspace, _, cx| {
1818            assert_active_item(workspace, path!("/root/dir/file.rs"), "", cx);
1819        });
1820
1821        // Insert a new file
1822        let fs = cx.workspace(|workspace, _, cx| workspace.project().read(cx).fs().clone());
1823        fs.as_fake()
1824            .insert_file(
1825                path!("/root/dir/file2.rs"),
1826                "This is file2.rs".as_bytes().to_vec(),
1827            )
1828            .await;
1829        fs.as_fake()
1830            .insert_file(
1831                path!("/root/dir/file3.rs"),
1832                "go to file3".as_bytes().to_vec(),
1833            )
1834            .await;
1835
1836        // Put the path to the second file into the currently open buffer
1837        cx.set_state(indoc! {"go to fiˇle2.rs"}, Mode::Normal);
1838
1839        // Go to file2.rs
1840        cx.simulate_keystrokes("g f");
1841
1842        // We now have two items
1843        cx.workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 2));
1844        cx.workspace(|workspace, _, cx| {
1845            assert_active_item(
1846                workspace,
1847                path!("/root/dir/file2.rs"),
1848                "This is file2.rs",
1849                cx,
1850            );
1851        });
1852
1853        // Update editor to point to `file2.rs`
1854        cx.editor =
1855            cx.workspace(|workspace, _, cx| workspace.active_item_as::<Editor>(cx).unwrap());
1856
1857        // Put the path to the third file into the currently open buffer,
1858        // but remove its suffix, because we want that lookup to happen automatically.
1859        cx.set_state(indoc! {"go to fiˇle3"}, Mode::Normal);
1860
1861        // Go to file3.rs
1862        cx.simulate_keystrokes("g f");
1863
1864        // We now have three items
1865        cx.workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 3));
1866        cx.workspace(|workspace, _, cx| {
1867            assert_active_item(workspace, path!("/root/dir/file3.rs"), "go to file3", cx);
1868        });
1869    }
1870
1871    #[gpui::test]
1872    async fn test_command_matching_lines(cx: &mut TestAppContext) {
1873        let mut cx = NeovimBackedTestContext::new(cx).await;
1874
1875        cx.set_shared_state(indoc! {"
1876            ˇa
1877            b
1878            a
1879            b
1880            a
1881        "})
1882            .await;
1883
1884        cx.simulate_shared_keystrokes(":").await;
1885        cx.simulate_shared_keystrokes("g / a / d").await;
1886        cx.simulate_shared_keystrokes("enter").await;
1887
1888        cx.shared_state().await.assert_eq(indoc! {"
1889            b
1890            b
1891            ˇ"});
1892
1893        cx.simulate_shared_keystrokes("u").await;
1894
1895        cx.shared_state().await.assert_eq(indoc! {"
1896            ˇa
1897            b
1898            a
1899            b
1900            a
1901        "});
1902
1903        cx.simulate_shared_keystrokes(":").await;
1904        cx.simulate_shared_keystrokes("v / a / d").await;
1905        cx.simulate_shared_keystrokes("enter").await;
1906
1907        cx.shared_state().await.assert_eq(indoc! {"
1908            a
1909            a
1910            ˇa"});
1911    }
1912}