state.rs

  1use crate::command::command_interceptor;
  2use crate::normal::repeat::Replayer;
  3use crate::surrounds::SurroundsType;
  4use crate::{motion::Motion, object::Object};
  5use crate::{UseSystemClipboard, Vim, VimSettings};
  6use collections::HashMap;
  7use command_palette_hooks::{CommandPaletteFilter, CommandPaletteInterceptor};
  8use editor::{Anchor, ClipboardSelection, Editor};
  9use gpui::{
 10    Action, App, BorrowAppContext, ClipboardEntry, ClipboardItem, Entity, Global, WeakEntity,
 11};
 12use language::Point;
 13use serde::{Deserialize, Serialize};
 14use settings::{Settings, SettingsStore};
 15use std::borrow::BorrowMut;
 16use std::{fmt::Display, ops::Range, sync::Arc};
 17use ui::{Context, KeyBinding, SharedString};
 18use workspace::searchable::Direction;
 19
 20#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
 21pub enum Mode {
 22    Normal,
 23    Insert,
 24    Replace,
 25    Visual,
 26    VisualLine,
 27    VisualBlock,
 28    HelixNormal,
 29}
 30
 31impl Display for Mode {
 32    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 33        match self {
 34            Mode::Normal => write!(f, "NORMAL"),
 35            Mode::Insert => write!(f, "INSERT"),
 36            Mode::Replace => write!(f, "REPLACE"),
 37            Mode::Visual => write!(f, "VISUAL"),
 38            Mode::VisualLine => write!(f, "VISUAL LINE"),
 39            Mode::VisualBlock => write!(f, "VISUAL BLOCK"),
 40            Mode::HelixNormal => write!(f, "HELIX NORMAL"),
 41        }
 42    }
 43}
 44
 45impl Mode {
 46    pub fn is_visual(&self) -> bool {
 47        match self {
 48            Self::Visual | Self::VisualLine | Self::VisualBlock => true,
 49            Self::Normal | Self::Insert | Self::Replace | Self::HelixNormal => false,
 50        }
 51    }
 52}
 53
 54impl Default for Mode {
 55    fn default() -> Self {
 56        Self::Normal
 57    }
 58}
 59
 60#[derive(Clone, Debug, PartialEq)]
 61pub enum Operator {
 62    Change,
 63    Delete,
 64    Yank,
 65    Replace,
 66    Object {
 67        around: bool,
 68    },
 69    FindForward {
 70        before: bool,
 71    },
 72    FindBackward {
 73        after: bool,
 74    },
 75    Sneak {
 76        first_char: Option<char>,
 77    },
 78    SneakBackward {
 79        first_char: Option<char>,
 80    },
 81    AddSurrounds {
 82        // Typically no need to configure this as `SendKeystrokes` can be used - see #23088.
 83        target: Option<SurroundsType>,
 84    },
 85    ChangeSurrounds {
 86        target: Option<Object>,
 87    },
 88    DeleteSurrounds,
 89    Mark,
 90    Jump {
 91        line: bool,
 92    },
 93    Indent,
 94    Outdent,
 95    AutoIndent,
 96    Rewrap,
 97    ShellCommand,
 98    Lowercase,
 99    Uppercase,
100    OppositeCase,
101    Digraph {
102        first_char: Option<char>,
103    },
104    Literal {
105        prefix: Option<String>,
106    },
107    Register,
108    RecordRegister,
109    ReplayRegister,
110    ToggleComments,
111    ReplaceWithRegister,
112    Exchange,
113}
114
115#[derive(Default, Clone, Debug)]
116pub enum RecordedSelection {
117    #[default]
118    None,
119    Visual {
120        rows: u32,
121        cols: u32,
122    },
123    SingleLine {
124        cols: u32,
125    },
126    VisualBlock {
127        rows: u32,
128        cols: u32,
129    },
130    VisualLine {
131        rows: u32,
132    },
133}
134
135#[derive(Default, Clone, Debug)]
136pub struct Register {
137    pub(crate) text: SharedString,
138    pub(crate) clipboard_selections: Option<Vec<ClipboardSelection>>,
139}
140
141impl From<Register> for ClipboardItem {
142    fn from(register: Register) -> Self {
143        if let Some(clipboard_selections) = register.clipboard_selections {
144            ClipboardItem::new_string_with_json_metadata(register.text.into(), clipboard_selections)
145        } else {
146            ClipboardItem::new_string(register.text.into())
147        }
148    }
149}
150
151impl From<ClipboardItem> for Register {
152    fn from(item: ClipboardItem) -> Self {
153        // For now, we don't store metadata for multiple entries.
154        match item.entries().first() {
155            Some(ClipboardEntry::String(value)) if item.entries().len() == 1 => Register {
156                text: value.text().to_owned().into(),
157                clipboard_selections: value.metadata_json::<Vec<ClipboardSelection>>(),
158            },
159            // For now, registers can't store images. This could change in the future.
160            _ => Register::default(),
161        }
162    }
163}
164
165impl From<String> for Register {
166    fn from(text: String) -> Self {
167        Register {
168            text: text.into(),
169            clipboard_selections: None,
170        }
171    }
172}
173
174#[derive(Default, Clone)]
175pub struct VimGlobals {
176    pub last_find: Option<Motion>,
177
178    pub dot_recording: bool,
179    pub dot_replaying: bool,
180
181    /// pre_count is the number before an operator is specified (3 in 3d2d)
182    pub pre_count: Option<usize>,
183    /// post_count is the number after an operator is specified (2 in 3d2d)
184    pub post_count: Option<usize>,
185
186    pub stop_recording_after_next_action: bool,
187    pub ignore_current_insertion: bool,
188    pub recorded_count: Option<usize>,
189    pub recording_actions: Vec<ReplayableAction>,
190    pub recorded_actions: Vec<ReplayableAction>,
191    pub recorded_selection: RecordedSelection,
192
193    pub recording_register: Option<char>,
194    pub last_recorded_register: Option<char>,
195    pub last_replayed_register: Option<char>,
196    pub replayer: Option<Replayer>,
197
198    pub last_yank: Option<SharedString>,
199    pub registers: HashMap<char, Register>,
200    pub recordings: HashMap<char, Vec<ReplayableAction>>,
201
202    pub focused_vim: Option<WeakEntity<Vim>>,
203}
204impl Global for VimGlobals {}
205
206impl VimGlobals {
207    pub(crate) fn register(cx: &mut App) {
208        cx.set_global(VimGlobals::default());
209
210        cx.observe_keystrokes(|event, _, cx| {
211            let Some(action) = event.action.as_ref().map(|action| action.boxed_clone()) else {
212                return;
213            };
214            Vim::globals(cx).observe_action(action.boxed_clone())
215        })
216        .detach();
217
218        cx.observe_global::<SettingsStore>(move |cx| {
219            if Vim::enabled(cx) {
220                KeyBinding::set_vim_mode(cx, true);
221                CommandPaletteFilter::update_global(cx, |filter, _| {
222                    filter.show_namespace(Vim::NAMESPACE);
223                });
224                CommandPaletteInterceptor::update_global(cx, |interceptor, _| {
225                    interceptor.set(Box::new(command_interceptor));
226                });
227            } else {
228                KeyBinding::set_vim_mode(cx, false);
229                *Vim::globals(cx) = VimGlobals::default();
230                CommandPaletteInterceptor::update_global(cx, |interceptor, _| {
231                    interceptor.clear();
232                });
233                CommandPaletteFilter::update_global(cx, |filter, _| {
234                    filter.hide_namespace(Vim::NAMESPACE);
235                });
236            }
237        })
238        .detach();
239    }
240
241    pub(crate) fn write_registers(
242        &mut self,
243        content: Register,
244        register: Option<char>,
245        is_yank: bool,
246        linewise: bool,
247        cx: &mut Context<Editor>,
248    ) {
249        if let Some(register) = register {
250            let lower = register.to_lowercase().next().unwrap_or(register);
251            if lower != register {
252                let current = self.registers.entry(lower).or_default();
253                current.text = (current.text.to_string() + &content.text).into();
254                // not clear how to support appending to registers with multiple cursors
255                current.clipboard_selections.take();
256                let yanked = current.clone();
257                self.registers.insert('"', yanked);
258            } else {
259                match lower {
260                    '_' | ':' | '.' | '%' | '#' | '=' | '/' => {}
261                    '+' => {
262                        self.registers.insert('"', content.clone());
263                        cx.write_to_clipboard(content.into());
264                    }
265                    '*' => {
266                        self.registers.insert('"', content.clone());
267                        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
268                        cx.write_to_primary(content.into());
269                        #[cfg(not(any(target_os = "linux", target_os = "freebsd")))]
270                        cx.write_to_clipboard(content.into());
271                    }
272                    '"' => {
273                        self.registers.insert('"', content.clone());
274                        self.registers.insert('0', content);
275                    }
276                    _ => {
277                        self.registers.insert('"', content.clone());
278                        self.registers.insert(lower, content);
279                    }
280                }
281            }
282        } else {
283            let setting = VimSettings::get_global(cx).use_system_clipboard;
284            if setting == UseSystemClipboard::Always
285                || setting == UseSystemClipboard::OnYank && is_yank
286            {
287                self.last_yank.replace(content.text.clone());
288                cx.write_to_clipboard(content.clone().into());
289            } else {
290                self.last_yank = cx
291                    .read_from_clipboard()
292                    .and_then(|item| item.text().map(|string| string.into()));
293            }
294
295            self.registers.insert('"', content.clone());
296            if is_yank {
297                self.registers.insert('0', content);
298            } else {
299                let contains_newline = content.text.contains('\n');
300                if !contains_newline {
301                    self.registers.insert('-', content.clone());
302                }
303                if linewise || contains_newline {
304                    let mut content = content;
305                    for i in '1'..'8' {
306                        if let Some(moved) = self.registers.insert(i, content) {
307                            content = moved;
308                        } else {
309                            break;
310                        }
311                    }
312                }
313            }
314        }
315    }
316
317    pub(crate) fn read_register(
318        &mut self,
319        register: Option<char>,
320        editor: Option<&mut Editor>,
321        cx: &mut Context<Editor>,
322    ) -> Option<Register> {
323        let Some(register) = register.filter(|reg| *reg != '"') else {
324            let setting = VimSettings::get_global(cx).use_system_clipboard;
325            return match setting {
326                UseSystemClipboard::Always => cx.read_from_clipboard().map(|item| item.into()),
327                UseSystemClipboard::OnYank if self.system_clipboard_is_newer(cx) => {
328                    cx.read_from_clipboard().map(|item| item.into())
329                }
330                _ => self.registers.get(&'"').cloned(),
331            };
332        };
333        let lower = register.to_lowercase().next().unwrap_or(register);
334        match lower {
335            '_' | ':' | '.' | '#' | '=' => None,
336            '+' => cx.read_from_clipboard().map(|item| item.into()),
337            '*' => {
338                #[cfg(any(target_os = "linux", target_os = "freebsd"))]
339                {
340                    cx.read_from_primary().map(|item| item.into())
341                }
342                #[cfg(not(any(target_os = "linux", target_os = "freebsd")))]
343                {
344                    cx.read_from_clipboard().map(|item| item.into())
345                }
346            }
347            '%' => editor.and_then(|editor| {
348                let selection = editor.selections.newest::<Point>(cx);
349                if let Some((_, buffer, _)) = editor
350                    .buffer()
351                    .read(cx)
352                    .excerpt_containing(selection.head(), cx)
353                {
354                    buffer
355                        .read(cx)
356                        .file()
357                        .map(|file| file.path().to_string_lossy().to_string().into())
358                } else {
359                    None
360                }
361            }),
362            _ => self.registers.get(&lower).cloned(),
363        }
364    }
365
366    fn system_clipboard_is_newer(&self, cx: &mut Context<Editor>) -> bool {
367        cx.read_from_clipboard().is_some_and(|item| {
368            if let Some(last_state) = &self.last_yank {
369                Some(last_state.as_ref()) != item.text().as_deref()
370            } else {
371                true
372            }
373        })
374    }
375
376    pub fn observe_action(&mut self, action: Box<dyn Action>) {
377        if self.dot_recording {
378            self.recording_actions
379                .push(ReplayableAction::Action(action.boxed_clone()));
380
381            if self.stop_recording_after_next_action {
382                self.dot_recording = false;
383                self.recorded_actions = std::mem::take(&mut self.recording_actions);
384                self.stop_recording_after_next_action = false;
385            }
386        }
387        if self.replayer.is_none() {
388            if let Some(recording_register) = self.recording_register {
389                self.recordings
390                    .entry(recording_register)
391                    .or_default()
392                    .push(ReplayableAction::Action(action));
393            }
394        }
395    }
396
397    pub fn observe_insertion(&mut self, text: &Arc<str>, range_to_replace: Option<Range<isize>>) {
398        if self.ignore_current_insertion {
399            self.ignore_current_insertion = false;
400            return;
401        }
402        if self.dot_recording {
403            self.recording_actions.push(ReplayableAction::Insertion {
404                text: text.clone(),
405                utf16_range_to_replace: range_to_replace.clone(),
406            });
407            if self.stop_recording_after_next_action {
408                self.dot_recording = false;
409                self.recorded_actions = std::mem::take(&mut self.recording_actions);
410                self.stop_recording_after_next_action = false;
411            }
412        }
413        if let Some(recording_register) = self.recording_register {
414            self.recordings.entry(recording_register).or_default().push(
415                ReplayableAction::Insertion {
416                    text: text.clone(),
417                    utf16_range_to_replace: range_to_replace,
418                },
419            );
420        }
421    }
422
423    pub fn focused_vim(&self) -> Option<Entity<Vim>> {
424        self.focused_vim.as_ref().and_then(|vim| vim.upgrade())
425    }
426}
427
428impl Vim {
429    pub fn globals(cx: &mut App) -> &mut VimGlobals {
430        cx.global_mut::<VimGlobals>()
431    }
432
433    pub fn update_globals<C, R>(cx: &mut C, f: impl FnOnce(&mut VimGlobals, &mut C) -> R) -> R
434    where
435        C: BorrowMut<App>,
436    {
437        cx.update_global(f)
438    }
439}
440
441#[derive(Debug)]
442pub enum ReplayableAction {
443    Action(Box<dyn Action>),
444    Insertion {
445        text: Arc<str>,
446        utf16_range_to_replace: Option<Range<isize>>,
447    },
448}
449
450impl Clone for ReplayableAction {
451    fn clone(&self) -> Self {
452        match self {
453            Self::Action(action) => Self::Action(action.boxed_clone()),
454            Self::Insertion {
455                text,
456                utf16_range_to_replace,
457            } => Self::Insertion {
458                text: text.clone(),
459                utf16_range_to_replace: utf16_range_to_replace.clone(),
460            },
461        }
462    }
463}
464
465#[derive(Clone, Default, Debug)]
466pub struct SearchState {
467    pub direction: Direction,
468    pub count: usize,
469
470    pub prior_selections: Vec<Range<Anchor>>,
471    pub prior_operator: Option<Operator>,
472    pub prior_mode: Mode,
473}
474
475impl Operator {
476    pub fn id(&self) -> &'static str {
477        match self {
478            Operator::Object { around: false } => "i",
479            Operator::Object { around: true } => "a",
480            Operator::Change => "c",
481            Operator::Delete => "d",
482            Operator::Yank => "y",
483            Operator::Replace => "r",
484            Operator::Digraph { .. } => "^K",
485            Operator::Literal { .. } => "^V",
486            Operator::FindForward { before: false } => "f",
487            Operator::FindForward { before: true } => "t",
488            Operator::Sneak { .. } => "s",
489            Operator::SneakBackward { .. } => "S",
490            Operator::FindBackward { after: false } => "F",
491            Operator::FindBackward { after: true } => "T",
492            Operator::AddSurrounds { .. } => "ys",
493            Operator::ChangeSurrounds { .. } => "cs",
494            Operator::DeleteSurrounds => "ds",
495            Operator::Mark => "m",
496            Operator::Jump { line: true } => "'",
497            Operator::Jump { line: false } => "`",
498            Operator::Indent => ">",
499            Operator::AutoIndent => "eq",
500            Operator::ShellCommand => "sh",
501            Operator::Rewrap => "gq",
502            Operator::ReplaceWithRegister => "gr",
503            Operator::Exchange => "cx",
504            Operator::Outdent => "<",
505            Operator::Uppercase => "gU",
506            Operator::Lowercase => "gu",
507            Operator::OppositeCase => "g~",
508            Operator::Register => "\"",
509            Operator::RecordRegister => "q",
510            Operator::ReplayRegister => "@",
511            Operator::ToggleComments => "gc",
512        }
513    }
514
515    pub fn status(&self) -> String {
516        match self {
517            Operator::Digraph {
518                first_char: Some(first_char),
519            } => format!("^K{first_char}"),
520            Operator::Literal {
521                prefix: Some(prefix),
522            } => format!("^V{prefix}"),
523            Operator::AutoIndent => "=".to_string(),
524            Operator::ShellCommand => "=".to_string(),
525            _ => self.id().to_string(),
526        }
527    }
528
529    pub fn is_waiting(&self, mode: Mode) -> bool {
530        match self {
531            Operator::AddSurrounds { target } => target.is_some() || mode.is_visual(),
532            Operator::FindForward { .. }
533            | Operator::Mark
534            | Operator::Jump { .. }
535            | Operator::FindBackward { .. }
536            | Operator::Sneak { .. }
537            | Operator::SneakBackward { .. }
538            | Operator::Register
539            | Operator::RecordRegister
540            | Operator::ReplayRegister
541            | Operator::Replace
542            | Operator::Digraph { .. }
543            | Operator::Literal { .. }
544            | Operator::ChangeSurrounds { target: Some(_) }
545            | Operator::DeleteSurrounds => true,
546            Operator::Change
547            | Operator::Delete
548            | Operator::Yank
549            | Operator::Rewrap
550            | Operator::Indent
551            | Operator::Outdent
552            | Operator::AutoIndent
553            | Operator::ShellCommand
554            | Operator::Lowercase
555            | Operator::Uppercase
556            | Operator::ReplaceWithRegister
557            | Operator::Exchange
558            | Operator::Object { .. }
559            | Operator::ChangeSurrounds { target: None }
560            | Operator::OppositeCase
561            | Operator::ToggleComments => false,
562        }
563    }
564
565    pub fn starts_dot_recording(&self) -> bool {
566        match self {
567            Operator::Change
568            | Operator::Delete
569            | Operator::Replace
570            | Operator::Indent
571            | Operator::Outdent
572            | Operator::AutoIndent
573            | Operator::Lowercase
574            | Operator::Uppercase
575            | Operator::OppositeCase
576            | Operator::ToggleComments
577            | Operator::ReplaceWithRegister
578            | Operator::Rewrap
579            | Operator::ShellCommand
580            | Operator::AddSurrounds { target: None }
581            | Operator::ChangeSurrounds { target: None }
582            | Operator::DeleteSurrounds
583            | Operator::Exchange => true,
584            Operator::Yank
585            | Operator::Object { .. }
586            | Operator::FindForward { .. }
587            | Operator::FindBackward { .. }
588            | Operator::Sneak { .. }
589            | Operator::SneakBackward { .. }
590            | Operator::Mark
591            | Operator::Digraph { .. }
592            | Operator::Literal { .. }
593            | Operator::AddSurrounds { .. }
594            | Operator::ChangeSurrounds { .. }
595            | Operator::Jump { .. }
596            | Operator::Register
597            | Operator::RecordRegister
598            | Operator::ReplayRegister => false,
599        }
600    }
601}