command.rs

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