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