command.rs

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