state.rs

  1use std::{fmt::Display, ops::Range, sync::Arc};
  2
  3use crate::surrounds::SurroundsType;
  4use crate::{motion::Motion, object::Object};
  5use collections::HashMap;
  6use editor::Anchor;
  7use gpui::{Action, KeyContext};
  8use language::{CursorShape, Selection, TransactionId};
  9use serde::{Deserialize, Serialize};
 10use workspace::searchable::Direction;
 11
 12#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)]
 13pub enum Mode {
 14    Normal,
 15    Insert,
 16    Replace,
 17    Visual,
 18    VisualLine,
 19    VisualBlock,
 20}
 21
 22impl Display for Mode {
 23    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 24        match self {
 25            Mode::Normal => write!(f, "NORMAL"),
 26            Mode::Insert => write!(f, "INSERT"),
 27            Mode::Replace => write!(f, "REPLACE"),
 28            Mode::Visual => write!(f, "VISUAL"),
 29            Mode::VisualLine => write!(f, "VISUAL LINE"),
 30            Mode::VisualBlock => write!(f, "VISUAL BLOCK"),
 31        }
 32    }
 33}
 34
 35impl Mode {
 36    pub fn is_visual(&self) -> bool {
 37        match self {
 38            Mode::Normal | Mode::Insert | Mode::Replace => false,
 39            Mode::Visual | Mode::VisualLine | Mode::VisualBlock => true,
 40        }
 41    }
 42}
 43
 44impl Default for Mode {
 45    fn default() -> Self {
 46        Self::Normal
 47    }
 48}
 49
 50#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
 51pub enum Operator {
 52    Change,
 53    Delete,
 54    Yank,
 55    Replace,
 56    Object { around: bool },
 57    FindForward { before: bool },
 58    FindBackward { after: bool },
 59    AddSurrounds { target: Option<SurroundsType> },
 60    ChangeSurrounds { target: Option<Object> },
 61    DeleteSurrounds,
 62    Mark,
 63    Jump { line: bool },
 64}
 65
 66#[derive(Default, Clone)]
 67pub struct EditorState {
 68    pub mode: Mode,
 69    pub last_mode: Mode,
 70
 71    /// pre_count is the number before an operator is specified (3 in 3d2d)
 72    pub pre_count: Option<usize>,
 73    /// post_count is the number after an operator is specified (2 in 3d2d)
 74    pub post_count: Option<usize>,
 75
 76    pub operator_stack: Vec<Operator>,
 77    pub replacements: Vec<(Range<editor::Anchor>, String)>,
 78
 79    pub marks: HashMap<String, Vec<Anchor>>,
 80
 81    pub current_tx: Option<TransactionId>,
 82    pub current_anchor: Option<Selection<Anchor>>,
 83    pub undo_modes: HashMap<TransactionId, Mode>,
 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)]
