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