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