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