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::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::str(("rev", "ert"), "git::Restore").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_spawn(async move {
1189                        let mut line = String::new();
1190                        let mut new_selections = Vec::new();
1191                        let chunks = snapshot
1192                            .buffer_snapshot
1193                            .text_for_range(point_range)
1194                            .chain(["\n"]);
1195
1196                        for chunk in chunks {
1197                            for (newline_ix, text) in chunk.split('\n').enumerate() {
1198                                if newline_ix > 0 {
1199                                    if regexes.iter().all(|(regex, should_match)| {
1200                                        regex.is_match(&line) == *should_match
1201                                    }) {
1202                                        new_selections
1203                                            .push(Point::new(row, 0).to_display_point(&snapshot))
1204                                    }
1205                                    row += 1;
1206                                    line.clear();
1207                                }
1208                                line.push_str(text)
1209                            }
1210                        }
1211
1212                        new_selections
1213                    })
1214                    .await;
1215
1216                if new_selections.is_empty() {
1217                    return;
1218                }
1219                editor
1220                    .update_in(&mut cx, |editor, window, cx| {
1221                        editor.start_transaction_at(Instant::now(), window, cx);
1222                        editor.change_selections(None, window, cx, |s| {
1223                            s.replace_cursors_with(|_| new_selections);
1224                        });
1225                        window.dispatch_action(action, cx);
1226                        cx.defer_in(window, move |editor, window, cx| {
1227                            let newest = editor.selections.newest::<Point>(cx).clone();
1228                            editor.change_selections(None, window, cx, |s| {
1229                                s.select(vec![newest]);
1230                            });
1231                            editor.end_transaction_at(Instant::now(), cx);
1232                        })
1233                    })
1234                    .ok();
1235            })
1236            .detach();
1237        });
1238    }
1239}
1240
1241#[derive(Clone, Debug, PartialEq)]
1242pub struct ShellExec {
1243    command: String,
1244    range: Option<CommandRange>,
1245    is_read: bool,
1246}
1247
1248impl Vim {
1249    pub fn cancel_running_command(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1250        if self.running_command.take().is_some() {
1251            self.update_editor(window, cx, |_, editor, window, cx| {
1252                editor.transact(window, cx, |editor, _window, _cx| {
1253                    editor.clear_row_highlights::<ShellExec>();
1254                })
1255            });
1256        }
1257    }
1258
1259    fn prepare_shell_command(
1260        &mut self,
1261        command: &str,
1262        window: &mut Window,
1263        cx: &mut Context<Self>,
1264    ) -> String {
1265        let mut ret = String::new();
1266        // N.B. non-standard escaping rules:
1267        // * !echo % => "echo README.md"
1268        // * !echo \% => "echo %"
1269        // * !echo \\% => echo \%
1270        // * !echo \\\% => echo \\%
1271        for c in command.chars() {
1272            if c != '%' && c != '!' {
1273                ret.push(c);
1274                continue;
1275            } else if ret.chars().last() == Some('\\') {
1276                ret.pop();
1277                ret.push(c);
1278                continue;
1279            }
1280            match c {
1281                '%' => {
1282                    self.update_editor(window, cx, |_, editor, _window, cx| {
1283                        if let Some((_, buffer, _)) = editor.active_excerpt(cx) {
1284                            if let Some(file) = buffer.read(cx).file() {
1285                                if let Some(local) = file.as_local() {
1286                                    if let Some(str) = local.path().to_str() {
1287                                        ret.push_str(str)
1288                                    }
1289                                }
1290                            }
1291                        }
1292                    });
1293                }
1294                '!' => {
1295                    if let Some(command) = &self.last_command {
1296                        ret.push_str(command)
1297                    }
1298                }
1299                _ => {}
1300            }
1301        }
1302        self.last_command = Some(ret.clone());
1303        ret
1304    }
1305
1306    pub fn shell_command_motion(
1307        &mut self,
1308        motion: Motion,
1309        times: Option<usize>,
1310        window: &mut Window,
1311        cx: &mut Context<Vim>,
1312    ) {
1313        self.stop_recording(cx);
1314        let Some(workspace) = self.workspace(window) else {
1315            return;
1316        };
1317        let command = self.update_editor(window, cx, |_, editor, window, cx| {
1318            let snapshot = editor.snapshot(window, cx);
1319            let start = editor.selections.newest_display(cx);
1320            let text_layout_details = editor.text_layout_details(window);
1321            let mut range = motion
1322                .range(&snapshot, start.clone(), times, false, &text_layout_details)
1323                .unwrap_or(start.range());
1324            if range.start != start.start {
1325                editor.change_selections(None, window, cx, |s| {
1326                    s.select_ranges([
1327                        range.start.to_point(&snapshot)..range.start.to_point(&snapshot)
1328                    ]);
1329                })
1330            }
1331            if range.end.row() > range.start.row() && range.end.column() != 0 {
1332                *range.end.row_mut() -= 1
1333            }
1334            if range.end.row() == range.start.row() {
1335                ".!".to_string()
1336            } else {
1337                format!(".,.+{}!", (range.end.row() - range.start.row()).0)
1338            }
1339        });
1340        if let Some(command) = command {
1341            workspace.update(cx, |workspace, cx| {
1342                command_palette::CommandPalette::toggle(workspace, &command, window, cx);
1343            });
1344        }
1345    }
1346
1347    pub fn shell_command_object(
1348        &mut self,
1349        object: Object,
1350        around: bool,
1351        window: &mut Window,
1352        cx: &mut Context<Vim>,
1353    ) {
1354        self.stop_recording(cx);
1355        let Some(workspace) = self.workspace(window) else {
1356            return;
1357        };
1358        let command = self.update_editor(window, cx, |_, editor, window, cx| {
1359            let snapshot = editor.snapshot(window, cx);
1360            let start = editor.selections.newest_display(cx);
1361            let range = object
1362                .range(&snapshot, start.clone(), around)
1363                .unwrap_or(start.range());
1364            if range.start != start.start {
1365                editor.change_selections(None, window, cx, |s| {
1366                    s.select_ranges([
1367                        range.start.to_point(&snapshot)..range.start.to_point(&snapshot)
1368                    ]);
1369                })
1370            }
1371            if range.end.row() == range.start.row() {
1372                ".!".to_string()
1373            } else {
1374                format!(".,.+{}!", (range.end.row() - range.start.row()).0)
1375            }
1376        });
1377        if let Some(command) = command {
1378            workspace.update(cx, |workspace, cx| {
1379                command_palette::CommandPalette::toggle(workspace, &command, window, cx);
1380            });
1381        }
1382    }
1383}
1384
1385impl ShellExec {
1386    pub fn parse(query: &str, range: Option<CommandRange>) -> Option<Box<dyn Action>> {
1387        let (before, after) = query.split_once('!')?;
1388        let before = before.trim();
1389
1390        if !"read".starts_with(before) {
1391            return None;
1392        }
1393
1394        Some(
1395            ShellExec {
1396                command: after.trim().to_string(),
1397                range,
1398                is_read: !before.is_empty(),
1399            }
1400            .boxed_clone(),
1401        )
1402    }
1403
1404    pub fn run(&self, vim: &mut Vim, window: &mut Window, cx: &mut Context<Vim>) {
1405        let Some(workspace) = vim.workspace(window) else {
1406            return;
1407        };
1408
1409        let project = workspace.read(cx).project().clone();
1410        let command = vim.prepare_shell_command(&self.command, window, cx);
1411
1412        if self.range.is_none() && !self.is_read {
1413            workspace.update(cx, |workspace, cx| {
1414                let project = workspace.project().read(cx);
1415                let cwd = project.first_project_directory(cx);
1416                let shell = project.terminal_settings(&cwd, cx).shell.clone();
1417                cx.emit(workspace::Event::SpawnTask {
1418                    action: Box::new(SpawnInTerminal {
1419                        id: TaskId("vim".to_string()),
1420                        full_label: self.command.clone(),
1421                        label: self.command.clone(),
1422                        command: command.clone(),
1423                        args: Vec::new(),
1424                        command_label: self.command.clone(),
1425                        cwd,
1426                        env: HashMap::default(),
1427                        use_new_terminal: true,
1428                        allow_concurrent_runs: true,
1429                        reveal: RevealStrategy::NoFocus,
1430                        reveal_target: RevealTarget::Dock,
1431                        hide: HideStrategy::Never,
1432                        shell,
1433                        show_summary: false,
1434                        show_command: false,
1435                    }),
1436                });
1437            });
1438            return;
1439        };
1440
1441        let mut input_snapshot = None;
1442        let mut input_range = None;
1443        let mut needs_newline_prefix = false;
1444        vim.update_editor(window, cx, |vim, editor, window, cx| {
1445            let snapshot = editor.buffer().read(cx).snapshot(cx);
1446            let range = if let Some(range) = self.range.clone() {
1447                let Some(range) = range.buffer_range(vim, editor, window, cx).log_err() else {
1448                    return;
1449                };
1450                Point::new(range.start.0, 0)
1451                    ..snapshot.clip_point(Point::new(range.end.0 + 1, 0), Bias::Right)
1452            } else {
1453                let mut end = editor.selections.newest::<Point>(cx).range().end;
1454                end = snapshot.clip_point(Point::new(end.row + 1, 0), Bias::Right);
1455                needs_newline_prefix = end == snapshot.max_point();
1456                end..end
1457            };
1458            if self.is_read {
1459                input_range =
1460                    Some(snapshot.anchor_after(range.end)..snapshot.anchor_after(range.end));
1461            } else {
1462                input_range =
1463                    Some(snapshot.anchor_before(range.start)..snapshot.anchor_after(range.end));
1464            }
1465            editor.highlight_rows::<ShellExec>(
1466                input_range.clone().unwrap(),
1467                cx.theme().status().unreachable_background,
1468                false,
1469                cx,
1470            );
1471
1472            if !self.is_read {
1473                input_snapshot = Some(snapshot)
1474            }
1475        });
1476
1477        let Some(range) = input_range else { return };
1478
1479        let mut process = project.read(cx).exec_in_shell(command, cx);
1480        process.stdout(Stdio::piped());
1481        process.stderr(Stdio::piped());
1482
1483        if input_snapshot.is_some() {
1484            process.stdin(Stdio::piped());
1485        } else {
1486            process.stdin(Stdio::null());
1487        };
1488
1489        // https://registerspill.thorstenball.com/p/how-to-lose-control-of-your-shell
1490        //
1491        // safety: code in pre_exec should be signal safe.
1492        // https://man7.org/linux/man-pages/man7/signal-safety.7.html
1493        #[cfg(not(target_os = "windows"))]
1494        unsafe {
1495            use std::os::unix::process::CommandExt;
1496            process.pre_exec(|| {
1497                libc::setsid();
1498                Ok(())
1499            });
1500        };
1501        let is_read = self.is_read;
1502
1503        let task = cx.spawn_in(window, |vim, mut cx| async move {
1504            let Some(mut running) = process.spawn().log_err() else {
1505                vim.update_in(&mut cx, |vim, window, cx| {
1506                    vim.cancel_running_command(window, cx);
1507                })
1508                .log_err();
1509                return;
1510            };
1511
1512            if let Some(mut stdin) = running.stdin.take() {
1513                if let Some(snapshot) = input_snapshot {
1514                    let range = range.clone();
1515                    cx.background_spawn(async move {
1516                        for chunk in snapshot.text_for_range(range) {
1517                            if stdin.write_all(chunk.as_bytes()).log_err().is_none() {
1518                                return;
1519                            }
1520                        }
1521                        stdin.flush().log_err();
1522                    })
1523                    .detach();
1524                }
1525            };
1526
1527            let output = cx
1528                .background_spawn(async move { running.wait_with_output() })
1529                .await;
1530
1531            let Some(output) = output.log_err() else {
1532                vim.update_in(&mut cx, |vim, window, cx| {
1533                    vim.cancel_running_command(window, cx);
1534                })
1535                .log_err();
1536                return;
1537            };
1538            let mut text = String::new();
1539            if needs_newline_prefix {
1540                text.push('\n');
1541            }
1542            text.push_str(&String::from_utf8_lossy(&output.stdout));
1543            text.push_str(&String::from_utf8_lossy(&output.stderr));
1544            if !text.is_empty() && text.chars().last() != Some('\n') {
1545                text.push('\n');
1546            }
1547
1548            vim.update_in(&mut cx, |vim, window, cx| {
1549                vim.update_editor(window, cx, |_, editor, window, cx| {
1550                    editor.transact(window, cx, |editor, window, cx| {
1551                        editor.edit([(range.clone(), text)], cx);
1552                        let snapshot = editor.buffer().read(cx).snapshot(cx);
1553                        editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
1554                            let point = if is_read {
1555                                let point = range.end.to_point(&snapshot);
1556                                Point::new(point.row.saturating_sub(1), 0)
1557                            } else {
1558                                let point = range.start.to_point(&snapshot);
1559                                Point::new(point.row, 0)
1560                            };
1561                            s.select_ranges([point..point]);
1562                        })
1563                    })
1564                });
1565                vim.cancel_running_command(window, cx);
1566            })
1567            .log_err();
1568        });
1569        vim.running_command.replace(task);
1570    }
1571}
1572
1573#[cfg(test)]
1574mod test {
1575    use std::path::Path;
1576
1577    use crate::{
1578        state::Mode,
1579        test::{NeovimBackedTestContext, VimTestContext},
1580    };
1581    use editor::Editor;
1582    use gpui::{Context, TestAppContext};
1583    use indoc::indoc;
1584    use util::path;
1585    use workspace::Workspace;
1586
1587    #[gpui::test]
1588    async fn test_command_basics(cx: &mut TestAppContext) {
1589        let mut cx = NeovimBackedTestContext::new(cx).await;
1590
1591        cx.set_shared_state(indoc! {"
1592            ˇa
1593            b
1594            c"})
1595            .await;
1596
1597        cx.simulate_shared_keystrokes(": j enter").await;
1598
1599        // hack: our cursor positioning after a join command is wrong
1600        cx.simulate_shared_keystrokes("^").await;
1601        cx.shared_state().await.assert_eq(indoc! {
1602            "ˇa b
1603            c"
1604        });
1605    }
1606
1607    #[gpui::test]
1608    async fn test_command_goto(cx: &mut TestAppContext) {
1609        let mut cx = NeovimBackedTestContext::new(cx).await;
1610
1611        cx.set_shared_state(indoc! {"
1612            ˇa
1613            b
1614            c"})
1615            .await;
1616        cx.simulate_shared_keystrokes(": 3 enter").await;
1617        cx.shared_state().await.assert_eq(indoc! {"
1618            a
1619            b
1620            ˇc"});
1621    }
1622
1623    #[gpui::test]
1624    async fn test_command_replace(cx: &mut TestAppContext) {
1625        let mut cx = NeovimBackedTestContext::new(cx).await;
1626
1627        cx.set_shared_state(indoc! {"
1628            ˇa
1629            b
1630            b
1631            c"})
1632            .await;
1633        cx.simulate_shared_keystrokes(": % s / b / d enter").await;
1634        cx.shared_state().await.assert_eq(indoc! {"
1635            a
1636            d
1637            ˇd
1638            c"});
1639        cx.simulate_shared_keystrokes(": % s : . : \\ 0 \\ 0 enter")
1640            .await;
1641        cx.shared_state().await.assert_eq(indoc! {"
1642            aa
1643            dd
1644            dd
1645            ˇcc"});
1646        cx.simulate_shared_keystrokes("k : s / d d / e e enter")
1647            .await;
1648        cx.shared_state().await.assert_eq(indoc! {"
1649            aa
1650            dd
1651            ˇee
1652            cc"});
1653    }
1654
1655    #[gpui::test]
1656    async fn test_command_search(cx: &mut TestAppContext) {
1657        let mut cx = NeovimBackedTestContext::new(cx).await;
1658
1659        cx.set_shared_state(indoc! {"
1660                ˇa
1661                b
1662                a
1663                c"})
1664            .await;
1665        cx.simulate_shared_keystrokes(": / b enter").await;
1666        cx.shared_state().await.assert_eq(indoc! {"
1667                a
1668                ˇb
1669                a
1670                c"});
1671        cx.simulate_shared_keystrokes(": ? a enter").await;
1672        cx.shared_state().await.assert_eq(indoc! {"
1673                ˇa
1674                b
1675                a
1676                c"});
1677    }
1678
1679    #[gpui::test]
1680    async fn test_command_write(cx: &mut TestAppContext) {
1681        let mut cx = VimTestContext::new(cx, true).await;
1682        let path = Path::new(path!("/root/dir/file.rs"));
1683        let fs = cx.workspace(|workspace, _, cx| workspace.project().read(cx).fs().clone());
1684
1685        cx.simulate_keystrokes("i @ escape");
1686        cx.simulate_keystrokes(": w enter");
1687
1688        assert_eq!(fs.load(path).await.unwrap().replace("\r\n", "\n"), "@\n");
1689
1690        fs.as_fake().insert_file(path, b"oops\n".to_vec()).await;
1691
1692        // conflict!
1693        cx.simulate_keystrokes("i @ escape");
1694        cx.simulate_keystrokes(": w enter");
1695        cx.simulate_prompt_answer("Cancel");
1696
1697        assert_eq!(fs.load(path).await.unwrap().replace("\r\n", "\n"), "oops\n");
1698        assert!(!cx.has_pending_prompt());
1699        cx.simulate_keystrokes(": w ! enter");
1700        assert!(!cx.has_pending_prompt());
1701        assert_eq!(fs.load(path).await.unwrap().replace("\r\n", "\n"), "@@\n");
1702    }
1703
1704    #[gpui::test]
1705    async fn test_command_quit(cx: &mut TestAppContext) {
1706        let mut cx = VimTestContext::new(cx, true).await;
1707
1708        cx.simulate_keystrokes(": n e w enter");
1709        cx.workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 2));
1710        cx.simulate_keystrokes(": q enter");
1711        cx.workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 1));
1712        cx.simulate_keystrokes(": n e w enter");
1713        cx.workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 2));
1714        cx.simulate_keystrokes(": q a enter");
1715        cx.workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 0));
1716    }
1717
1718    #[gpui::test]
1719    async fn test_offsets(cx: &mut TestAppContext) {
1720        let mut cx = NeovimBackedTestContext::new(cx).await;
1721
1722        cx.set_shared_state("ˇ1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n")
1723            .await;
1724
1725        cx.simulate_shared_keystrokes(": + enter").await;
1726        cx.shared_state()
1727            .await
1728            .assert_eq("1\nˇ2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n");
1729
1730        cx.simulate_shared_keystrokes(": 1 0 - enter").await;
1731        cx.shared_state()
1732            .await
1733            .assert_eq("1\n2\n3\n4\n5\n6\n7\n8\nˇ9\n10\n11\n");
1734
1735        cx.simulate_shared_keystrokes(": . - 2 enter").await;
1736        cx.shared_state()
1737            .await
1738            .assert_eq("1\n2\n3\n4\n5\n6\nˇ7\n8\n9\n10\n11\n");
1739
1740        cx.simulate_shared_keystrokes(": % enter").await;
1741        cx.shared_state()
1742            .await
1743            .assert_eq("1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\nˇ");
1744    }
1745
1746    #[gpui::test]
1747    async fn test_command_ranges(cx: &mut TestAppContext) {
1748        let mut cx = NeovimBackedTestContext::new(cx).await;
1749
1750        cx.set_shared_state("ˇ1\n2\n3\n4\n4\n3\n2\n1").await;
1751
1752        cx.simulate_shared_keystrokes(": 2 , 4 d enter").await;
1753        cx.shared_state().await.assert_eq("1\nˇ4\n3\n2\n1");
1754
1755        cx.simulate_shared_keystrokes(": 2 , 4 s o r t enter").await;
1756        cx.shared_state().await.assert_eq("1\nˇ2\n3\n4\n1");
1757
1758        cx.simulate_shared_keystrokes(": 2 , 4 j o i n enter").await;
1759        cx.shared_state().await.assert_eq("1\nˇ2 3 4\n1");
1760    }
1761
1762    #[gpui::test]
1763    async fn test_command_visual_replace(cx: &mut TestAppContext) {
1764        let mut cx = NeovimBackedTestContext::new(cx).await;
1765
1766        cx.set_shared_state("ˇ1\n2\n3\n4\n4\n3\n2\n1").await;
1767
1768        cx.simulate_shared_keystrokes("v 2 j : s / . / k enter")
1769            .await;
1770        cx.shared_state().await.assert_eq("k\nk\nˇk\n4\n4\n3\n2\n1");
1771    }
1772
1773    fn assert_active_item(
1774        workspace: &mut Workspace,
1775        expected_path: &str,
1776        expected_text: &str,
1777        cx: &mut Context<Workspace>,
1778    ) {
1779        let active_editor = workspace.active_item_as::<Editor>(cx).unwrap();
1780
1781        let buffer = active_editor
1782            .read(cx)
1783            .buffer()
1784            .read(cx)
1785            .as_singleton()
1786            .unwrap();
1787
1788        let text = buffer.read(cx).text();
1789        let file = buffer.read(cx).file().unwrap();
1790        let file_path = file.as_local().unwrap().abs_path(cx);
1791
1792        assert_eq!(text, expected_text);
1793        assert_eq!(file_path, Path::new(expected_path));
1794    }
1795
1796    #[gpui::test]
1797    async fn test_command_gf(cx: &mut TestAppContext) {
1798        let mut cx = VimTestContext::new(cx, true).await;
1799
1800        // Assert base state, that we're in /root/dir/file.rs
1801        cx.workspace(|workspace, _, cx| {
1802            assert_active_item(workspace, path!("/root/dir/file.rs"), "", cx);
1803        });
1804
1805        // Insert a new file
1806        let fs = cx.workspace(|workspace, _, cx| workspace.project().read(cx).fs().clone());
1807        fs.as_fake()
1808            .insert_file(
1809                path!("/root/dir/file2.rs"),
1810                "This is file2.rs".as_bytes().to_vec(),
1811            )
1812            .await;
1813        fs.as_fake()
1814            .insert_file(
1815                path!("/root/dir/file3.rs"),
1816                "go to file3".as_bytes().to_vec(),
1817            )
1818            .await;
1819
1820        // Put the path to the second file into the currently open buffer
1821        cx.set_state(indoc! {"go to fiˇle2.rs"}, Mode::Normal);
1822
1823        // Go to file2.rs
1824        cx.simulate_keystrokes("g f");
1825
1826        // We now have two items
1827        cx.workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 2));
1828        cx.workspace(|workspace, _, cx| {
1829            assert_active_item(
1830                workspace,
1831                path!("/root/dir/file2.rs"),
1832                "This is file2.rs",
1833                cx,
1834            );
1835        });
1836
1837        // Update editor to point to `file2.rs`
1838        cx.editor =
1839            cx.workspace(|workspace, _, cx| workspace.active_item_as::<Editor>(cx).unwrap());
1840
1841        // Put the path to the third file into the currently open buffer,
1842        // but remove its suffix, because we want that lookup to happen automatically.
1843        cx.set_state(indoc! {"go to fiˇle3"}, Mode::Normal);
1844
1845        // Go to file3.rs
1846        cx.simulate_keystrokes("g f");
1847
1848        // We now have three items
1849        cx.workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 3));
1850        cx.workspace(|workspace, _, cx| {
1851            assert_active_item(workspace, path!("/root/dir/file3.rs"), "go to file3", cx);
1852        });
1853    }
1854
1855    #[gpui::test]
1856    async fn test_command_matching_lines(cx: &mut TestAppContext) {
1857        let mut cx = NeovimBackedTestContext::new(cx).await;
1858
1859        cx.set_shared_state(indoc! {"
1860            ˇa
1861            b
1862            a
1863            b
1864            a
1865        "})
1866            .await;
1867
1868        cx.simulate_shared_keystrokes(":").await;
1869        cx.simulate_shared_keystrokes("g / a / d").await;
1870        cx.simulate_shared_keystrokes("enter").await;
1871
1872        cx.shared_state().await.assert_eq(indoc! {"
1873            b
1874            b
1875            ˇ"});
1876
1877        cx.simulate_shared_keystrokes("u").await;
1878
1879        cx.shared_state().await.assert_eq(indoc! {"
1880            ˇa
1881            b
1882            a
1883            b
1884            a
1885        "});
1886
1887        cx.simulate_shared_keystrokes(":").await;
1888        cx.simulate_shared_keystrokes("v / a / d").await;
1889        cx.simulate_shared_keystrokes("enter").await;
1890
1891        cx.shared_state().await.assert_eq(indoc! {"
1892            a
1893            a
1894            ˇa"});
1895    }
1896}