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