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 vim_controlled(&self) -> bool {
232 let is_insert_mode = matches!(self.mode, Mode::Insert);
233 if !is_insert_mode {
234 return true;
235 }
236 matches!(
237 self.operator_stack.last(),
238 Some(Operator::FindForward { .. })
239 | Some(Operator::FindBackward { .. })
240 | Some(Operator::Mark)
241 | Some(Operator::Register)
242 | Some(Operator::RecordRegister)
243 | Some(Operator::ReplayRegister)
244 | Some(Operator::Jump { .. })
245 )
246 }
247
248 pub fn should_autoindent(&self) -> bool {
249 !(self.mode == Mode::Insert && self.last_mode == Mode::VisualBlock)
250 }
251
252 pub fn clip_at_line_ends(&self) -> bool {
253 match self.mode {
254 Mode::Insert | Mode::Visual | Mode::VisualLine | Mode::VisualBlock | Mode::Replace => {
255 false
256 }
257 Mode::Normal => true,
258 }
259 }
260
261 pub fn active_operator(&self) -> Option<Operator> {
262 self.operator_stack.last().cloned()
263 }
264
265 pub fn keymap_context_layer(&self) -> KeyContext {
266 let mut context = KeyContext::new_with_defaults();
267 context.set(
268 "vim_mode",
269 match self.mode {
270 Mode::Normal => "normal",
271 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => "visual",
272 Mode::Insert => "insert",
273 Mode::Replace => "replace",
274 },
275 );
276
277 if self.vim_controlled() {
278 context.add("VimControl");
279 }
280
281 if self.active_operator().is_none() && self.pre_count.is_some()
282 || self.active_operator().is_some() && self.post_count.is_some()
283 {
284 context.add("VimCount");
285 }
286
287 let active_operator = self.active_operator();
288
289 if let Some(active_operator) = active_operator.clone() {
290 for context_flag in active_operator.context_flags().into_iter() {
291 context.add(*context_flag);
292 }
293 }
294
295 context.set(
296 "vim_operator",
297 active_operator
298 .clone()
299 .map(|op| op.id())
300 .unwrap_or_else(|| "none"),
301 );
302
303 if self.mode == Mode::Replace
304 || (matches!(active_operator, Some(Operator::AddSurrounds { .. }))
305 && self.mode.is_visual())
306 {
307 context.add("VimWaiting");
308 }
309 context
310 }
311}
312
313impl Operator {
314 pub fn id(&self) -> &'static str {
315 match self {
316 Operator::Object { around: false } => "i",
317 Operator::Object { around: true } => "a",
318 Operator::Change => "c",
319 Operator::Delete => "d",
320 Operator::Yank => "y",
321 Operator::Replace => "r",
322 Operator::FindForward { before: false } => "f",
323 Operator::FindForward { before: true } => "t",
324 Operator::FindBackward { after: false } => "F",
325 Operator::FindBackward { after: true } => "T",
326 Operator::AddSurrounds { .. } => "ys",
327 Operator::ChangeSurrounds { .. } => "cs",
328 Operator::DeleteSurrounds => "ds",
329 Operator::Mark => "m",
330 Operator::Jump { line: true } => "'",
331 Operator::Jump { line: false } => "`",
332 Operator::Indent => ">",
333 Operator::Outdent => "<",
334 Operator::Uppercase => "gU",
335 Operator::Lowercase => "gu",
336 Operator::OppositeCase => "g~",
337 Operator::Register => "\"",
338 Operator::RecordRegister => "q",
339 Operator::ReplayRegister => "@",
340 }
341 }
342
343 pub fn context_flags(&self) -> &'static [&'static str] {
344 match self {
345 Operator::Object { .. } | Operator::ChangeSurrounds { target: None } => &["VimObject"],
346 Operator::FindForward { .. }
347 | Operator::Mark
348 | Operator::Jump { .. }
349 | Operator::FindBackward { .. }
350 | Operator::Register
351 | Operator::RecordRegister
352 | Operator::ReplayRegister
353 | Operator::Replace
354 | Operator::AddSurrounds { target: Some(_) }
355 | Operator::ChangeSurrounds { .. }
356 | Operator::DeleteSurrounds => &["VimWaiting"],
357 _ => &[],
358 }
359 }
360}