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