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