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