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