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