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