107pub struct WorkspaceState {
108    pub search: SearchState,
109    pub last_find: Option<Motion>,
110
111    pub recording: bool,
112    pub stop_recording_after_next_action: bool,
113    pub replaying: bool,
114    pub recorded_count: Option<usize>,
115    pub recorded_actions: Vec<ReplayableAction>,
116    pub recorded_selection: RecordedSelection,
117
118    pub registers: HashMap<String, String>,
119}
120
121#[derive(Debug)]
122pub enum ReplayableAction {
123    Action(Box<dyn Action>),
124    Insertion {
125        text: Arc<str>,
126        utf16_range_to_replace: Option<Range<isize>>,
127    },
128}
129
130impl Clone for ReplayableAction {
131    fn clone(&self) -> Self {
132        match self {
133            Self::Action(action) => Self::Action(action.boxed_clone()),
134            Self::Insertion {
135                text,
136                utf16_range_to_replace,
137            } => Self::Insertion {
138                text: text.clone(),
139                utf16_range_to_replace: utf16_range_to_replace.clone(),
140            },
141        }
142    }
143}
144
145#[derive(Clone, Default, Debug)]
146pub struct SearchState {
147    pub direction: Direction,
148    pub count: usize,
149    pub initial_query: String,
150
151    pub prior_selections: Vec<Range<Anchor>>,
152    pub prior_operator: Option<Operator>,
153    pub prior_mode: Mode,
154}
155
156impl EditorState {
157    pub fn cursor_shape(&self) -> CursorShape {
158        match self.mode {
159            Mode::Normal => {
160                if self.operator_stack.is_empty() {
161                    CursorShape::Block
162                } else {
163                    CursorShape::Underscore
164                }
165            }
166            Mode::Replace => CursorShape::Underscore,
167            Mode::Visual | Mode::VisualLine | Mode::VisualBlock => CursorShape::Block,
168            Mode::Insert => CursorShape::Bar,
169        }
170    }
171
172    pub fn vim_controlled(&self) -> bool {
173        let is_insert_mode = matches!(self.mode, Mode::Insert);
174        if !is_insert_mode {
175            return true;
176        }
177        matches!(
178            self.operator_stack.last(),
179            Some(Operator::FindForward { .. })
180                | Some(Operator::FindBackward { .. })
181                | Some(Operator::Mark)
182                | Some(Operator::Jump { .. })
183        )
184    }
185
186    pub fn should_autoindent(&self) -> bool {
187        !(self.mode == Mode::Insert && self.last_mode == Mode::VisualBlock)
188    }
189
190    pub fn clip_at_line_ends(&self) -> bool {
191        match self.mode {
192            Mode::Insert | Mode::Visual | Mode::VisualLine | Mode::VisualBlock | Mode::Replace => {
193                false
194            }
195            Mode::Normal => true,
196        }
197    }
198
199    pub fn active_operator(&self) -> Option<Operator> {
200        self.operator_stack.last().cloned()
201    }
202
203    pub fn keymap_context_layer(&self) -> KeyContext {
204        let mut context = KeyContext::new_with_defaults();
205        context.set(
206            "vim_mode",
207            match self.mode {
208                Mode::Normal => "normal",
209                Mode::Visual | Mode::VisualLine | Mode::VisualBlock => "visual",
210                Mode::Insert => "insert",
211                Mode::Replace => "replace",
212            },
213        );
214
215        if self.vim_controlled() {
216            context.add("VimControl");
217        }
218
219        if self.active_operator().is_none() && self.pre_count.is_some()
220            || self.active_operator().is_some() && self.post_count.is_some()
221        {
222            context.add("VimCount");
223        }
224
225        let active_operator = self.active_operator();
226
227        if let Some(active_operator) = active_operator.clone() {
228            for context_flag in active_operator.context_flags().into_iter() {
229                context.add(*context_flag);
230            }
231        }
232
233        context.set(
234            "vim_operator",
235            active_operator
236                .clone()
237                .map(|op| op.id())
238                .unwrap_or_else(|| "none"),
239        );
240
241        if self.mode == Mode::Replace {
242            context.add("VimWaiting");
243        }
244        context
245    }
246}
247
248impl Operator {
249    pub fn id(&self) -> &'static str {
250        match self {
251            Operator::Object { around: false } => "i",
252            Operator::Object { around: true } => "a",
253            Operator::Change => "c",
254            Operator::Delete => "d",
255            Operator::Yank => "y",
256            Operator::Replace => "r",
257            Operator::FindForward { before: false } => "f",
258            Operator::FindForward { before: true } => "t",
259            Operator::FindBackward { after: false } => "F",
260            Operator::FindBackward { after: true } => "T",
261            Operator::AddSurrounds { .. } => "ys",
262            Operator::ChangeSurrounds { .. } => "cs",
263            Operator::DeleteSurrounds => "ds",
264            Operator::Mark => "m",
265            Operator::Jump { line: true } => "'",
266            Operator::Jump { line: false } => "`",
267        }
268    }
269
270    pub fn context_flags(&self) -> &'static [&'static str] {
271        match self {
272            Operator::Object { .. } | Operator::ChangeSurrounds { target: None } => &["VimObject"],
273            Operator::FindForward { .. }
274            | Operator::Mark
275            | Operator::Jump { .. }
276            | Operator::FindBackward { .. }
277            | Operator::Replace
278            | Operator::AddSurrounds { target: Some(_) }
279            | Operator::ChangeSurrounds { .. }
280            | Operator::DeleteSurrounds => &["VimWaiting"],
281            _ => &[],
282        }
283    }
284}