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