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