1use crate::command::command_interceptor;
2use crate::motion::MotionKind;
3use crate::normal::repeat::Replayer;
4use crate::surrounds::SurroundsType;
5use crate::{ToggleMarksView, ToggleRegistersView, UseSystemClipboard, Vim, VimAddon, VimSettings};
6use crate::{motion::Motion, object::Object};
7use anyhow::Result;
8use collections::HashMap;
9use command_palette_hooks::{CommandPaletteFilter, GlobalCommandPaletteInterceptor};
10use db::{
11 sqlez::{domain::Domain, thread_safe_connection::ThreadSafeConnection},
12 sqlez_macros::sql,
13};
14use editor::display_map::{is_invisible, replacement};
15use editor::{Anchor, ClipboardSelection, Editor, MultiBuffer, ToPoint as EditorToPoint};
16use gpui::{
17 Action, App, AppContext, BorrowAppContext, ClipboardEntry, ClipboardItem, DismissEvent, Entity,
18 EntityId, Global, HighlightStyle, StyledText, Subscription, Task, TextStyle, WeakEntity,
19};
20use language::{Buffer, BufferEvent, BufferId, Chunk, Point};
21
22use multi_buffer::MultiBufferRow;
23use picker::{Picker, PickerDelegate};
24use project::{Project, ProjectItem, ProjectPath};
25use serde::{Deserialize, Serialize};
26use settings::{Settings, SettingsStore};
27use std::borrow::BorrowMut;
28use std::collections::HashSet;
29use std::path::Path;
30use std::{fmt::Display, ops::Range, sync::Arc};
31use text::{Bias, ToPoint};
32use theme_settings::ThemeSettings;
33use ui::{
34 ActiveTheme, Context, Div, FluentBuilder, KeyBinding, ParentElement, SharedString, Styled,
35 StyledTypography, Window, h_flex, rems,
36};
37use util::ResultExt;
38use util::rel_path::RelPath;
39use workspace::searchable::Direction;
40use workspace::{MultiWorkspace, Workspace, WorkspaceDb, WorkspaceId};
41
42#[derive(Clone, Copy, Default, Debug, PartialEq, Serialize, Deserialize)]
43pub enum Mode {
44 #[default]
45 Normal,
46 Insert,
47 Replace,
48 Visual,
49 VisualLine,
50 VisualBlock,
51 HelixNormal,
52 HelixSelect,
53}
54
55impl Display for Mode {
56 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57 match self {
58 Mode::Normal => write!(f, "NORMAL"),
59 Mode::Insert => write!(f, "INSERT"),
60 Mode::Replace => write!(f, "REPLACE"),
61 Mode::Visual => write!(f, "VISUAL"),
62 Mode::VisualLine => write!(f, "VISUAL LINE"),
63 Mode::VisualBlock => write!(f, "VISUAL BLOCK"),
64 Mode::HelixNormal => write!(f, "NORMAL"),
65 Mode::HelixSelect => write!(f, "SELECT"),
66 }
67 }
68}
69
70impl Mode {
71 pub fn is_visual(&self) -> bool {
72 match self {
73 Self::Visual | Self::VisualLine | Self::VisualBlock | Self::HelixSelect => true,
74 Self::Normal | Self::Insert | Self::Replace | Self::HelixNormal => false,
75 }
76 }
77
78 pub fn is_helix(&self) -> bool {
79 matches!(self, Self::HelixNormal | Self::HelixSelect)
80 }
81}
82
83#[derive(Clone, Debug, PartialEq)]
84pub enum Operator {
85 Change,
86 Delete,
87 Yank,
88 Replace,
89 Object {
90 around: bool,
91 },
92 FindForward {
93 before: bool,
94 multiline: bool,
95 },
96 FindBackward {
97 after: bool,
98 multiline: bool,
99 },
100 Sneak {
101 first_char: Option<char>,
102 },
103 SneakBackward {
104 first_char: Option<char>,
105 },
106 AddSurrounds {
107 // Typically no need to configure this as `SendKeystrokes` can be used - see #23088.
108 target: Option<SurroundsType>,
109 },
110 ChangeSurrounds {
111 target: Option<Object>,
112 /// Represents whether the opening bracket was used for the target
113 /// object.
114 opening: bool,
115 },
116 DeleteSurrounds,
117 Mark,
118 Jump {
119 line: bool,
120 },
121 Indent,
122 Outdent,
123 AutoIndent,
124 Rewrap,
125 ShellCommand,
126 Lowercase,
127 Uppercase,
128 OppositeCase,
129 Rot13,
130 Rot47,
131 Digraph {
132 first_char: Option<char>,
133 },
134 Literal {
135 prefix: Option<String>,
136 },
137 Register,
138 RecordRegister,
139 ReplayRegister,
140 ToggleComments,
141 ReplaceWithRegister,
142 Exchange,
143 HelixMatch,
144 HelixNext {
145 around: bool,
146 },
147 HelixPrevious {
148 around: bool,
149 },
150 HelixSurroundAdd,
151 HelixSurroundReplace {
152 replaced_char: Option<char>,
153 },
154 HelixSurroundDelete,
155}
156
157#[derive(Default, Clone, Debug)]
158pub enum RecordedSelection {
159 #[default]
160 None,
161 Visual {
162 rows: u32,
163 cols: u32,
164 },
165 SingleLine {
166 cols: u32,
167 },
168 VisualBlock {
169 rows: u32,
170 cols: u32,
171 },
172 VisualLine {
173 rows: u32,
174 },
175}
176
177#[derive(Default, Clone, Debug)]
178pub struct Register {
179 pub(crate) text: SharedString,
180 pub(crate) clipboard_selections: Option<Vec<ClipboardSelection>>,
181}
182
183impl From<Register> for ClipboardItem {
184 fn from(register: Register) -> Self {
185 if let Some(clipboard_selections) = register.clipboard_selections {
186 ClipboardItem::new_string_with_json_metadata(register.text.into(), clipboard_selections)
187 } else {
188 ClipboardItem::new_string(register.text.into())
189 }
190 }
191}
192
193impl From<ClipboardItem> for Register {
194 fn from(item: ClipboardItem) -> Self {
195 match item.entries().iter().find_map(|entry| match entry {
196 ClipboardEntry::String(value) => Some(value),
197 _ => None,
198 }) {
199 Some(value) => Register {
200 text: value.text().to_owned().into(),
201 clipboard_selections: value.metadata_json::<Vec<ClipboardSelection>>(),
202 },
203 None => Register::default(),
204 }
205 }
206}
207
208impl From<String> for Register {
209 fn from(text: String) -> Self {
210 Register {
211 text: text.into(),
212 clipboard_selections: None,
213 }
214 }
215}
216
217#[derive(Default)]
218pub struct VimGlobals {
219 pub last_find: Option<Motion>,
220
221 pub dot_recording: bool,
222 pub dot_replaying: bool,
223
224 /// pre_count is the number before an operator is specified (3 in 3d2d)
225 pub pre_count: Option<usize>,
226 /// post_count is the number after an operator is specified (2 in 3d2d)
227 pub post_count: Option<usize>,
228 pub forced_motion: bool,
229 pub stop_recording_after_next_action: bool,
230 pub ignore_current_insertion: bool,
231 pub recording_count: Option<usize>,
232 pub recorded_count: Option<usize>,
233 pub recording_actions: Vec<ReplayableAction>,
234 pub recorded_actions: Vec<ReplayableAction>,
235 pub recorded_selection: RecordedSelection,
236
237 /// The register being written to by the active `q{register}` macro
238 /// recording.
239 pub recording_register: Option<char>,
240 /// The register that was selected at the start of the current
241 /// dot-recording, for example, `"ap`.
242 pub recording_register_for_dot: Option<char>,
243 /// The register from the last completed dot-recording. Used when replaying
244 /// with `.`.
245 pub recorded_register_for_dot: Option<char>,
246 pub last_recorded_register: Option<char>,
247 pub last_replayed_register: Option<char>,
248 pub replayer: Option<Replayer>,
249
250 pub last_yank: Option<SharedString>,
251 pub registers: HashMap<char, Register>,
252 pub recordings: HashMap<char, Vec<ReplayableAction>>,
253
254 pub focused_vim: Option<WeakEntity<Vim>>,
255
256 pub marks: HashMap<EntityId, Entity<MarksState>>,
257}
258
259pub struct MarksState {
260 workspace: WeakEntity<Workspace>,
261
262 multibuffer_marks: HashMap<EntityId, HashMap<String, Vec<Anchor>>>,
263 buffer_marks: HashMap<BufferId, HashMap<String, Vec<text::Anchor>>>,
264 watched_buffers: HashMap<BufferId, (MarkLocation, Subscription, Subscription)>,
265
266 serialized_marks: HashMap<Arc<Path>, HashMap<String, Vec<Point>>>,
267 global_marks: HashMap<String, MarkLocation>,
268
269 _subscription: Subscription,
270}
271
272#[derive(Debug, PartialEq, Eq, Clone)]
273pub enum MarkLocation {
274 Buffer(EntityId),
275 Path(Arc<Path>),
276}
277
278pub enum Mark {
279 Local(Vec<Anchor>),
280 Buffer(EntityId, Vec<Anchor>),
281 Path(Arc<Path>, Vec<Point>),
282}
283
284impl MarksState {
285 pub fn new(workspace: &Workspace, cx: &mut App) -> Entity<MarksState> {
286 cx.new(|cx| {
287 let buffer_store = workspace.project().read(cx).buffer_store().clone();
288 let subscription = cx.subscribe(&buffer_store, move |this: &mut Self, _, event, cx| {
289 if let project::buffer_store::BufferStoreEvent::BufferAdded(buffer) = event {
290 this.on_buffer_loaded(buffer, cx);
291 }
292 });
293
294 let mut this = Self {
295 workspace: workspace.weak_handle(),
296 multibuffer_marks: HashMap::default(),
297 buffer_marks: HashMap::default(),
298 watched_buffers: HashMap::default(),
299 serialized_marks: HashMap::default(),
300 global_marks: HashMap::default(),
301 _subscription: subscription,
302 };
303
304 this.load(cx);
305 this
306 })
307 }
308
309 fn workspace_id(&self, cx: &App) -> Option<WorkspaceId> {
310 self.workspace
311 .read_with(cx, |workspace, _| workspace.database_id())
312 .ok()
313 .flatten()
314 }
315
316 fn project(&self, cx: &App) -> Option<Entity<Project>> {
317 self.workspace
318 .read_with(cx, |workspace, _| workspace.project().clone())
319 .ok()
320 }
321
322 fn load(&mut self, cx: &mut Context<Self>) {
323 cx.spawn(async move |this, cx| {
324 let Some(workspace_id) = this.update(cx, |this, cx| this.workspace_id(cx)).ok()? else {
325 return None;
326 };
327 let db = cx.update(|cx| VimDb::global(cx));
328 let (marks, paths) = cx
329 .background_spawn(async move {
330 let marks = db.get_marks(workspace_id)?;
331 let paths = db.get_global_marks_paths(workspace_id)?;
332 anyhow::Ok((marks, paths))
333 })
334 .await
335 .log_err()?;
336 this.update(cx, |this, cx| this.loaded(marks, paths, cx))
337 .ok()
338 })
339 .detach();
340 }
341
342 fn loaded(
343 &mut self,
344 marks: Vec<SerializedMark>,
345 global_mark_paths: Vec<(String, Arc<Path>)>,
346 cx: &mut Context<Self>,
347 ) {
348 let Some(project) = self.project(cx) else {
349 return;
350 };
351
352 for mark in marks {
353 self.serialized_marks
354 .entry(mark.path)
355 .or_default()
356 .insert(mark.name, mark.points);
357 }
358
359 for (name, path) in global_mark_paths {
360 self.global_marks
361 .insert(name, MarkLocation::Path(path.clone()));
362
363 let project_path = project
364 .read(cx)
365 .worktrees(cx)
366 .filter_map(|worktree| {
367 let relative = path.strip_prefix(worktree.read(cx).abs_path()).ok()?;
368 let path = RelPath::new(relative, worktree.read(cx).path_style()).log_err()?;
369 Some(ProjectPath {
370 worktree_id: worktree.read(cx).id(),
371 path: path.into_arc(),
372 })
373 })
374 .next();
375 if let Some(buffer) = project_path
376 .and_then(|project_path| project.read(cx).get_open_buffer(&project_path, cx))
377 {
378 self.on_buffer_loaded(&buffer, cx)
379 }
380 }
381 }
382
383 pub fn on_buffer_loaded(&mut self, buffer_handle: &Entity<Buffer>, cx: &mut Context<Self>) {
384 let Some(project) = self.project(cx) else {
385 return;
386 };
387 let Some(project_path) = buffer_handle.read(cx).project_path(cx) else {
388 return;
389 };
390 let Some(abs_path) = project.read(cx).absolute_path(&project_path, cx) else {
391 return;
392 };
393 let abs_path: Arc<Path> = abs_path.into();
394
395 let Some(serialized_marks) = self.serialized_marks.get(&abs_path) else {
396 return;
397 };
398
399 let mut loaded_marks = HashMap::default();
400 let buffer = buffer_handle.read(cx);
401 for (name, points) in serialized_marks.iter() {
402 loaded_marks.insert(
403 name.clone(),
404 points
405 .iter()
406 .map(|point| buffer.anchor_before(buffer.clip_point(*point, Bias::Left)))
407 .collect(),
408 );
409 }
410 self.buffer_marks.insert(buffer.remote_id(), loaded_marks);
411 self.watch_buffer(MarkLocation::Path(abs_path), buffer_handle, cx)
412 }
413
414 fn serialize_buffer_marks(
415 &mut self,
416 path: Arc<Path>,
417 buffer: &Entity<Buffer>,
418 cx: &mut Context<Self>,
419 ) {
420 let new_points: HashMap<String, Vec<Point>> =
421 if let Some(anchors) = self.buffer_marks.get(&buffer.read(cx).remote_id()) {
422 anchors
423 .iter()
424 .map(|(name, anchors)| {
425 (
426 name.clone(),
427 buffer
428 .read(cx)
429 .summaries_for_anchors::<Point, _>(anchors)
430 .collect(),
431 )
432 })
433 .collect()
434 } else {
435 HashMap::default()
436 };
437 let old_points = self.serialized_marks.get(&path);
438 if old_points == Some(&new_points) {
439 return;
440 }
441 let mut to_write = HashMap::default();
442
443 for (key, value) in &new_points {
444 if self.is_global_mark(key)
445 && self.global_marks.get(key) != Some(&MarkLocation::Path(path.clone()))
446 {
447 if let Some(workspace_id) = self.workspace_id(cx) {
448 let path = path.clone();
449 let key = key.clone();
450 let db = VimDb::global(cx);
451 cx.background_spawn(async move {
452 db.set_global_mark_path(workspace_id, key, path).await
453 })
454 .detach_and_log_err(cx);
455 }
456
457 self.global_marks
458 .insert(key.clone(), MarkLocation::Path(path.clone()));
459 }
460 if old_points.and_then(|o| o.get(key)) != Some(value) {
461 to_write.insert(key.clone(), value.clone());
462 }
463 }
464
465 self.serialized_marks.insert(path.clone(), new_points);
466
467 if let Some(workspace_id) = self.workspace_id(cx) {
468 let db = VimDb::global(cx);
469 cx.background_spawn(async move {
470 db.set_marks(workspace_id, path.clone(), to_write).await?;
471 anyhow::Ok(())
472 })
473 .detach_and_log_err(cx);
474 }
475 }
476
477 fn is_global_mark(&self, key: &str) -> bool {
478 key.chars()
479 .next()
480 .is_some_and(|c| c.is_uppercase() || c.is_digit(10))
481 }
482
483 fn rename_buffer(
484 &mut self,
485 old_path: MarkLocation,
486 new_path: Arc<Path>,
487 buffer: &Entity<Buffer>,
488 cx: &mut Context<Self>,
489 ) {
490 if let MarkLocation::Buffer(entity_id) = old_path
491 && let Some(old_marks) = self.multibuffer_marks.remove(&entity_id)
492 {
493 let buffer_marks = old_marks
494 .into_iter()
495 .map(|(k, v)| (k, v.into_iter().map(|anchor| anchor.text_anchor).collect()))
496 .collect();
497 self.buffer_marks
498 .insert(buffer.read(cx).remote_id(), buffer_marks);
499 }
500 self.watch_buffer(MarkLocation::Path(new_path.clone()), buffer, cx);
501 self.serialize_buffer_marks(new_path, buffer, cx);
502 }
503
504 fn path_for_buffer(&self, buffer: &Entity<Buffer>, cx: &App) -> Option<Arc<Path>> {
505 let project_path = buffer.read(cx).project_path(cx)?;
506 let project = self.project(cx)?;
507 let abs_path = project.read(cx).absolute_path(&project_path, cx)?;
508 Some(abs_path.into())
509 }
510
511 fn points_at(
512 &self,
513 location: &MarkLocation,
514 multi_buffer: &Entity<MultiBuffer>,
515 cx: &App,
516 ) -> bool {
517 match location {
518 MarkLocation::Buffer(entity_id) => entity_id == &multi_buffer.entity_id(),
519 MarkLocation::Path(path) => {
520 let Some(singleton) = multi_buffer.read(cx).as_singleton() else {
521 return false;
522 };
523 self.path_for_buffer(&singleton, cx).as_ref() == Some(path)
524 }
525 }
526 }
527
528 pub fn watch_buffer(
529 &mut self,
530 mark_location: MarkLocation,
531 buffer_handle: &Entity<Buffer>,
532 cx: &mut Context<Self>,
533 ) {
534 let on_change = cx.subscribe(buffer_handle, move |this, buffer, event, cx| match event {
535 BufferEvent::Edited { .. } => {
536 if let Some(path) = this.path_for_buffer(&buffer, cx) {
537 this.serialize_buffer_marks(path, &buffer, cx);
538 }
539 }
540 BufferEvent::FileHandleChanged => {
541 let buffer_id = buffer.read(cx).remote_id();
542 if let Some(old_path) = this
543 .watched_buffers
544 .get(&buffer_id.clone())
545 .map(|(path, _, _)| path.clone())
546 && let Some(new_path) = this.path_for_buffer(&buffer, cx)
547 {
548 this.rename_buffer(old_path, new_path, &buffer, cx)
549 }
550 }
551 _ => {}
552 });
553
554 let on_release = cx.observe_release(buffer_handle, |this, buffer, _| {
555 this.watched_buffers.remove(&buffer.remote_id());
556 this.buffer_marks.remove(&buffer.remote_id());
557 });
558
559 self.watched_buffers.insert(
560 buffer_handle.read(cx).remote_id(),
561 (mark_location, on_change, on_release),
562 );
563 }
564
565 pub fn set_mark(
566 &mut self,
567 name: String,
568 multibuffer: &Entity<MultiBuffer>,
569 anchors: Vec<Anchor>,
570 cx: &mut Context<Self>,
571 ) {
572 let buffer = multibuffer.read(cx).as_singleton();
573 let abs_path = buffer.as_ref().and_then(|b| self.path_for_buffer(b, cx));
574
575 if self.is_global_mark(&name) && self.global_marks.contains_key(&name) {
576 self.delete_mark(name.clone(), multibuffer, cx);
577 }
578
579 let Some(abs_path) = abs_path else {
580 self.multibuffer_marks
581 .entry(multibuffer.entity_id())
582 .or_default()
583 .insert(name.clone(), anchors);
584 if self.is_global_mark(&name) {
585 self.global_marks
586 .insert(name, MarkLocation::Buffer(multibuffer.entity_id()));
587 }
588 if let Some(buffer) = buffer {
589 let buffer_id = buffer.read(cx).remote_id();
590 if !self.watched_buffers.contains_key(&buffer_id) {
591 self.watch_buffer(MarkLocation::Buffer(multibuffer.entity_id()), &buffer, cx)
592 }
593 }
594 return;
595 };
596 let Some(buffer) = buffer else {
597 return;
598 };
599
600 let buffer_id = buffer.read(cx).remote_id();
601 self.buffer_marks.entry(buffer_id).or_default().insert(
602 name.clone(),
603 anchors
604 .into_iter()
605 .map(|anchor| anchor.text_anchor)
606 .collect(),
607 );
608 if !self.watched_buffers.contains_key(&buffer_id) {
609 self.watch_buffer(MarkLocation::Path(abs_path.clone()), &buffer, cx)
610 }
611 if self.is_global_mark(&name) {
612 self.global_marks
613 .insert(name, MarkLocation::Path(abs_path.clone()));
614 }
615 self.serialize_buffer_marks(abs_path, &buffer, cx)
616 }
617
618 pub fn get_mark(
619 &self,
620 name: &str,
621 multi_buffer: &Entity<MultiBuffer>,
622 cx: &App,
623 ) -> Option<Mark> {
624 let target = self.global_marks.get(name);
625
626 if !self.is_global_mark(name) || target.is_some_and(|t| self.points_at(t, multi_buffer, cx))
627 {
628 if let Some(anchors) = self.multibuffer_marks.get(&multi_buffer.entity_id()) {
629 return Some(Mark::Local(anchors.get(name)?.clone()));
630 }
631
632 let (excerpt_id, buffer_id, _) = multi_buffer.read(cx).read(cx).as_singleton()?;
633 if let Some(anchors) = self.buffer_marks.get(&buffer_id) {
634 let text_anchors = anchors.get(name)?;
635 let anchors = text_anchors
636 .iter()
637 .map(|anchor| Anchor::in_buffer(excerpt_id, *anchor))
638 .collect();
639 return Some(Mark::Local(anchors));
640 }
641 }
642
643 match target? {
644 MarkLocation::Buffer(entity_id) => {
645 let anchors = self.multibuffer_marks.get(entity_id)?;
646 Some(Mark::Buffer(*entity_id, anchors.get(name)?.clone()))
647 }
648 MarkLocation::Path(path) => {
649 let points = self.serialized_marks.get(path)?;
650 Some(Mark::Path(path.clone(), points.get(name)?.clone()))
651 }
652 }
653 }
654 pub fn delete_mark(
655 &mut self,
656 mark_name: String,
657 multi_buffer: &Entity<MultiBuffer>,
658 cx: &mut Context<Self>,
659 ) {
660 let path = if let Some(target) = self.global_marks.get(&mark_name.clone()) {
661 let name = mark_name.clone();
662 if let Some(workspace_id) = self.workspace_id(cx) {
663 let db = VimDb::global(cx);
664 cx.background_spawn(async move {
665 db.delete_global_marks_path(workspace_id, name).await
666 })
667 .detach_and_log_err(cx);
668 }
669 self.buffer_marks.iter_mut().for_each(|(_, m)| {
670 m.remove(&mark_name.clone());
671 });
672
673 match target {
674 MarkLocation::Buffer(entity_id) => {
675 self.multibuffer_marks
676 .get_mut(entity_id)
677 .map(|m| m.remove(&mark_name.clone()));
678 return;
679 }
680 MarkLocation::Path(path) => path.clone(),
681 }
682 } else {
683 self.multibuffer_marks
684 .get_mut(&multi_buffer.entity_id())
685 .map(|m| m.remove(&mark_name.clone()));
686
687 if let Some(singleton) = multi_buffer.read(cx).as_singleton() {
688 let buffer_id = singleton.read(cx).remote_id();
689 self.buffer_marks
690 .get_mut(&buffer_id)
691 .map(|m| m.remove(&mark_name.clone()));
692 let Some(path) = self.path_for_buffer(&singleton, cx) else {
693 return;
694 };
695 path
696 } else {
697 return;
698 }
699 };
700 self.global_marks.remove(&mark_name);
701 self.serialized_marks
702 .get_mut(&path)
703 .map(|m| m.remove(&mark_name.clone()));
704 if let Some(workspace_id) = self.workspace_id(cx) {
705 let db = VimDb::global(cx);
706 cx.background_spawn(async move { db.delete_mark(workspace_id, path, mark_name).await })
707 .detach_and_log_err(cx);
708 }
709 }
710}
711
712impl Global for VimGlobals {}
713
714impl VimGlobals {
715 pub(crate) fn register(cx: &mut App) {
716 cx.set_global(VimGlobals::default());
717
718 cx.observe_keystrokes(|event, _, cx| {
719 let Some(action) = event.action.as_ref().map(|action| action.boxed_clone()) else {
720 return;
721 };
722 Vim::globals(cx).observe_action(action.boxed_clone())
723 })
724 .detach();
725
726 cx.observe_new(|workspace: &mut Workspace, window, _| {
727 RegistersView::register(workspace, window);
728 })
729 .detach();
730
731 cx.observe_new(move |workspace: &mut Workspace, window, _| {
732 MarksView::register(workspace, window);
733 })
734 .detach();
735
736 let mut was_enabled = None;
737
738 cx.observe_global::<SettingsStore>(move |cx| {
739 let is_enabled = Vim::enabled(cx);
740 if was_enabled == Some(is_enabled) {
741 return;
742 }
743 was_enabled = Some(is_enabled);
744 if is_enabled {
745 KeyBinding::set_vim_mode(cx, true);
746 CommandPaletteFilter::update_global(cx, |filter, _| {
747 filter.show_namespace(Vim::NAMESPACE);
748 });
749 GlobalCommandPaletteInterceptor::set(cx, command_interceptor);
750 for window in cx.windows() {
751 if let Some(multi_workspace) = window.downcast::<MultiWorkspace>() {
752 multi_workspace
753 .update(cx, |multi_workspace, _, cx| {
754 for workspace in multi_workspace.workspaces() {
755 workspace.update(cx, |workspace, cx| {
756 Vim::update_globals(cx, |globals, cx| {
757 globals.register_workspace(workspace, cx)
758 });
759 });
760 }
761 })
762 .ok();
763 }
764 }
765 } else {
766 KeyBinding::set_vim_mode(cx, false);
767 *Vim::globals(cx) = VimGlobals::default();
768 GlobalCommandPaletteInterceptor::clear(cx);
769 CommandPaletteFilter::update_global(cx, |filter, _| {
770 filter.hide_namespace(Vim::NAMESPACE);
771 });
772 }
773 })
774 .detach();
775 cx.observe_new(|workspace: &mut Workspace, _, cx| {
776 Vim::update_globals(cx, |globals, cx| globals.register_workspace(workspace, cx));
777 })
778 .detach()
779 }
780
781 fn register_workspace(&mut self, workspace: &Workspace, cx: &mut Context<Workspace>) {
782 let entity_id = cx.entity_id();
783 self.marks.insert(entity_id, MarksState::new(workspace, cx));
784 cx.observe_release(&cx.entity(), move |_, _, cx| {
785 Vim::update_globals(cx, |globals, _| {
786 globals.marks.remove(&entity_id);
787 })
788 })
789 .detach();
790 }
791
792 pub(crate) fn write_registers(
793 &mut self,
794 content: Register,
795 register: Option<char>,
796 is_yank: bool,
797 kind: MotionKind,
798 cx: &mut Context<Editor>,
799 ) {
800 if let Some(register) = register {
801 let lower = register.to_lowercase().next().unwrap_or(register);
802 if lower != register {
803 let current = self.registers.entry(lower).or_default();
804 current.text = (current.text.to_string() + &content.text).into();
805 // not clear how to support appending to registers with multiple cursors
806 current.clipboard_selections.take();
807 let yanked = current.clone();
808 self.registers.insert('"', yanked);
809 } else {
810 match lower {
811 '_' | ':' | '.' | '%' | '#' | '=' | '/' => {}
812 '+' => {
813 self.registers.insert('"', content.clone());
814 cx.write_to_clipboard(content.into());
815 }
816 '*' => {
817 self.registers.insert('"', content.clone());
818 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
819 cx.write_to_primary(content.into());
820 #[cfg(not(any(target_os = "linux", target_os = "freebsd")))]
821 cx.write_to_clipboard(content.into());
822 }
823 '"' => {
824 self.registers.insert('"', content.clone());
825 self.registers.insert('0', content);
826 }
827 _ => {
828 self.registers.insert('"', content.clone());
829 self.registers.insert(lower, content);
830 }
831 }
832 }
833 } else {
834 let setting = VimSettings::get_global(cx).use_system_clipboard;
835 if setting == UseSystemClipboard::Always
836 || setting == UseSystemClipboard::OnYank && is_yank
837 {
838 self.last_yank.replace(content.text.clone());
839 cx.write_to_clipboard(content.clone().into());
840 } else {
841 if let Some(text) = cx.read_from_clipboard().and_then(|i| i.text()) {
842 self.last_yank.replace(text.into());
843 }
844 }
845 self.registers.insert('"', content.clone());
846 if is_yank {
847 self.registers.insert('0', content);
848 } else {
849 let contains_newline = content.text.contains('\n');
850 if !contains_newline {
851 self.registers.insert('-', content.clone());
852 }
853 if kind.linewise() || contains_newline {
854 let mut content = content;
855 for i in '1'..='9' {
856 if let Some(moved) = self.registers.insert(i, content) {
857 content = moved;
858 } else {
859 break;
860 }
861 }
862 }
863 }
864 }
865 }
866
867 pub(crate) fn read_register(
868 &self,
869 register: Option<char>,
870 editor: Option<&mut Editor>,
871 cx: &mut App,
872 ) -> Option<Register> {
873 let Some(register) = register.filter(|reg| *reg != '"') else {
874 let setting = VimSettings::get_global(cx).use_system_clipboard;
875 return match setting {
876 UseSystemClipboard::Always => cx.read_from_clipboard().map(|item| item.into()),
877 UseSystemClipboard::OnYank if self.system_clipboard_is_newer(cx) => {
878 cx.read_from_clipboard().map(|item| item.into())
879 }
880 _ => self.registers.get(&'"').cloned(),
881 };
882 };
883 let lower = register.to_lowercase().next().unwrap_or(register);
884 match lower {
885 '_' | ':' | '.' | '#' | '=' => None,
886 '+' => cx.read_from_clipboard().map(|item| item.into()),
887 '*' => {
888 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
889 {
890 cx.read_from_primary().map(|item| item.into())
891 }
892 #[cfg(not(any(target_os = "linux", target_os = "freebsd")))]
893 {
894 cx.read_from_clipboard().map(|item| item.into())
895 }
896 }
897 '%' => editor.and_then(|editor| {
898 let selection = editor
899 .selections
900 .newest::<Point>(&editor.display_snapshot(cx));
901 if let Some((_, buffer, _)) = editor
902 .buffer()
903 .read(cx)
904 .excerpt_containing(selection.head(), cx)
905 {
906 buffer
907 .read(cx)
908 .file()
909 .map(|file| file.path().display(file.path_style(cx)).into_owned().into())
910 } else {
911 None
912 }
913 }),
914 _ => self.registers.get(&lower).cloned(),
915 }
916 }
917
918 fn system_clipboard_is_newer(&self, cx: &App) -> bool {
919 cx.read_from_clipboard().is_some_and(|item| {
920 match (item.text().as_deref(), &self.last_yank) {
921 (Some(new), Some(last)) => last.as_ref() != new,
922 (Some(_), None) => true,
923 (None, _) => false,
924 }
925 })
926 }
927
928 pub fn observe_action(&mut self, action: Box<dyn Action>) {
929 if self.dot_recording {
930 self.recording_actions
931 .push(ReplayableAction::Action(action.boxed_clone()));
932
933 if self.stop_recording_after_next_action {
934 self.dot_recording = false;
935 self.recorded_actions = std::mem::take(&mut self.recording_actions);
936 self.recorded_count = self.recording_count.take();
937 self.recorded_register_for_dot = self.recording_register_for_dot.take();
938 self.stop_recording_after_next_action = false;
939 }
940 }
941 if self.replayer.is_none()
942 && let Some(recording_register) = self.recording_register
943 {
944 self.recordings
945 .entry(recording_register)
946 .or_default()
947 .push(ReplayableAction::Action(action));
948 }
949 }
950
951 pub fn observe_insertion(&mut self, text: &Arc<str>, range_to_replace: Option<Range<isize>>) {
952 if self.ignore_current_insertion {
953 self.ignore_current_insertion = false;
954 return;
955 }
956 if self.dot_recording {
957 self.recording_actions.push(ReplayableAction::Insertion {
958 text: text.clone(),
959 utf16_range_to_replace: range_to_replace.clone(),
960 });
961 if self.stop_recording_after_next_action {
962 self.dot_recording = false;
963 self.recorded_actions = std::mem::take(&mut self.recording_actions);
964 self.recorded_count = self.recording_count.take();
965 self.recorded_register_for_dot = self.recording_register_for_dot.take();
966 self.stop_recording_after_next_action = false;
967 }
968 }
969 if let Some(recording_register) = self.recording_register {
970 self.recordings.entry(recording_register).or_default().push(
971 ReplayableAction::Insertion {
972 text: text.clone(),
973 utf16_range_to_replace: range_to_replace,
974 },
975 );
976 }
977 }
978
979 pub fn focused_vim(&self) -> Option<Entity<Vim>> {
980 self.focused_vim.as_ref().and_then(|vim| vim.upgrade())
981 }
982}
983
984impl Vim {
985 pub fn globals(cx: &mut App) -> &mut VimGlobals {
986 cx.global_mut::<VimGlobals>()
987 }
988
989 pub fn update_globals<C, R>(cx: &mut C, f: impl FnOnce(&mut VimGlobals, &mut C) -> R) -> R
990 where
991 C: BorrowMut<App>,
992 {
993 cx.update_global(f)
994 }
995}
996
997#[derive(Debug)]
998pub enum ReplayableAction {
999 Action(Box<dyn Action>),
1000 Insertion {
1001 text: Arc<str>,
1002 utf16_range_to_replace: Option<Range<isize>>,
1003 },
1004}
1005
1006impl Clone for ReplayableAction {
1007 fn clone(&self) -> Self {
1008 match self {
1009 Self::Action(action) => Self::Action(action.boxed_clone()),
1010 Self::Insertion {
1011 text,
1012 utf16_range_to_replace,
1013 } => Self::Insertion {
1014 text: text.clone(),
1015 utf16_range_to_replace: utf16_range_to_replace.clone(),
1016 },
1017 }
1018 }
1019}
1020
1021#[derive(Default, Debug)]
1022pub struct SearchState {
1023 pub direction: Direction,
1024 pub count: usize,
1025 pub cmd_f_search: bool,
1026
1027 pub prior_selections: Vec<Range<Anchor>>,
1028 pub prior_operator: Option<Operator>,
1029 pub prior_mode: Mode,
1030 pub helix_select: bool,
1031 pub _dismiss_subscription: Option<gpui::Subscription>,
1032}
1033
1034impl Operator {
1035 pub fn id(&self) -> &'static str {
1036 match self {
1037 Operator::Object { around: false } => "i",
1038 Operator::Object { around: true } => "a",
1039 Operator::Change => "c",
1040 Operator::Delete => "d",
1041 Operator::Yank => "y",
1042 Operator::Replace => "r",
1043 Operator::Digraph { .. } => "^K",
1044 Operator::Literal { .. } => "^V",
1045 Operator::FindForward { before: false, .. } => "f",
1046 Operator::FindForward { before: true, .. } => "t",
1047 Operator::Sneak { .. } => "s",
1048 Operator::SneakBackward { .. } => "S",
1049 Operator::FindBackward { after: false, .. } => "F",
1050 Operator::FindBackward { after: true, .. } => "T",
1051 Operator::AddSurrounds { .. } => "ys",
1052 Operator::ChangeSurrounds { .. } => "cs",
1053 Operator::DeleteSurrounds => "ds",
1054 Operator::Mark => "m",
1055 Operator::Jump { line: true } => "'",
1056 Operator::Jump { line: false } => "`",
1057 Operator::Indent => ">",
1058 Operator::AutoIndent => "eq",
1059 Operator::ShellCommand => "sh",
1060 Operator::Rewrap => "gq",
1061 Operator::ReplaceWithRegister => "gR",
1062 Operator::Exchange => "cx",
1063 Operator::Outdent => "<",
1064 Operator::Uppercase => "gU",
1065 Operator::Lowercase => "gu",
1066 Operator::OppositeCase => "g~",
1067 Operator::Rot13 => "g?",
1068 Operator::Rot47 => "g?",
1069 Operator::Register => "\"",
1070 Operator::RecordRegister => "q",
1071 Operator::ReplayRegister => "@",
1072 Operator::ToggleComments => "gc",
1073 Operator::HelixMatch => "helix_m",
1074 Operator::HelixNext { .. } => "helix_next",
1075 Operator::HelixPrevious { .. } => "helix_previous",
1076 Operator::HelixSurroundAdd => "helix_ms",
1077 Operator::HelixSurroundReplace { .. } => "helix_mr",
1078 Operator::HelixSurroundDelete => "helix_md",
1079 }
1080 }
1081
1082 pub fn status(&self) -> String {
1083 fn make_visible(c: &str) -> &str {
1084 match c {
1085 "\n" => "enter",
1086 "\t" => "tab",
1087 " " => "space",
1088 c => c,
1089 }
1090 }
1091 match self {
1092 Operator::Digraph {
1093 first_char: Some(first_char),
1094 } => format!("^K{}", make_visible(&first_char.to_string())),
1095 Operator::Literal {
1096 prefix: Some(prefix),
1097 } => format!("^V{}", make_visible(prefix)),
1098 Operator::AutoIndent => "=".to_string(),
1099 Operator::ShellCommand => "=".to_string(),
1100 Operator::HelixMatch => "m".to_string(),
1101 Operator::HelixNext { .. } => "]".to_string(),
1102 Operator::HelixPrevious { .. } => "[".to_string(),
1103 Operator::HelixSurroundAdd => "ms".to_string(),
1104 Operator::HelixSurroundReplace {
1105 replaced_char: None,
1106 } => "mr".to_string(),
1107 Operator::HelixSurroundReplace {
1108 replaced_char: Some(c),
1109 } => format!("mr{}", c),
1110 Operator::HelixSurroundDelete => "md".to_string(),
1111 _ => self.id().to_string(),
1112 }
1113 }
1114
1115 pub fn is_waiting(&self, mode: Mode) -> bool {
1116 match self {
1117 Operator::AddSurrounds { target } => target.is_some() || mode.is_visual(),
1118 Operator::FindForward { .. }
1119 | Operator::Mark
1120 | Operator::Jump { .. }
1121 | Operator::FindBackward { .. }
1122 | Operator::Sneak { .. }
1123 | Operator::SneakBackward { .. }
1124 | Operator::Register
1125 | Operator::RecordRegister
1126 | Operator::ReplayRegister
1127 | Operator::Replace
1128 | Operator::Digraph { .. }
1129 | Operator::Literal { .. }
1130 | Operator::ChangeSurrounds {
1131 target: Some(_), ..
1132 }
1133 | Operator::DeleteSurrounds => true,
1134 Operator::Change
1135 | Operator::Delete
1136 | Operator::Yank
1137 | Operator::Rewrap
1138 | Operator::Indent
1139 | Operator::Outdent
1140 | Operator::AutoIndent
1141 | Operator::ShellCommand
1142 | Operator::Lowercase
1143 | Operator::Uppercase
1144 | Operator::Rot13
1145 | Operator::Rot47
1146 | Operator::ReplaceWithRegister
1147 | Operator::Exchange
1148 | Operator::Object { .. }
1149 | Operator::ChangeSurrounds { target: None, .. }
1150 | Operator::OppositeCase
1151 | Operator::ToggleComments
1152 | Operator::HelixMatch
1153 | Operator::HelixNext { .. }
1154 | Operator::HelixPrevious { .. } => false,
1155 Operator::HelixSurroundAdd
1156 | Operator::HelixSurroundReplace { .. }
1157 | Operator::HelixSurroundDelete => true,
1158 }
1159 }
1160
1161 pub fn starts_dot_recording(&self) -> bool {
1162 match self {
1163 Operator::Change
1164 | Operator::Delete
1165 | Operator::Replace
1166 | Operator::Indent
1167 | Operator::Outdent
1168 | Operator::AutoIndent
1169 | Operator::Lowercase
1170 | Operator::Uppercase
1171 | Operator::OppositeCase
1172 | Operator::Rot13
1173 | Operator::Rot47
1174 | Operator::ToggleComments
1175 | Operator::ReplaceWithRegister
1176 | Operator::Rewrap
1177 | Operator::ShellCommand
1178 | Operator::AddSurrounds { target: None }
1179 | Operator::ChangeSurrounds { target: None, .. }
1180 | Operator::DeleteSurrounds
1181 | Operator::Exchange
1182 | Operator::HelixNext { .. }
1183 | Operator::HelixPrevious { .. }
1184 | Operator::HelixSurroundAdd
1185 | Operator::HelixSurroundReplace { .. }
1186 | Operator::HelixSurroundDelete => true,
1187 Operator::Yank
1188 | Operator::Object { .. }
1189 | Operator::FindForward { .. }
1190 | Operator::FindBackward { .. }
1191 | Operator::Sneak { .. }
1192 | Operator::SneakBackward { .. }
1193 | Operator::Mark
1194 | Operator::Digraph { .. }
1195 | Operator::Literal { .. }
1196 | Operator::AddSurrounds { .. }
1197 | Operator::ChangeSurrounds { .. }
1198 | Operator::Jump { .. }
1199 | Operator::Register
1200 | Operator::RecordRegister
1201 | Operator::ReplayRegister
1202 | Operator::HelixMatch => false,
1203 }
1204 }
1205}
1206
1207struct RegisterMatch {
1208 name: char,
1209 contents: SharedString,
1210}
1211
1212pub struct RegistersViewDelegate {
1213 selected_index: usize,
1214 matches: Vec<RegisterMatch>,
1215}
1216
1217impl PickerDelegate for RegistersViewDelegate {
1218 type ListItem = Div;
1219
1220 fn match_count(&self) -> usize {
1221 self.matches.len()
1222 }
1223
1224 fn selected_index(&self) -> usize {
1225 self.selected_index
1226 }
1227
1228 fn set_selected_index(&mut self, ix: usize, _: &mut Window, cx: &mut Context<Picker<Self>>) {
1229 self.selected_index = ix;
1230 cx.notify();
1231 }
1232
1233 fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str> {
1234 Arc::default()
1235 }
1236
1237 fn update_matches(
1238 &mut self,
1239 _: String,
1240 _: &mut Window,
1241 _: &mut Context<Picker<Self>>,
1242 ) -> gpui::Task<()> {
1243 Task::ready(())
1244 }
1245
1246 fn confirm(&mut self, _: bool, _: &mut Window, _: &mut Context<Picker<Self>>) {}
1247
1248 fn dismissed(&mut self, _: &mut Window, _: &mut Context<Picker<Self>>) {}
1249
1250 fn render_match(
1251 &self,
1252 ix: usize,
1253 selected: bool,
1254 _: &mut Window,
1255 cx: &mut Context<Picker<Self>>,
1256 ) -> Option<Self::ListItem> {
1257 let register_match = self.matches.get(ix)?;
1258
1259 let mut output = String::new();
1260 let mut runs = Vec::new();
1261 output.push('"');
1262 output.push(register_match.name);
1263 runs.push((
1264 0..output.len(),
1265 HighlightStyle::color(cx.theme().colors().text_accent),
1266 ));
1267 output.push(' ');
1268 output.push(' ');
1269 let mut base = output.len();
1270 for (ix, c) in register_match.contents.char_indices() {
1271 if ix > 100 {
1272 break;
1273 }
1274 let replace = match c {
1275 '\t' => Some("\\t".to_string()),
1276 '\n' => Some("\\n".to_string()),
1277 '\r' => Some("\\r".to_string()),
1278 c if is_invisible(c) => {
1279 if c <= '\x1f' {
1280 replacement(c).map(|s| s.to_string())
1281 } else {
1282 Some(format!("\\u{:04X}", c as u32))
1283 }
1284 }
1285 _ => None,
1286 };
1287 let Some(replace) = replace else {
1288 output.push(c);
1289 continue;
1290 };
1291 output.push_str(&replace);
1292 runs.push((
1293 base + ix..base + ix + replace.len(),
1294 HighlightStyle::color(cx.theme().colors().text_muted),
1295 ));
1296 base += replace.len() - c.len_utf8();
1297 }
1298
1299 let theme = ThemeSettings::get_global(cx);
1300 let text_style = TextStyle {
1301 color: cx.theme().colors().editor_foreground,
1302 font_family: theme.buffer_font.family.clone(),
1303 font_features: theme.buffer_font.features.clone(),
1304 font_fallbacks: theme.buffer_font.fallbacks.clone(),
1305 font_size: theme.buffer_font_size(cx).into(),
1306 line_height: (theme.line_height() * theme.buffer_font_size(cx)).into(),
1307 font_weight: theme.buffer_font.weight,
1308 font_style: theme.buffer_font.style,
1309 ..Default::default()
1310 };
1311
1312 Some(
1313 h_flex()
1314 .when(selected, |el| el.bg(cx.theme().colors().element_selected))
1315 .font_buffer(cx)
1316 .text_buffer(cx)
1317 .h(theme.buffer_font_size(cx) * theme.line_height())
1318 .px_2()
1319 .gap_1()
1320 .child(StyledText::new(output).with_default_highlights(&text_style, runs)),
1321 )
1322 }
1323}
1324
1325pub struct RegistersView {}
1326
1327impl RegistersView {
1328 fn register(workspace: &mut Workspace, _window: Option<&mut Window>) {
1329 workspace.register_action(|workspace, _: &ToggleRegistersView, window, cx| {
1330 Self::toggle(workspace, window, cx);
1331 });
1332 }
1333
1334 pub fn toggle(workspace: &mut Workspace, window: &mut Window, cx: &mut Context<Workspace>) {
1335 let editor = workspace
1336 .active_item(cx)
1337 .and_then(|item| item.act_as::<Editor>(cx));
1338 workspace.toggle_modal(window, cx, move |window, cx| {
1339 RegistersView::new(editor, window, cx)
1340 });
1341 }
1342
1343 fn new(
1344 editor: Option<Entity<Editor>>,
1345 window: &mut Window,
1346 cx: &mut Context<Picker<RegistersViewDelegate>>,
1347 ) -> Picker<RegistersViewDelegate> {
1348 let mut matches = Vec::default();
1349 cx.update_global(|globals: &mut VimGlobals, cx| {
1350 for name in ['"', '+', '*'] {
1351 if let Some(register) = globals.read_register(Some(name), None, cx) {
1352 matches.push(RegisterMatch {
1353 name,
1354 contents: register.text.clone(),
1355 })
1356 }
1357 }
1358 if let Some(editor) = editor {
1359 let register = editor.update(cx, |editor, cx| {
1360 globals.read_register(Some('%'), Some(editor), cx)
1361 });
1362 if let Some(register) = register {
1363 matches.push(RegisterMatch {
1364 name: '%',
1365 contents: register.text,
1366 })
1367 }
1368 }
1369 for (name, register) in globals.registers.iter() {
1370 if ['"', '+', '*', '%'].contains(name) {
1371 continue;
1372 };
1373 matches.push(RegisterMatch {
1374 name: *name,
1375 contents: register.text.clone(),
1376 })
1377 }
1378 });
1379 matches.sort_by(|a, b| a.name.cmp(&b.name));
1380 let delegate = RegistersViewDelegate {
1381 selected_index: 0,
1382 matches,
1383 };
1384
1385 Picker::nonsearchable_uniform_list(delegate, window, cx)
1386 .width(rems(36.))
1387 .modal(true)
1388 }
1389}
1390
1391enum MarksMatchInfo {
1392 Path(Arc<Path>),
1393 Title(String),
1394 Content {
1395 line: String,
1396 highlights: Vec<(Range<usize>, HighlightStyle)>,
1397 },
1398}
1399
1400impl MarksMatchInfo {
1401 fn from_chunks<'a>(chunks: impl Iterator<Item = Chunk<'a>>, cx: &App) -> Self {
1402 let mut line = String::new();
1403 let mut highlights = Vec::new();
1404 let mut offset = 0;
1405 for chunk in chunks {
1406 line.push_str(chunk.text);
1407 if let Some(highlight_id) = chunk.syntax_highlight_id
1408 && let Some(highlight) = cx.theme().syntax().get(highlight_id).cloned()
1409 {
1410 highlights.push((offset..offset + chunk.text.len(), highlight))
1411 }
1412 offset += chunk.text.len();
1413 }
1414 MarksMatchInfo::Content { line, highlights }
1415 }
1416}
1417
1418struct MarksMatch {
1419 name: String,
1420 position: Point,
1421 info: MarksMatchInfo,
1422}
1423
1424pub struct MarksViewDelegate {
1425 selected_index: usize,
1426 matches: Vec<MarksMatch>,
1427 point_column_width: usize,
1428 workspace: WeakEntity<Workspace>,
1429}
1430
1431impl PickerDelegate for MarksViewDelegate {
1432 type ListItem = Div;
1433
1434 fn match_count(&self) -> usize {
1435 self.matches.len()
1436 }
1437
1438 fn selected_index(&self) -> usize {
1439 self.selected_index
1440 }
1441
1442 fn set_selected_index(&mut self, ix: usize, _: &mut Window, cx: &mut Context<Picker<Self>>) {
1443 self.selected_index = ix;
1444 cx.notify();
1445 }
1446
1447 fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str> {
1448 Arc::default()
1449 }
1450
1451 fn update_matches(
1452 &mut self,
1453 _: String,
1454 _: &mut Window,
1455 cx: &mut Context<Picker<Self>>,
1456 ) -> gpui::Task<()> {
1457 let Some(workspace) = self.workspace.upgrade() else {
1458 return Task::ready(());
1459 };
1460 cx.spawn(async move |picker, cx| {
1461 let mut matches = Vec::new();
1462 let _ = workspace.update(cx, |workspace, cx| {
1463 let entity_id = cx.entity_id();
1464 let Some(editor) = workspace
1465 .active_item(cx)
1466 .and_then(|item| item.act_as::<Editor>(cx))
1467 else {
1468 return;
1469 };
1470 let editor = editor.read(cx);
1471 let mut has_seen = HashSet::new();
1472 let Some(marks_state) = cx.global::<VimGlobals>().marks.get(&entity_id) else {
1473 return;
1474 };
1475 let marks_state = marks_state.read(cx);
1476
1477 if let Some(map) = marks_state
1478 .multibuffer_marks
1479 .get(&editor.buffer().entity_id())
1480 {
1481 for (name, anchors) in map {
1482 if has_seen.contains(name) {
1483 continue;
1484 }
1485 has_seen.insert(name.clone());
1486 let Some(anchor) = anchors.first() else {
1487 continue;
1488 };
1489
1490 let snapshot = editor.buffer().read(cx).snapshot(cx);
1491 let position = anchor.to_point(&snapshot);
1492
1493 let chunks = snapshot.chunks(
1494 Point::new(position.row, 0)
1495 ..Point::new(
1496 position.row,
1497 snapshot.line_len(MultiBufferRow(position.row)),
1498 ),
1499 true,
1500 );
1501 matches.push(MarksMatch {
1502 name: name.clone(),
1503 position,
1504 info: MarksMatchInfo::from_chunks(chunks, cx),
1505 })
1506 }
1507 }
1508
1509 if let Some(buffer) = editor.buffer().read(cx).as_singleton() {
1510 let buffer = buffer.read(cx);
1511 if let Some(map) = marks_state.buffer_marks.get(&buffer.remote_id()) {
1512 for (name, anchors) in map {
1513 if has_seen.contains(name) {
1514 continue;
1515 }
1516 has_seen.insert(name.clone());
1517 let Some(anchor) = anchors.first() else {
1518 continue;
1519 };
1520 let snapshot = buffer.snapshot();
1521 let position = anchor.to_point(&snapshot);
1522 let chunks = snapshot.chunks(
1523 Point::new(position.row, 0)
1524 ..Point::new(position.row, snapshot.line_len(position.row)),
1525 true,
1526 );
1527
1528 matches.push(MarksMatch {
1529 name: name.clone(),
1530 position,
1531 info: MarksMatchInfo::from_chunks(chunks, cx),
1532 })
1533 }
1534 }
1535 }
1536
1537 for (name, mark_location) in marks_state.global_marks.iter() {
1538 if has_seen.contains(name) {
1539 continue;
1540 }
1541 has_seen.insert(name.clone());
1542
1543 match mark_location {
1544 MarkLocation::Buffer(entity_id) => {
1545 if let Some(&anchor) = marks_state
1546 .multibuffer_marks
1547 .get(entity_id)
1548 .and_then(|map| map.get(name))
1549 .and_then(|anchors| anchors.first())
1550 {
1551 let Some((info, snapshot)) = workspace
1552 .items(cx)
1553 .filter_map(|item| item.act_as::<Editor>(cx))
1554 .map(|entity| entity.read(cx).buffer())
1555 .find(|buffer| buffer.entity_id().eq(entity_id))
1556 .map(|buffer| {
1557 (
1558 MarksMatchInfo::Title(
1559 buffer.read(cx).title(cx).to_string(),
1560 ),
1561 buffer.read(cx).snapshot(cx),
1562 )
1563 })
1564 else {
1565 continue;
1566 };
1567 matches.push(MarksMatch {
1568 name: name.clone(),
1569 position: anchor.to_point(&snapshot),
1570 info,
1571 });
1572 }
1573 }
1574 MarkLocation::Path(path) => {
1575 if let Some(&position) = marks_state
1576 .serialized_marks
1577 .get(path.as_ref())
1578 .and_then(|map| map.get(name))
1579 .and_then(|points| points.first())
1580 {
1581 let info = MarksMatchInfo::Path(path.clone());
1582 matches.push(MarksMatch {
1583 name: name.clone(),
1584 position,
1585 info,
1586 });
1587 }
1588 }
1589 }
1590 }
1591 });
1592 let _ = picker.update(cx, |picker, cx| {
1593 matches.sort_by_key(|a| {
1594 (
1595 a.name.chars().next().map(|c| c.is_ascii_uppercase()),
1596 a.name.clone(),
1597 )
1598 });
1599 let digits = matches
1600 .iter()
1601 .map(|m| (m.position.row + 1).ilog10() + (m.position.column + 1).ilog10())
1602 .max()
1603 .unwrap_or_default();
1604 picker.delegate.matches = matches;
1605 picker.delegate.point_column_width = (digits + 4) as usize;
1606 cx.notify();
1607 });
1608 })
1609 }
1610
1611 fn confirm(&mut self, _: bool, window: &mut Window, cx: &mut Context<Picker<Self>>) {
1612 let Some(vim) = self
1613 .workspace
1614 .upgrade()
1615 .map(|w| w.read(cx))
1616 .and_then(|w| w.focused_pane(window, cx).read(cx).active_item())
1617 .and_then(|item| item.act_as::<Editor>(cx))
1618 .and_then(|editor| editor.read(cx).addon::<VimAddon>().cloned())
1619 .map(|addon| addon.entity)
1620 else {
1621 return;
1622 };
1623 let Some(text): Option<Arc<str>> = self
1624 .matches
1625 .get(self.selected_index)
1626 .map(|m| Arc::from(m.name.to_string().into_boxed_str()))
1627 else {
1628 return;
1629 };
1630 vim.update(cx, |vim, cx| {
1631 vim.jump(text, false, false, window, cx);
1632 });
1633
1634 cx.emit(DismissEvent);
1635 }
1636
1637 fn dismissed(&mut self, _: &mut Window, _: &mut Context<Picker<Self>>) {}
1638
1639 fn render_match(
1640 &self,
1641 ix: usize,
1642 selected: bool,
1643 _: &mut Window,
1644 cx: &mut Context<Picker<Self>>,
1645 ) -> Option<Self::ListItem> {
1646 let mark_match = self.matches.get(ix)?;
1647
1648 let mut left_output = String::new();
1649 let mut left_runs = Vec::new();
1650 left_output.push('`');
1651 left_output.push_str(&mark_match.name);
1652 left_runs.push((
1653 0..left_output.len(),
1654 HighlightStyle::color(cx.theme().colors().text_accent),
1655 ));
1656 left_output.push(' ');
1657 left_output.push(' ');
1658 let point_column = format!(
1659 "{},{}",
1660 mark_match.position.row + 1,
1661 mark_match.position.column + 1
1662 );
1663 left_output.push_str(&point_column);
1664 if let Some(padding) = self.point_column_width.checked_sub(point_column.len()) {
1665 left_output.push_str(&" ".repeat(padding));
1666 }
1667
1668 let (right_output, right_runs): (String, Vec<_>) = match &mark_match.info {
1669 MarksMatchInfo::Path(path) => {
1670 let s = path.to_string_lossy().into_owned();
1671 (
1672 s.clone(),
1673 vec![(0..s.len(), HighlightStyle::color(cx.theme().colors().text))],
1674 )
1675 }
1676 MarksMatchInfo::Title(title) => (
1677 title.clone(),
1678 vec![(
1679 0..title.len(),
1680 HighlightStyle::color(cx.theme().colors().text),
1681 )],
1682 ),
1683 MarksMatchInfo::Content { line, highlights } => (line.clone(), highlights.clone()),
1684 };
1685
1686 let theme = ThemeSettings::get_global(cx);
1687 let text_style = TextStyle {
1688 color: cx.theme().colors().editor_foreground,
1689 font_family: theme.buffer_font.family.clone(),
1690 font_features: theme.buffer_font.features.clone(),
1691 font_fallbacks: theme.buffer_font.fallbacks.clone(),
1692 font_size: theme.buffer_font_size(cx).into(),
1693 line_height: (theme.line_height() * theme.buffer_font_size(cx)).into(),
1694 font_weight: theme.buffer_font.weight,
1695 font_style: theme.buffer_font.style,
1696 ..Default::default()
1697 };
1698
1699 Some(
1700 h_flex()
1701 .when(selected, |el| el.bg(cx.theme().colors().element_selected))
1702 .font_buffer(cx)
1703 .text_buffer(cx)
1704 .h(theme.buffer_font_size(cx) * theme.line_height())
1705 .px_2()
1706 .child(StyledText::new(left_output).with_default_highlights(&text_style, left_runs))
1707 .child(
1708 StyledText::new(right_output).with_default_highlights(&text_style, right_runs),
1709 ),
1710 )
1711 }
1712}
1713
1714pub struct MarksView {}
1715
1716impl MarksView {
1717 fn register(workspace: &mut Workspace, _window: Option<&mut Window>) {
1718 workspace.register_action(|workspace, _: &ToggleMarksView, window, cx| {
1719 Self::toggle(workspace, window, cx);
1720 });
1721 }
1722
1723 pub fn toggle(workspace: &mut Workspace, window: &mut Window, cx: &mut Context<Workspace>) {
1724 let handle = cx.weak_entity();
1725 workspace.toggle_modal(window, cx, move |window, cx| {
1726 MarksView::new(handle, window, cx)
1727 });
1728 }
1729
1730 fn new(
1731 workspace: WeakEntity<Workspace>,
1732 window: &mut Window,
1733 cx: &mut Context<Picker<MarksViewDelegate>>,
1734 ) -> Picker<MarksViewDelegate> {
1735 let matches = Vec::default();
1736 let delegate = MarksViewDelegate {
1737 selected_index: 0,
1738 point_column_width: 0,
1739 matches,
1740 workspace,
1741 };
1742 Picker::nonsearchable_uniform_list(delegate, window, cx)
1743 .width(rems(36.))
1744 .modal(true)
1745 }
1746}
1747
1748pub struct VimDb(ThreadSafeConnection);
1749
1750impl Domain for VimDb {
1751 const NAME: &str = stringify!(VimDb);
1752
1753 const MIGRATIONS: &[&str] = &[
1754 sql! (
1755 CREATE TABLE vim_marks (
1756 workspace_id INTEGER,
1757 mark_name TEXT,
1758 path BLOB,
1759 value TEXT
1760 );
1761 CREATE UNIQUE INDEX idx_vim_marks ON vim_marks (workspace_id, mark_name, path);
1762 ),
1763 sql! (
1764 CREATE TABLE vim_global_marks_paths(
1765 workspace_id INTEGER,
1766 mark_name TEXT,
1767 path BLOB
1768 );
1769 CREATE UNIQUE INDEX idx_vim_global_marks_paths
1770 ON vim_global_marks_paths(workspace_id, mark_name);
1771 ),
1772 ];
1773}
1774
1775db::static_connection!(VimDb, [WorkspaceDb]);
1776
1777struct SerializedMark {
1778 path: Arc<Path>,
1779 name: String,
1780 points: Vec<Point>,
1781}
1782
1783impl VimDb {
1784 pub(crate) async fn set_marks(
1785 &self,
1786 workspace_id: WorkspaceId,
1787 path: Arc<Path>,
1788 marks: HashMap<String, Vec<Point>>,
1789 ) -> Result<()> {
1790 log::debug!("Setting path {path:?} for {} marks", marks.len());
1791
1792 self.write(move |conn| {
1793 let mut query = conn.exec_bound(sql!(
1794 INSERT OR REPLACE INTO vim_marks
1795 (workspace_id, mark_name, path, value)
1796 VALUES
1797 (?, ?, ?, ?)
1798 ))?;
1799 for (mark_name, value) in marks {
1800 let pairs: Vec<(u32, u32)> = value
1801 .into_iter()
1802 .map(|point| (point.row, point.column))
1803 .collect();
1804 let serialized = serde_json::to_string(&pairs)?;
1805 query((workspace_id, mark_name, path.clone(), serialized))?;
1806 }
1807 Ok(())
1808 })
1809 .await
1810 }
1811
1812 fn get_marks(&self, workspace_id: WorkspaceId) -> Result<Vec<SerializedMark>> {
1813 let result: Vec<(Arc<Path>, String, String)> = self.select_bound(sql!(
1814 SELECT path, mark_name, value FROM vim_marks
1815 WHERE workspace_id = ?
1816 ))?(workspace_id)?;
1817
1818 Ok(result
1819 .into_iter()
1820 .filter_map(|(path, name, value)| {
1821 let pairs: Vec<(u32, u32)> = serde_json::from_str(&value).log_err()?;
1822 Some(SerializedMark {
1823 path,
1824 name,
1825 points: pairs
1826 .into_iter()
1827 .map(|(row, column)| Point { row, column })
1828 .collect(),
1829 })
1830 })
1831 .collect())
1832 }
1833
1834 pub(crate) async fn delete_mark(
1835 &self,
1836 workspace_id: WorkspaceId,
1837 path: Arc<Path>,
1838 mark_name: String,
1839 ) -> Result<()> {
1840 self.write(move |conn| {
1841 conn.exec_bound(sql!(
1842 DELETE FROM vim_marks
1843 WHERE workspace_id = ? AND mark_name = ? AND path = ?
1844 ))?((workspace_id, mark_name, path))
1845 })
1846 .await
1847 }
1848
1849 pub(crate) async fn set_global_mark_path(
1850 &self,
1851 workspace_id: WorkspaceId,
1852 mark_name: String,
1853 path: Arc<Path>,
1854 ) -> Result<()> {
1855 log::debug!("Setting global mark path {path:?} for {mark_name}");
1856 self.write(move |conn| {
1857 conn.exec_bound(sql!(
1858 INSERT OR REPLACE INTO vim_global_marks_paths
1859 (workspace_id, mark_name, path)
1860 VALUES
1861 (?, ?, ?)
1862 ))?((workspace_id, mark_name, path))
1863 })
1864 .await
1865 }
1866
1867 pub fn get_global_marks_paths(
1868 &self,
1869 workspace_id: WorkspaceId,
1870 ) -> Result<Vec<(String, Arc<Path>)>> {
1871 self.select_bound(sql!(
1872 SELECT mark_name, path FROM vim_global_marks_paths
1873 WHERE workspace_id = ?
1874 ))?(workspace_id)
1875 }
1876
1877 pub(crate) async fn delete_global_marks_path(
1878 &self,
1879 workspace_id: WorkspaceId,
1880 mark_name: String,
1881 ) -> Result<()> {
1882 self.write(move |conn| {
1883 conn.exec_bound(sql!(
1884 DELETE FROM vim_global_marks_paths
1885 WHERE workspace_id = ? AND mark_name = ?
1886 ))?((workspace_id, mark_name))
1887 })
1888 .await
1889 }
1890}