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