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 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 let item = ClipboardItem::new(register.text.into());
133 if let Some(clipboard_selections) = register.clipboard_selections {
134 item.with_metadata(clipboard_selections)
135 } else {
136 item
137 }
138 }
139}
140
141impl From<ClipboardItem> for Register {
142 fn from(value: ClipboardItem) -> Self {
143 Register {
144 text: value.text().to_owned().into(),
145 clipboard_selections: value.metadata::<Vec<ClipboardSelection>>(),
146 }
147 }
148}
149
150impl From<String> for Register {
151 fn from(text: String) -> Self {
152 Register {
153 text: text.into(),
154 clipboard_selections: None,
155 }
156 }
157}
158
159#[derive(Default, Clone)]
160pub struct WorkspaceState {
161 pub last_find: Option<Motion>,
162
163 pub dot_recording: bool,
164 pub dot_replaying: bool,
165
166 pub stop_recording_after_next_action: bool,
167 pub ignore_current_insertion: bool,
168 pub recorded_count: Option<usize>,
169 pub recorded_actions: Vec<ReplayableAction>,
170 pub recorded_selection: RecordedSelection,
171
172 pub recording_register: Option<char>,
173 pub last_recorded_register: Option<char>,
174 pub last_replayed_register: Option<char>,
175 pub replayer: Option<Replayer>,
176
177 pub last_yank: Option<SharedString>,
178 pub registers: HashMap<char, Register>,
179 pub recordings: HashMap<char, Vec<ReplayableAction>>,
180}
181
182#[derive(Debug)]
183pub enum ReplayableAction {
184 Action(Box<dyn Action>),
185 Insertion {
186 text: Arc<str>,
187 utf16_range_to_replace: Option<Range<isize>>,
188 },
189}
190
191impl Clone for ReplayableAction {
192 fn clone(&self) -> Self {
193 match self {
194 Self::Action(action) => Self::Action(action.boxed_clone()),
195 Self::Insertion {
196 text,
197 utf16_range_to_replace,
198 } => Self::Insertion {
199 text: text.clone(),
200 utf16_range_to_replace: utf16_range_to_replace.clone(),
201 },
202 }
203 }
204}
205
206#[derive(Clone, Default, Debug)]
207pub struct SearchState {
208 pub direction: Direction,
209 pub count: usize,
210 pub initial_query: String,
211
212 pub prior_selections: Vec<Range<Anchor>>,
213 pub prior_operator: Option<Operator>,
214 pub prior_mode: Mode,
215}
216
217impl EditorState {
218 pub fn cursor_shape(&self) -> CursorShape {
219 match self.mode {
220 Mode::Normal => {
221 if self.operator_stack.is_empty() {
222 CursorShape::Block
223 } else {
224 CursorShape::Underscore
225 }
226 }
227 Mode::Replace => CursorShape::Underscore,
228 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => CursorShape::Block,
229 Mode::Insert => CursorShape::Bar,
230 }
231 }
232
233 pub fn editor_input_enabled(&self) -> bool {
234 match self.mode {
235 Mode::Insert => {
236 if let Some(operator) = self.operator_stack.last() {
237 !operator.is_waiting(self.mode)
238 } else {
239 true
240 }
241 }
242 Mode::Normal | Mode::Replace | Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
243 false
244 }
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
268 let mut mode = match self.mode {
269 Mode::Normal => "normal",
270 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => "visual",
271 Mode::Insert => "insert",
272 Mode::Replace => "replace",
273 }
274 .to_string();
275
276 let mut operator_id = "none";
277
278 let active_operator = self.active_operator();
279 if active_operator.is_none() && self.pre_count.is_some()
280 || active_operator.is_some() && self.post_count.is_some()
281 {
282 context.add("VimCount");
283 }
284
285 if let Some(active_operator) = active_operator {
286 if active_operator.is_waiting(self.mode) {
287 mode = "waiting".to_string();
288 } else {
289 mode = "operator".to_string();
290 operator_id = active_operator.id();
291 }
292 }
293
294 if mode != "waiting" && mode != "insert" && mode != "replace" {
295 context.add("VimControl");
296 }
297 context.set("vim_mode", mode);
298 context.set("vim_operator", operator_id);
299
300 context
301 }
302}
303
304impl Operator {
305 pub fn id(&self) -> &'static str {
306 match self {
307 Operator::Object { around: false } => "i",
308 Operator::Object { around: true } => "a",
309 Operator::Change => "c",
310 Operator::Delete => "d",
311 Operator::Yank => "y",
312 Operator::Replace => "r",
313 Operator::Digraph { .. } => "^K",
314 Operator::FindForward { before: false } => "f",
315 Operator::FindForward { before: true } => "t",
316 Operator::FindBackward { after: false } => "F",
317 Operator::FindBackward { after: true } => "T",
318 Operator::AddSurrounds { .. } => "ys",
319 Operator::ChangeSurrounds { .. } => "cs",
320 Operator::DeleteSurrounds => "ds",
321 Operator::Mark => "m",
322 Operator::Jump { line: true } => "'",
323 Operator::Jump { line: false } => "`",
324 Operator::Indent => ">",
325 Operator::Outdent => "<",
326 Operator::Uppercase => "gU",
327 Operator::Lowercase => "gu",
328 Operator::OppositeCase => "g~",
329 Operator::Register => "\"",
330 Operator::RecordRegister => "q",
331 Operator::ReplayRegister => "@",
332 Operator::ToggleComments => "gc",
333 }
334 }
335
336 pub fn is_waiting(&self, mode: Mode) -> bool {
337 match self {
338 Operator::AddSurrounds { target } => target.is_some() || mode.is_visual(),
339 Operator::FindForward { .. }
340 | Operator::Mark
341 | Operator::Jump { .. }
342 | Operator::FindBackward { .. }
343 | Operator::Register
344 | Operator::RecordRegister
345 | Operator::ReplayRegister
346 | Operator::Replace
347 | Operator::Digraph { .. }
348 | Operator::ChangeSurrounds { target: Some(_) }
349 | Operator::DeleteSurrounds => true,
350 Operator::Change
351 | Operator::Delete
352 | Operator::Yank
353 | Operator::Indent
354 | Operator::Outdent
355 | Operator::Lowercase
356 | Operator::Uppercase
357 | Operator::Object { .. }
358 | Operator::ChangeSurrounds { target: None }
359 | Operator::OppositeCase
360 | Operator::ToggleComments => false,
361 }
362 }
363}