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