state.rs

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