1use std::borrow::BorrowMut;
2use std::{fmt::Display, ops::Range, sync::Arc};
3
4use crate::command::command_interceptor;
5use crate::normal::repeat::Replayer;
6use crate::surrounds::SurroundsType;
7use crate::{motion::Motion, object::Object};
8use crate::{UseSystemClipboard, Vim, VimSettings};
9use collections::HashMap;
10use command_palette_hooks::{CommandPaletteFilter, CommandPaletteInterceptor};
11use editor::{Anchor, ClipboardSelection, Editor};
12use gpui::{
13 Action, AppContext, BorrowAppContext, ClipboardEntry, ClipboardItem, Global, View, WeakView,
14};
15use language::Point;
16use serde::{Deserialize, Serialize};
17use settings::{Settings, SettingsStore};
18use ui::{SharedString, ViewContext};
19use workspace::searchable::Direction;
20
21#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)]
22pub enum Mode {
23 Normal,
24 Insert,
25 Replace,
26 Visual,
27 VisualLine,
28 VisualBlock,
29 HelixNormal,
30}
31
32impl Display for Mode {
33 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
34 match self {
35 Mode::Normal => write!(f, "NORMAL"),
36 Mode::Insert => write!(f, "INSERT"),
37 Mode::Replace => write!(f, "REPLACE"),
38 Mode::Visual => write!(f, "VISUAL"),
39 Mode::VisualLine => write!(f, "VISUAL LINE"),
40 Mode::VisualBlock => write!(f, "VISUAL BLOCK"),
41 Mode::HelixNormal => write!(f, "HELIX NORMAL"),
42 }
43 }
44}
45
46impl Mode {
47 pub fn is_visual(&self) -> bool {
48 match self {
49 Mode::Normal | Mode::Insert | Mode::Replace => false,
50 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => true,
51 Mode::HelixNormal => false,
52 }
53 }
54}
55
56impl Default for Mode {
57 fn default() -> Self {
58 Self::Normal
59 }
60}
61
62#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
63pub enum Operator {
64 Change,
65 Delete,
66 Yank,
67 Replace,
68 Object { around: bool },
69 FindForward { before: bool },
70 FindBackward { after: bool },
71 AddSurrounds { target: Option<SurroundsType> },
72 ChangeSurrounds { target: Option<Object> },
73 DeleteSurrounds,
74 Mark,
75 Jump { line: bool },
76 Indent,
77 Outdent,
78 AutoIndent,
79 Rewrap,
80 Lowercase,
81 Uppercase,
82 OppositeCase,
83 Digraph { first_char: Option<char> },
84 Literal { prefix: Option<String> },
85 Register,
86 RecordRegister,
87 ReplayRegister,
88 ToggleComments,
89}
90
91#[derive(Default, Clone, Debug)]
92pub enum RecordedSelection {
93 #[default]
94 None,
95 Visual {
96 rows: u32,
97 cols: u32,
98 },
99 SingleLine {
100 cols: u32,
101 },
102 VisualBlock {
103 rows: u32,
104 cols: u32,
105 },
106 VisualLine {
107 rows: u32,
108 },
109}
110
111#[derive(Default, Clone, Debug)]
112pub struct Register {
113 pub(crate) text: SharedString,
114 pub(crate) clipboard_selections: Option<Vec<ClipboardSelection>>,
115}
116
117impl From<Register> for ClipboardItem {
118 fn from(register: Register) -> Self {
119 if let Some(clipboard_selections) = register.clipboard_selections {
120 ClipboardItem::new_string_with_json_metadata(register.text.into(), clipboard_selections)
121 } else {
122 ClipboardItem::new_string(register.text.into())
123 }
124 }
125}
126
127impl From<ClipboardItem> for Register {
128 fn from(item: ClipboardItem) -> Self {
129 // For now, we don't store metadata for multiple entries.
130 match item.entries().first() {
131 Some(ClipboardEntry::String(value)) if item.entries().len() == 1 => Register {
132 text: value.text().to_owned().into(),
133 clipboard_selections: value.metadata_json::<Vec<ClipboardSelection>>(),
134 },
135 // For now, registers can't store images. This could change in the future.
136 _ => Register::default(),
137 }
138 }
139}
140
141impl From<String> for Register {
142 fn from(text: String) -> Self {
143 Register {
144 text: text.into(),
145 clipboard_selections: None,
146 }
147 }
148}
149
150#[derive(Default, Clone)]
151pub struct VimGlobals {
152 pub last_find: Option<Motion>,
153
154 pub dot_recording: bool,
155 pub dot_replaying: bool,
156
157 /// pre_count is the number before an operator is specified (3 in 3d2d)
158 pub pre_count: Option<usize>,
159 /// post_count is the number after an operator is specified (2 in 3d2d)
160 pub post_count: Option<usize>,
161
162 pub stop_recording_after_next_action: bool,
163 pub ignore_current_insertion: bool,
164 pub recorded_count: Option<usize>,
165 pub recording_actions: Vec<ReplayableAction>,
166 pub recorded_actions: Vec<ReplayableAction>,
167 pub recorded_selection: RecordedSelection,
168
169 pub recording_register: Option<char>,
170 pub last_recorded_register: Option<char>,
171 pub last_replayed_register: Option<char>,
172 pub replayer: Option<Replayer>,
173
174 pub last_yank: Option<SharedString>,
175 pub registers: HashMap<char, Register>,
176 pub recordings: HashMap<char, Vec<ReplayableAction>>,
177
178 pub focused_vim: Option<WeakView<Vim>>,
179}
180impl Global for VimGlobals {}
181
182impl VimGlobals {
183 pub(crate) fn register(cx: &mut AppContext) {
184 cx.set_global(VimGlobals::default());
185
186 cx.observe_keystrokes(|event, cx| {
187 let Some(action) = event.action.as_ref().map(|action| action.boxed_clone()) else {
188 return;
189 };
190 Vim::globals(cx).observe_action(action.boxed_clone())
191 })
192 .detach();
193
194 cx.observe_global::<SettingsStore>(move |cx| {
195 if Vim::enabled(cx) {
196 CommandPaletteFilter::update_global(cx, |filter, _| {
197 filter.show_namespace(Vim::NAMESPACE);
198 });
199 CommandPaletteInterceptor::update_global(cx, |interceptor, _| {
200 interceptor.set(Box::new(command_interceptor));
201 });
202 } else {
203 *Vim::globals(cx) = VimGlobals::default();
204 CommandPaletteInterceptor::update_global(cx, |interceptor, _| {
205 interceptor.clear();
206 });
207 CommandPaletteFilter::update_global(cx, |filter, _| {
208 filter.hide_namespace(Vim::NAMESPACE);
209 });
210 }
211 })
212 .detach();
213 }
214
215 pub(crate) fn write_registers(
216 &mut self,
217 content: Register,
218 register: Option<char>,
219 is_yank: bool,
220 linewise: bool,
221 cx: &mut ViewContext<Editor>,
222 ) {
223 if let Some(register) = register {
224 let lower = register.to_lowercase().next().unwrap_or(register);
225 if lower != register {
226 let current = self.registers.entry(lower).or_default();
227 current.text = (current.text.to_string() + &content.text).into();
228 // not clear how to support appending to registers with multiple cursors
229 current.clipboard_selections.take();
230 let yanked = current.clone();
231 self.registers.insert('"', yanked);
232 } else {
233 match lower {
234 '_' | ':' | '.' | '%' | '#' | '=' | '/' => {}
235 '+' => {
236 self.registers.insert('"', content.clone());
237 cx.write_to_clipboard(content.into());
238 }
239 '*' => {
240 self.registers.insert('"', content.clone());
241 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
242 cx.write_to_primary(content.into());
243 #[cfg(not(any(target_os = "linux", target_os = "freebsd")))]
244 cx.write_to_clipboard(content.into());
245 }
246 '"' => {
247 self.registers.insert('"', content.clone());
248 self.registers.insert('0', content);
249 }
250 _ => {
251 self.registers.insert('"', content.clone());
252 self.registers.insert(lower, content);
253 }
254 }
255 }
256 } else {
257 let setting = VimSettings::get_global(cx).use_system_clipboard;
258 if setting == UseSystemClipboard::Always
259 || setting == UseSystemClipboard::OnYank && is_yank
260 {
261 self.last_yank.replace(content.text.clone());
262 cx.write_to_clipboard(content.clone().into());
263 } else {
264 self.last_yank = cx
265 .read_from_clipboard()
266 .and_then(|item| item.text().map(|string| string.into()));
267 }
268
269 self.registers.insert('"', content.clone());
270 if is_yank {
271 self.registers.insert('0', content);
272 } else {
273 let contains_newline = content.text.contains('\n');
274 if !contains_newline {
275 self.registers.insert('-', content.clone());
276 }
277 if linewise || contains_newline {
278 let mut content = content;
279 for i in '1'..'8' {
280 if let Some(moved) = self.registers.insert(i, content) {
281 content = moved;
282 } else {
283 break;
284 }
285 }
286 }
287 }
288 }
289 }
290
291 pub(crate) fn read_register(
292 &mut self,
293 register: Option<char>,
294 editor: Option<&mut Editor>,
295 cx: &mut ViewContext<Editor>,
296 ) -> Option<Register> {
297 let Some(register) = register.filter(|reg| *reg != '"') else {
298 let setting = VimSettings::get_global(cx).use_system_clipboard;
299 return match setting {
300 UseSystemClipboard::Always => cx.read_from_clipboard().map(|item| item.into()),
301 UseSystemClipboard::OnYank if self.system_clipboard_is_newer(cx) => {
302 cx.read_from_clipboard().map(|item| item.into())
303 }
304 _ => self.registers.get(&'"').cloned(),
305 };
306 };
307 let lower = register.to_lowercase().next().unwrap_or(register);
308 match lower {
309 '_' | ':' | '.' | '#' | '=' => None,
310 '+' => cx.read_from_clipboard().map(|item| item.into()),
311 '*' => {
312 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
313 {
314 cx.read_from_primary().map(|item| item.into())
315 }
316 #[cfg(not(any(target_os = "linux", target_os = "freebsd")))]
317 {
318 cx.read_from_clipboard().map(|item| item.into())
319 }
320 }
321 '%' => editor.and_then(|editor| {
322 let selection = editor.selections.newest::<Point>(cx);
323 if let Some((_, buffer, _)) = editor
324 .buffer()
325 .read(cx)
326 .excerpt_containing(selection.head(), cx)
327 {
328 buffer
329 .read(cx)
330 .file()
331 .map(|file| file.path().to_string_lossy().to_string().into())
332 } else {
333 None
334 }
335 }),
336 _ => self.registers.get(&lower).cloned(),
337 }
338 }
339
340 fn system_clipboard_is_newer(&self, cx: &ViewContext<Editor>) -> bool {
341 cx.read_from_clipboard().is_some_and(|item| {
342 if let Some(last_state) = &self.last_yank {
343 Some(last_state.as_ref()) != item.text().as_deref()
344 } else {
345 true
346 }
347 })
348 }
349
350 pub fn observe_action(&mut self, action: Box<dyn Action>) {
351 if self.dot_recording {
352 self.recording_actions
353 .push(ReplayableAction::Action(action.boxed_clone()));
354
355 if self.stop_recording_after_next_action {
356 self.dot_recording = false;
357 self.recorded_actions = std::mem::take(&mut self.recording_actions);
358 self.stop_recording_after_next_action = false;
359 }
360 }
361 if self.replayer.is_none() {
362 if let Some(recording_register) = self.recording_register {
363 self.recordings
364 .entry(recording_register)
365 .or_default()
366 .push(ReplayableAction::Action(action));
367 }
368 }
369 }
370
371 pub fn observe_insertion(&mut self, text: &Arc<str>, range_to_replace: Option<Range<isize>>) {
372 if self.ignore_current_insertion {
373 self.ignore_current_insertion = false;
374 return;
375 }
376 if self.dot_recording {
377 self.recording_actions.push(ReplayableAction::Insertion {
378 text: text.clone(),
379 utf16_range_to_replace: range_to_replace.clone(),
380 });
381 if self.stop_recording_after_next_action {
382 self.dot_recording = false;
383 self.recorded_actions = std::mem::take(&mut self.recording_actions);
384 self.stop_recording_after_next_action = false;
385 }
386 }
387 if let Some(recording_register) = self.recording_register {
388 self.recordings.entry(recording_register).or_default().push(
389 ReplayableAction::Insertion {
390 text: text.clone(),
391 utf16_range_to_replace: range_to_replace,
392 },
393 );
394 }
395 }
396
397 pub fn focused_vim(&self) -> Option<View<Vim>> {
398 self.focused_vim.as_ref().and_then(|vim| vim.upgrade())
399 }
400}
401
402impl Vim {
403 pub fn globals(cx: &mut AppContext) -> &mut VimGlobals {
404 cx.global_mut::<VimGlobals>()
405 }
406
407 pub fn update_globals<C, R>(cx: &mut C, f: impl FnOnce(&mut VimGlobals, &mut C) -> R) -> R
408 where
409 C: BorrowMut<AppContext>,
410 {
411 cx.update_global(f)
412 }
413}
414
415#[derive(Debug)]
416pub enum ReplayableAction {
417 Action(Box<dyn Action>),
418 Insertion {
419 text: Arc<str>,
420 utf16_range_to_replace: Option<Range<isize>>,
421 },
422}
423
424impl Clone for ReplayableAction {
425 fn clone(&self) -> Self {
426 match self {
427 Self::Action(action) => Self::Action(action.boxed_clone()),
428 Self::Insertion {
429 text,
430 utf16_range_to_replace,
431 } => Self::Insertion {
432 text: text.clone(),
433 utf16_range_to_replace: utf16_range_to_replace.clone(),
434 },
435 }
436 }
437}
438
439#[derive(Clone, Default, Debug)]
440pub struct SearchState {
441 pub direction: Direction,
442 pub count: usize,
443 pub initial_query: String,
444
445 pub prior_selections: Vec<Range<Anchor>>,
446 pub prior_operator: Option<Operator>,
447 pub prior_mode: Mode,
448}
449
450impl Operator {
451 pub fn id(&self) -> &'static str {
452 match self {
453 Operator::Object { around: false } => "i",
454 Operator::Object { around: true } => "a",
455 Operator::Change => "c",
456 Operator::Delete => "d",
457 Operator::Yank => "y",
458 Operator::Replace => "r",
459 Operator::Digraph { .. } => "^K",
460 Operator::Literal { .. } => "^V",
461 Operator::FindForward { before: false } => "f",
462 Operator::FindForward { before: true } => "t",
463 Operator::FindBackward { after: false } => "F",
464 Operator::FindBackward { after: true } => "T",
465 Operator::AddSurrounds { .. } => "ys",
466 Operator::ChangeSurrounds { .. } => "cs",
467 Operator::DeleteSurrounds => "ds",
468 Operator::Mark => "m",
469 Operator::Jump { line: true } => "'",
470 Operator::Jump { line: false } => "`",
471 Operator::Indent => ">",
472 Operator::AutoIndent => "eq",
473 Operator::Rewrap => "gq",
474 Operator::Outdent => "<",
475 Operator::Uppercase => "gU",
476 Operator::Lowercase => "gu",
477 Operator::OppositeCase => "g~",
478 Operator::Register => "\"",
479 Operator::RecordRegister => "q",
480 Operator::ReplayRegister => "@",
481 Operator::ToggleComments => "gc",
482 }
483 }
484
485 pub fn status(&self) -> String {
486 match self {
487 Operator::Digraph {
488 first_char: Some(first_char),
489 } => format!("^K{first_char}"),
490 Operator::Literal {
491 prefix: Some(prefix),
492 } => format!("^V{prefix}"),
493 Operator::AutoIndent => "=".to_string(),
494 _ => self.id().to_string(),
495 }
496 }
497
498 pub fn is_waiting(&self, mode: Mode) -> bool {
499 match self {
500 Operator::AddSurrounds { target } => target.is_some() || mode.is_visual(),
501 Operator::FindForward { .. }
502 | Operator::Mark
503 | Operator::Jump { .. }
504 | Operator::FindBackward { .. }
505 | Operator::Register
506 | Operator::RecordRegister
507 | Operator::ReplayRegister
508 | Operator::Replace
509 | Operator::Digraph { .. }
510 | Operator::Literal { .. }
511 | Operator::ChangeSurrounds { target: Some(_) }
512 | Operator::DeleteSurrounds => true,
513 Operator::Change
514 | Operator::Delete
515 | Operator::Yank
516 | Operator::Rewrap
517 | Operator::Indent
518 | Operator::Outdent
519 | Operator::AutoIndent
520 | Operator::Lowercase
521 | Operator::Uppercase
522 | Operator::Object { .. }
523 | Operator::ChangeSurrounds { target: None }
524 | Operator::OppositeCase
525 | Operator::ToggleComments => false,
526 }
527 }
528}