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