state.rs

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