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