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