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