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}
 63
 64#[derive(Default, Clone)]
 65pub struct EditorState {
 66    pub mode: Mode,
 67    pub last_mode: Mode,
 68
 69    /// pre_count is the number before an operator is specified (3 in 3d2d)
 70    pub pre_count: Option<usize>,
 71    /// post_count is the number after an operator is specified (2 in 3d2d)
 72    pub post_count: Option<usize>,
 73
 74    pub operator_stack: Vec<Operator>,
 75    pub replacements: Vec<(Range<editor::Anchor>, String)>,
 76
 77    pub current_tx: Option<TransactionId>,
 78    pub current_anchor: Option<Selection<Anchor>>,
 79    pub undo_modes: HashMap<TransactionId, Mode>,
 80}
 81
 82#[derive(Default, Clone, Debug)]
 83pub enum RecordedSelection {
 84    #[default]
 85    None,
 86    Visual {
 87        rows: u32,
 88        cols: u32,
 89    },
 90    SingleLine {
 91        cols: u32,
 92    },
 93    VisualBlock {
 94        rows: u32,
 95        cols: u32,
 96    },
 97    VisualLine {
 98        rows: u32,
 99    },
100}
101
102#[derive(Default, Clone)]
103pub struct WorkspaceState {
104    pub search: SearchState,
105    pub last_find: Option<Motion>,
106
107    pub recording: bool,
108    pub stop_recording_after_next_action: bool,
109    pub replaying: bool,
110    pub recorded_count: Option<usize>,
111    pub recorded_actions: Vec<ReplayableAction>,
112    pub recorded_selection: RecordedSelection,
113
114    pub registers: HashMap<String, String>,
115}
116
117#[derive(Debug)]
118pub enum ReplayableAction {
119    Action(Box<dyn Action>),
120    Insertion {
121        text: Arc<str>,
122        utf16_range_to_replace: Option<Range<isize>>,
123    },
124}
125
126impl Clone for ReplayableAction {
127    fn clone(&self) -> Self {
128        match self {
129            Self::Action(action) => Self::Action(action.boxed_clone()),
130            Self::Insertion {
131                text,
132                utf16_range_to_replace,
133            } => Self::Insertion {
134                text: text.clone(),
135                utf16_range_to_replace: utf16_range_to_replace.clone(),
136            },
137        }
138    }
139}
140
141#[derive(Clone, Default, Debug)]
142pub struct SearchState {
143    pub direction: Direction,
144    pub count: usize,
145    pub initial_query: String,
146
147    pub prior_selections: Vec<Range<Anchor>>,
148    pub prior_operator: Option<Operator>,
149    pub prior_mode: Mode,
150}
151
152impl EditorState {
153    pub fn cursor_shape(&self) -> CursorShape {
154        match self.mode {
155            Mode::Normal => {
156                if self.operator_stack.is_empty() {
157                    CursorShape::Block
158                } else {
159                    CursorShape::Underscore
160                }
161            }
162            Mode::Replace => CursorShape::Underscore,
163            Mode::Visual | Mode::VisualLine | Mode::VisualBlock => CursorShape::Block,
164            Mode::Insert => CursorShape::Bar,
165        }
166    }
167
168    pub fn vim_controlled(&self) -> bool {
169        let is_insert_mode = matches!(self.mode, Mode::Insert);
170        if !is_insert_mode {
171            return true;
172        }
173        matches!(
174            self.operator_stack.last(),
175            Some(Operator::FindForward { .. }) | Some(Operator::FindBackward { .. })
176        )
177    }
178
179    pub fn should_autoindent(&self) -> bool {
180        !(self.mode == Mode::Insert && self.last_mode == Mode::VisualBlock)
181    }
182
183    pub fn clip_at_line_ends(&self) -> bool {
184        match self.mode {
185            Mode::Insert | Mode::Visual | Mode::VisualLine | Mode::VisualBlock | Mode::Replace => {
186                false
187            }
188            Mode::Normal => true,
189        }
190    }
191
192    pub fn active_operator(&self) -> Option<Operator> {
193        self.operator_stack.last().cloned()
194    }
195
196    pub fn keymap_context_layer(&self) -> KeyContext {
197        let mut context = KeyContext::default();
198        context.set(
199            "vim_mode",
200            match self.mode {
201                Mode::Normal => "normal",
202                Mode::Visual | Mode::VisualLine | Mode::VisualBlock => "visual",
203                Mode::Insert => "insert",
204                Mode::Replace => "replace",
205            },
206        );
207
208        if self.vim_controlled() {
209            context.add("VimControl");
210        }
211
212        if self.active_operator().is_none() && self.pre_count.is_some()
213            || self.active_operator().is_some() && self.post_count.is_some()
214        {
215            context.add("VimCount");
216        }
217
218        let active_operator = self.active_operator();
219
220        if let Some(active_operator) = active_operator.clone() {
221            for context_flag in active_operator.context_flags().into_iter() {
222                context.add(*context_flag);
223            }
224        }
225
226        context.set(
227            "vim_operator",
228            active_operator
229                .clone()
230                .map(|op| op.id())
231                .unwrap_or_else(|| "none"),
232        );
233
234        if self.mode == Mode::Replace {
235            context.add("VimWaiting");
236        }
237        context
238    }
239}
240
241impl Operator {
242    pub fn id(&self) -> &'static str {
243        match self {
244            Operator::Object { around: false } => "i",
245            Operator::Object { around: true } => "a",
246            Operator::Change => "c",
247            Operator::Delete => "d",
248            Operator::Yank => "y",
249            Operator::Replace => "r",
250            Operator::FindForward { before: false } => "f",
251            Operator::FindForward { before: true } => "t",
252            Operator::FindBackward { after: false } => "F",
253            Operator::FindBackward { after: true } => "T",
254            Operator::AddSurrounds { .. } => "ys",
255            Operator::ChangeSurrounds { .. } => "cs",
256            Operator::DeleteSurrounds => "ds",
257        }
258    }
259
260    pub fn context_flags(&self) -> &'static [&'static str] {
261        match self {
262            Operator::Object { .. } | Operator::ChangeSurrounds { target: None } => &["VimObject"],
263            Operator::FindForward { .. }
264            | Operator::FindBackward { .. }
265            | Operator::Replace
266            | Operator::AddSurrounds { target: Some(_) }
267            | Operator::ChangeSurrounds { .. }
268            | Operator::DeleteSurrounds => &["VimWaiting"],
269            _ => &[],
270        }
271    }
272}