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