state.rs

  1use std::{fmt::Display, ops::Range, sync::Arc};
  2
  3use crate::normal::repeat::Replayer;
  4use crate::surrounds::SurroundsType;
  5use crate::{motion::Motion, object::Object};
  6use collections::HashMap;
  7use editor::{Anchor, ClipboardSelection};
  8use gpui::{Action, ClipboardItem, KeyContext};
  9use language::{CursorShape, Selection, TransactionId};
 10use serde::{Deserialize, Serialize};
 11use ui::SharedString;
 12use workspace::searchable::Direction;
 13
 14#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)]
 15pub enum Mode {
 16    Normal,
 17    Insert,
 18    Replace,
 19    Visual,
 20    VisualLine,
 21    VisualBlock,
 22}
 23
 24impl Display for Mode {
 25    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 26        match self {
 27            Mode::Normal => write!(f, "NORMAL"),
 28            Mode::Insert => write!(f, "INSERT"),
 29            Mode::Replace => write!(f, "REPLACE"),
 30            Mode::Visual => write!(f, "VISUAL"),
 31            Mode::VisualLine => write!(f, "VISUAL LINE"),
 32            Mode::VisualBlock => write!(f, "VISUAL BLOCK"),
 33        }
 34    }
 35}
 36
 37impl Mode {
 38    pub fn is_visual(&self) -> bool {
 39        match self {
 40            Mode::Normal | Mode::Insert | Mode::Replace => false,
 41            Mode::Visual | Mode::VisualLine | Mode::VisualBlock => true,
 42        }
 43    }
 44}
 45
 46impl Default for Mode {
 47    fn default() -> Self {
 48        Self::Normal
 49    }
 50}
 51
 52#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
 53pub enum Operator {
 54    Change,
 55    Delete,
 56    Yank,
 57    Replace,
 58    Object { around: bool },
 59    FindForward { before: bool },
 60    FindBackward { after: bool },
 61    AddSurrounds { target: Option<SurroundsType> },
 62    ChangeSurrounds { target: Option<Object> },
 63    DeleteSurrounds,
 64    Mark,
 65    Jump { line: bool },
 66    Indent,
 67    Outdent,
 68    Lowercase,
 69    Uppercase,
 70    OppositeCase,
 71    Register,
 72    RecordRegister,
 73    ReplayRegister,
 74}
 75
 76#[derive(Default, Clone)]
 77pub struct EditorState {
 78    pub mode: Mode,
 79    pub last_mode: Mode,
 80
 81    /// pre_count is the number before an operator is specified (3 in 3d2d)
 82    pub pre_count: Option<usize>,
 83    /// post_count is the number after an operator is specified (2 in 3d2d)
 84    pub post_count: Option<usize>,
 85
 86    pub operator_stack: Vec<Operator>,
 87    pub replacements: Vec<(Range<editor::Anchor>, String)>,
 88
 89    pub marks: HashMap<String, Vec<Anchor>>,
 90    pub stored_visual_mode: Option<(Mode, Vec<bool>)>,
 91    pub change_list: Vec<Vec<Anchor>>,
 92    pub change_list_position: Option<usize>,
 93
 94    pub current_tx: Option<TransactionId>,
 95    pub current_anchor: Option<Selection<Anchor>>,
 96    pub undo_modes: HashMap<TransactionId, Mode>,
 97
 98    pub selected_register: Option<char>,
 99    pub search: SearchState,
100}
101
102#[derive(Default, Clone, Debug)]
103pub enum RecordedSelection {
104    #[default]
105    None,
106    Visual {
107        rows: u32,
108        cols: u32,
109    },
110    SingleLine {
111        cols: u32,
112    },
113    VisualBlock {
114        rows: u32,
115        cols: u32,
116    },
117    VisualLine {
118        rows: u32,
119    },
120}
121
122#[derive(Default, Clone, Debug)]
123pub struct Register {
124    pub(crate) text: SharedString,
125    pub(crate) clipboard_selections: Option<Vec<ClipboardSelection>>,
126}
127
128impl From<Register> for ClipboardItem {
129    fn from(register: Register) -> Self {
130        let item = ClipboardItem::new(register.text.into());
131        if let Some(clipboard_selections) = register.clipboard_selections {
132            item.with_metadata(clipboard_selections)
133        } else {
134            item
135        }
136    }
137}
138
139impl From<ClipboardItem> for Register {
140    fn from(value: ClipboardItem) -> Self {
141        Register {
142            text: value.text().to_owned().into(),
143            clipboard_selections: value.metadata::<Vec<ClipboardSelection>>(),
144        }
145    }
146}
147
148impl From<String> for Register {
149    fn from(text: String) -> Self {
150        Register {
151            text: text.into(),
152            clipboard_selections: None,
153        }
154    }
155}
156
157#[derive(Default, Clone)]
158pub struct WorkspaceState {
159    pub last_find: Option<Motion>,
160
161    pub dot_recording: bool,
162    pub dot_replaying: bool,
163
164    pub stop_recording_after_next_action: bool,
165    pub ignore_current_insertion: bool,
166    pub recorded_count: Option<usize>,
167    pub recorded_actions: Vec<ReplayableAction>,
168    pub recorded_selection: RecordedSelection,
169
170    pub recording_register: Option<char>,
171    pub last_recorded_register: Option<char>,
172    pub last_replayed_register: Option<char>,
173    pub replayer: Option<Replayer>,
174
175    pub last_yank: Option<SharedString>,
176    pub registers: HashMap<char, Register>,
177    pub recordings: HashMap<char, Vec<ReplayableAction>>,
178}
179
180#[derive(Debug)]
181pub enum ReplayableAction {
182    Action(Box<dyn Action>),
183    Insertion {
184        text: Arc<str>,
185        utf16_range_to_replace: Option<Range<isize>>,
186    },
187}
188
189impl Clone for ReplayableAction {
190    fn clone(&self) -> Self {
191        match self {
192            Self::Action(action) => Self::Action(action.boxed_clone()),
193            Self::Insertion {
194                text,
195                utf16_range_to_replace,
196            } => Self::Insertion {
197                text: text.clone(),
198                utf16_range_to_replace: utf16_range_to_replace.clone(),
199            },
200        }
201    }
202}
203
204#[derive(Clone, Default, Debug)]
205pub struct SearchState {
206    pub direction: Direction,
207    pub count: usize,
208    pub initial_query: String,
209
210    pub prior_selections: Vec<Range<Anchor>>,
211    pub prior_operator: Option<Operator>,
212    pub prior_mode: Mode,
213}
214
215impl EditorState {
216    pub fn cursor_shape(&self) -> CursorShape {
217        match self.mode {
218            Mode::Normal => {
219                if self.operator_stack.is_empty() {
220                    CursorShape::Block
221                } else {
222                    CursorShape::Underscore
223                }
224            }
225            Mode::Replace => CursorShape::Underscore,
226            Mode::Visual | Mode::VisualLine | Mode::VisualBlock => CursorShape::Block,
227            Mode::Insert => CursorShape::Bar,
228        }
229    }
230
231    pub fn editor_input_enabled(&self) -> bool {
232        match self.mode {
233            Mode::Insert => {
234                if let Some(operator) = self.operator_stack.last() {
235                    !operator.is_waiting(self.mode)
236                } else {
237                    true
238                }
239            }
240            Mode::Normal | Mode::Replace | Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
241                false
242            }
243        }
244    }
245
246    pub fn should_autoindent(&self) -> bool {
247        !(self.mode == Mode::Insert && self.last_mode == Mode::VisualBlock)
248    }
249
250    pub fn clip_at_line_ends(&self) -> bool {
251        match self.mode {
252            Mode::Insert | Mode::Visual | Mode::VisualLine | Mode::VisualBlock | Mode::Replace => {
253                false
254            }
255            Mode::Normal => true,
256        }
257    }
258
259    pub fn active_operator(&self) -> Option<Operator> {
260        self.operator_stack.last().cloned()
261    }
262
263    pub fn keymap_context_layer(&self) -> KeyContext {
264        let mut context = KeyContext::new_with_defaults();
265
266        let mut mode = match self.mode {
267            Mode::Normal => "normal",
268            Mode::Visual | Mode::VisualLine | Mode::VisualBlock => "visual",
269            Mode::Insert => "insert",
270            Mode::Replace => "replace",
271        }
272        .to_string();
273
274        let mut operator_id = "none";
275
276        let active_operator = self.active_operator();
277        if active_operator.is_none() && self.pre_count.is_some()
278            || active_operator.is_some() && self.post_count.is_some()
279        {
280            context.add("VimCount");
281        }
282
283        if let Some(active_operator) = active_operator {
284            if active_operator.is_waiting(self.mode) {
285                mode = "waiting".to_string();
286            } else {
287                mode = "operator".to_string();
288                operator_id = active_operator.id();
289            }
290        }
291
292        if mode != "waiting" && mode != "insert" && mode != "replace" {
293            context.add("VimControl");
294        }
295        context.set("vim_mode", mode);
296        context.set("vim_operator", operator_id);
297
298        context
299    }
300}
301
302impl Operator {
303    pub fn id(&self) -> &'static str {
304        match self {
305            Operator::Object { around: false } => "i",
306            Operator::Object { around: true } => "a",
307            Operator::Change => "c",
308            Operator::Delete => "d",
309            Operator::Yank => "y",
310            Operator::Replace => "r",
311            Operator::FindForward { before: false } => "f",
312            Operator::FindForward { before: true } => "t",
313            Operator::FindBackward { after: false } => "F",
314            Operator::FindBackward { after: true } => "T",
315            Operator::AddSurrounds { .. } => "ys",
316            Operator::ChangeSurrounds { .. } => "cs",
317            Operator::DeleteSurrounds => "ds",
318            Operator::Mark => "m",
319            Operator::Jump { line: true } => "'",
320            Operator::Jump { line: false } => "`",
321            Operator::Indent => ">",
322            Operator::Outdent => "<",
323            Operator::Uppercase => "gU",
324            Operator::Lowercase => "gu",
325            Operator::OppositeCase => "g~",
326            Operator::Register => "\"",
327            Operator::RecordRegister => "q",
328            Operator::ReplayRegister => "@",
329        }
330    }
331
332    pub fn is_waiting(&self, mode: Mode) -> bool {
333        match self {
334            Operator::AddSurrounds { target } => target.is_some() || mode.is_visual(),
335            Operator::FindForward { .. }
336            | Operator::Mark
337            | Operator::Jump { .. }
338            | Operator::FindBackward { .. }
339            | Operator::Register
340            | Operator::RecordRegister
341            | Operator::ReplayRegister
342            | Operator::Replace
343            | Operator::ChangeSurrounds { target: Some(_) }
344            | Operator::DeleteSurrounds => true,
345            Operator::Change
346            | Operator::Delete
347            | Operator::Yank
348            | Operator::Indent
349            | Operator::Outdent
350            | Operator::Lowercase
351            | Operator::Uppercase
352            | Operator::Object { .. }
353            | Operator::ChangeSurrounds { target: None }
354            | Operator::OppositeCase => false,
355        }
356    }
357}