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, ClipboardEntry, 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 Digraph { first_char: Option<char> },
72 Register,
73 RecordRegister,
74 ReplayRegister,
75 ToggleComments,
76}
77
78#[derive(Default, Clone)]
79pub struct EditorState {
80 pub mode: Mode,
81 pub last_mode: Mode,
82
83 /// pre_count is the number before an operator is specified (3 in 3d2d)
84 pub pre_count: Option<usize>,
85 /// post_count is the number after an operator is specified (2 in 3d2d)
86 pub post_count: Option<usize>,
87
88 pub operator_stack: Vec<Operator>,
89 pub replacements: Vec<(Range<editor::Anchor>, String)>,
90
91 pub marks: HashMap<String, Vec<Anchor>>,
92 pub stored_visual_mode: Option<(Mode, Vec<bool>)>,
93 pub change_list: Vec<Vec<Anchor>>,
94 pub change_list_position: Option<usize>,
95
96 pub current_tx: Option<TransactionId>,
97 pub current_anchor: Option<Selection<Anchor>>,
98 pub undo_modes: HashMap<TransactionId, Mode>,
99
100 pub selected_register: Option<char>,
101 pub search: SearchState,
102}
103
104#[derive(Default, Clone, Debug)]
105pub enum RecordedSelection {
106 #[default]
107 None,
108 Visual {
109 rows: u32,
110 cols: u32,
111 },
112 SingleLine {
113 cols: u32,
114 },
115 VisualBlock {
116 rows: u32,
117 cols: u32,
118 },
119 VisualLine {
120 rows: u32,
121 },
122}
123
124#[derive(Default, Clone, Debug)]
125pub struct Register {
126 pub(crate) text: SharedString,
127 pub(crate) clipboard_selections: Option<Vec<ClipboardSelection>>,
128}
129
130impl From<Register> for ClipboardItem {
131 fn from(register: Register) -> Self {
132 if let Some(clipboard_selections) = register.clipboard_selections {
133 ClipboardItem::new_string_with_json_metadata(register.text.into(), clipboard_selections)
134 } else {
135 ClipboardItem::new_string(register.text.into())
136 }
137 }
138}
139
140impl From<ClipboardItem> for Register {
141 fn from(item: ClipboardItem) -> Self {
142 // For now, we don't store metadata for multiple entries.
143 match item.entries().first() {
144 Some(ClipboardEntry::String(value)) if item.entries().len() == 1 => Register {
145 text: value.text().to_owned().into(),
146 clipboard_selections: value.metadata_json::<Vec<ClipboardSelection>>(),
147 },
148 // For now, registers can't store images. This could change in the future.
149 _ => Register::default(),
150 }
151 }
152}
153
154impl From<String> for Register {
155 fn from(text: String) -> Self {
156 Register {
157 text: text.into(),
158 clipboard_selections: None,
159 }
160 }
161}
162
163#[derive(Default, Clone)]
164pub struct WorkspaceState {
165 pub last_find: Option<Motion>,
166
167 pub dot_recording: bool,
168 pub dot_replaying: bool,
169
170 pub stop_recording_after_next_action: bool,
171 pub ignore_current_insertion: bool,
172 pub recorded_count: Option<usize>,
173 pub recorded_actions: Vec<ReplayableAction>,
174 pub recorded_selection: RecordedSelection,
175
176 pub recording_register: Option<char>,
177 pub last_recorded_register: Option<char>,
178 pub last_replayed_register: Option<char>,
179 pub replayer: Option<Replayer>,
180
181 pub last_yank: Option<SharedString>,
182 pub registers: HashMap<char, Register>,
183 pub recordings: HashMap<char, Vec<ReplayableAction>>,
184}
185
186#[derive(Debug)]
187pub enum ReplayableAction {
188 Action(Box<dyn Action>),
189 Insertion {
190 text: Arc<str>,
191 utf16_range_to_replace: Option<Range<isize>>,
192 },
193}
194
195impl Clone for ReplayableAction {
196 fn clone(&self) -> Self {
197 match self {
198 Self::Action(action) => Self::Action(action.boxed_clone()),
199 Self::Insertion {
200 text,
201 utf16_range_to_replace,
202 } => Self::Insertion {
203 text: text.clone(),
204 utf16_range_to_replace: utf16_range_to_replace.clone(),
205 },
206 }
207 }
208}
209
210#[derive(Clone, Default, Debug)]
211pub struct SearchState {
212 pub direction: Direction,
213 pub count: usize,
214 pub initial_query: String,
215
216 pub prior_selections: Vec<Range<Anchor>>,
217 pub prior_operator: Option<Operator>,
218 pub prior_mode: Mode,
219}
220
221impl EditorState {
222 pub fn cursor_shape(&self) -> CursorShape {
223 match self.mode {
224 Mode::Normal => {
225 if self.operator_stack.is_empty() {
226 CursorShape::Block
227 } else {
228 CursorShape::Underscore
229 }
230 }
231 Mode::Replace => CursorShape::Underscore,
232 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => CursorShape::Block,
233 Mode::Insert => CursorShape::Bar,
234 }
235 }
236
237 pub fn editor_input_enabled(&self) -> bool {
238 match self.mode {
239 Mode::Insert => {
240 if let Some(operator) = self.operator_stack.last() {
241 !operator.is_waiting(self.mode)
242 } else {
243 true
244 }
245 }
246 Mode::Normal | Mode::Replace | Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
247 false
248 }
249 }
250 }
251
252 pub fn should_autoindent(&self) -> bool {
253 !(self.mode == Mode::Insert && self.last_mode == Mode::VisualBlock)
254 }
255
256 pub fn clip_at_line_ends(&self) -> bool {
257 match self.mode {
258 Mode::Insert | Mode::Visual | Mode::VisualLine | Mode::VisualBlock | Mode::Replace => {
259 false
260 }
261 Mode::Normal => true,
262 }
263 }
264
265 pub fn active_operator(&self) -> Option<Operator> {
266 self.operator_stack.last().cloned()
267 }
268
269 pub fn keymap_context_layer(&self) -> KeyContext {
270 let mut context = KeyContext::new_with_defaults();
271
272 let mut mode = match self.mode {
273 Mode::Normal => "normal",
274 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => "visual",
275 Mode::Insert => "insert",
276 Mode::Replace => "replace",
277 }
278 .to_string();
279
280 let mut operator_id = "none";
281
282 let active_operator = self.active_operator();
283 if active_operator.is_none() && self.pre_count.is_some()
284 || active_operator.is_some() && self.post_count.is_some()
285 {
286 context.add("VimCount");
287 }
288
289 if let Some(active_operator) = active_operator {
290 if active_operator.is_waiting(self.mode) {
291 mode = "waiting".to_string();
292 } else {
293 mode = "operator".to_string();
294 operator_id = active_operator.id();
295 }
296 }
297
298 if mode != "waiting" && mode != "insert" && mode != "replace" {
299 context.add("VimControl");
300 }
301 context.set("vim_mode", mode);
302 context.set("vim_operator", operator_id);
303
304 context
305 }
306}
307
308impl Operator {
309 pub fn id(&self) -> &'static str {
310 match self {
311 Operator::Object { around: false } => "i",
312 Operator::Object { around: true } => "a",
313 Operator::Change => "c",
314 Operator::Delete => "d",
315 Operator::Yank => "y",
316 Operator::Replace => "r",
317 Operator::Digraph { .. } => "^K",
318 Operator::FindForward { before: false } => "f",
319 Operator::FindForward { before: true } => "t",
320 Operator::FindBackward { after: false } => "F",
321 Operator::FindBackward { after: true } => "T",
322 Operator::AddSurrounds { .. } => "ys",
323 Operator::ChangeSurrounds { .. } => "cs",
324 Operator::DeleteSurrounds => "ds",
325 Operator::Mark => "m",
326 Operator::Jump { line: true } => "'",
327 Operator::Jump { line: false } => "`",
328 Operator::Indent => ">",
329 Operator::Outdent => "<",
330 Operator::Uppercase => "gU",
331 Operator::Lowercase => "gu",
332 Operator::OppositeCase => "g~",
333 Operator::Register => "\"",
334 Operator::RecordRegister => "q",
335 Operator::ReplayRegister => "@",
336 Operator::ToggleComments => "gc",
337 }
338 }
339
340 pub fn is_waiting(&self, mode: Mode) -> bool {
341 match self {
342 Operator::AddSurrounds { target } => target.is_some() || mode.is_visual(),
343 Operator::FindForward { .. }
344 | Operator::Mark
345 | Operator::Jump { .. }
346 | Operator::FindBackward { .. }
347 | Operator::Register
348 | Operator::RecordRegister
349 | Operator::ReplayRegister
350 | Operator::Replace
351 | Operator::Digraph { .. }
352 | Operator::ChangeSurrounds { target: Some(_) }
353 | Operator::DeleteSurrounds => true,
354 Operator::Change
355 | Operator::Delete
356 | Operator::Yank
357 | Operator::Indent
358 | Operator::Outdent
359 | Operator::Lowercase
360 | Operator::Uppercase
361 | Operator::Object { .. }
362 | Operator::ChangeSurrounds { target: None }
363 | Operator::OppositeCase
364 | Operator::ToggleComments => false,
365 }
366 }
367}