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