1use crate::command::command_interceptor;
2use crate::motion::MotionKind;
3use crate::normal::repeat::Replayer;
4use crate::surrounds::SurroundsType;
5use crate::{ToggleMarksView, ToggleRegistersView, UseSystemClipboard, Vim, VimAddon, VimSettings};
6use crate::{motion::Motion, object::Object};
7use anyhow::Result;
8use collections::HashMap;
9use command_palette_hooks::{CommandPaletteFilter, GlobalCommandPaletteInterceptor};
10use db::{
11 sqlez::{domain::Domain, thread_safe_connection::ThreadSafeConnection},
12 sqlez_macros::sql,
13};
14use editor::display_map::{is_invisible, replacement};
15use editor::{Anchor, ClipboardSelection, Editor, MultiBuffer, ToPoint as EditorToPoint};
16use gpui::{
17 Action, App, AppContext, BorrowAppContext, ClipboardEntry, ClipboardItem, DismissEvent, Entity,
18 EntityId, Global, HighlightStyle, StyledText, Subscription, Task, TextStyle, WeakEntity,
19};
20use language::{Buffer, BufferEvent, BufferId, Chunk, Point};
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 true,
1508 );
1509 matches.push(MarksMatch {
1510 name: name.clone(),
1511 position,
1512 info: MarksMatchInfo::from_chunks(chunks, cx),
1513 })
1514 }
1515 }
1516
1517 if let Some(buffer) = editor.buffer().read(cx).as_singleton() {
1518 let buffer = buffer.read(cx);
1519 if let Some(map) = marks_state.buffer_marks.get(&buffer.remote_id()) {
1520 for (name, anchors) in map {
1521 if has_seen.contains(name) {
1522 continue;
1523 }
1524 has_seen.insert(name.clone());
1525 let Some(anchor) = anchors.first() else {
1526 continue;
1527 };
1528 let snapshot = buffer.snapshot();
1529 let position = anchor.to_point(&snapshot);
1530 let chunks = snapshot.chunks(
1531 Point::new(position.row, 0)
1532 ..Point::new(position.row, snapshot.line_len(position.row)),
1533 true,
1534 );
1535
1536 matches.push(MarksMatch {
1537 name: name.clone(),
1538 position,
1539 info: MarksMatchInfo::from_chunks(chunks, cx),
1540 })
1541 }
1542 }
1543 }
1544
1545 for (name, mark_location) in marks_state.global_marks.iter() {
1546 if has_seen.contains(name) {
1547 continue;
1548 }
1549 has_seen.insert(name.clone());
1550
1551 match mark_location {
1552 MarkLocation::Buffer(entity_id) => {
1553 if let Some(&anchor) = marks_state
1554 .multibuffer_marks
1555 .get(entity_id)
1556 .and_then(|map| map.get(name))
1557 .and_then(|anchors| anchors.first())
1558 {
1559 let Some((info, snapshot)) = workspace
1560 .items(cx)
1561 .filter_map(|item| item.act_as::<Editor>(cx))
1562 .map(|entity| entity.read(cx).buffer())
1563 .find(|buffer| buffer.entity_id().eq(entity_id))
1564 .map(|buffer| {
1565 (
1566 MarksMatchInfo::Title(
1567 buffer.read(cx).title(cx).to_string(),
1568 ),
1569 buffer.read(cx).snapshot(cx),
1570 )
1571 })
1572 else {
1573 continue;
1574 };
1575 matches.push(MarksMatch {
1576 name: name.clone(),
1577 position: anchor.to_point(&snapshot),
1578 info,
1579 });
1580 }
1581 }
1582 MarkLocation::Path(path) => {
1583 if let Some(&position) = marks_state
1584 .serialized_marks
1585 .get(path.as_ref())
1586 .and_then(|map| map.get(name))
1587 .and_then(|points| points.first())
1588 {
1589 let info = MarksMatchInfo::Path(path.clone());
1590 matches.push(MarksMatch {
1591 name: name.clone(),
1592 position,
1593 info,
1594 });
1595 }
1596 }
1597 }
1598 }
1599 });
1600 let _ = picker.update(cx, |picker, cx| {
1601 matches.sort_by_key(|a| {
1602 (
1603 a.name.chars().next().map(|c| c.is_ascii_uppercase()),
1604 a.name.clone(),
1605 )
1606 });
1607 let digits = matches
1608 .iter()
1609 .map(|m| (m.position.row + 1).ilog10() + (m.position.column + 1).ilog10())
1610 .max()
1611 .unwrap_or_default();
1612 picker.delegate.matches = matches;
1613 picker.delegate.point_column_width = (digits + 4) as usize;
1614 cx.notify();
1615 });
1616 })
1617 }
1618
1619 fn confirm(&mut self, _: bool, window: &mut Window, cx: &mut Context<Picker<Self>>) {
1620 let Some(vim) = self
1621 .workspace
1622 .upgrade()
1623 .map(|w| w.read(cx))
1624 .and_then(|w| w.focused_pane(window, cx).read(cx).active_item())
1625 .and_then(|item| item.act_as::<Editor>(cx))
1626 .and_then(|editor| editor.read(cx).addon::<VimAddon>().cloned())
1627 .map(|addon| addon.entity)
1628 else {
1629 return;
1630 };
1631 let Some(text): Option<Arc<str>> = self
1632 .matches
1633 .get(self.selected_index)
1634 .map(|m| Arc::from(m.name.to_string().into_boxed_str()))
1635 else {
1636 return;
1637 };
1638 vim.update(cx, |vim, cx| {
1639 vim.jump(text, false, false, window, cx);
1640 });
1641
1642 cx.emit(DismissEvent);
1643 }
1644
1645 fn dismissed(&mut self, _: &mut Window, _: &mut Context<Picker<Self>>) {}
1646
1647 fn render_match(
1648 &self,
1649 ix: usize,
1650 selected: bool,
1651 _: &mut Window,
1652 cx: &mut Context<Picker<Self>>,
1653 ) -> Option<Self::ListItem> {
1654 let mark_match = self.matches.get(ix)?;
1655
1656 let mut left_output = String::new();
1657 let mut left_runs = Vec::new();
1658 left_output.push('`');
1659 left_output.push_str(&mark_match.name);
1660 left_runs.push((
1661 0..left_output.len(),
1662 HighlightStyle::color(cx.theme().colors().text_accent),
1663 ));
1664 left_output.push(' ');
1665 left_output.push(' ');
1666 let point_column = format!(
1667 "{},{}",
1668 mark_match.position.row + 1,
1669 mark_match.position.column + 1
1670 );
1671 left_output.push_str(&point_column);
1672 if let Some(padding) = self.point_column_width.checked_sub(point_column.len()) {
1673 left_output.push_str(&" ".repeat(padding));
1674 }
1675
1676 let (right_output, right_runs): (String, Vec<_>) = match &mark_match.info {
1677 MarksMatchInfo::Path(path) => {
1678 let s = path.to_string_lossy().into_owned();
1679 (
1680 s.clone(),
1681 vec![(0..s.len(), HighlightStyle::color(cx.theme().colors().text))],
1682 )
1683 }
1684 MarksMatchInfo::Title(title) => (
1685 title.clone(),
1686 vec![(
1687 0..title.len(),
1688 HighlightStyle::color(cx.theme().colors().text),
1689 )],
1690 ),
1691 MarksMatchInfo::Content { line, highlights } => (line.clone(), highlights.clone()),
1692 };
1693
1694 let theme = ThemeSettings::get_global(cx);
1695 let text_style = TextStyle {
1696 color: cx.theme().colors().editor_foreground,
1697 font_family: theme.buffer_font.family.clone(),
1698 font_features: theme.buffer_font.features.clone(),
1699 font_fallbacks: theme.buffer_font.fallbacks.clone(),
1700 font_size: theme.buffer_font_size(cx).into(),
1701 line_height: (theme.line_height() * theme.buffer_font_size(cx)).into(),
1702 font_weight: theme.buffer_font.weight,
1703 font_style: theme.buffer_font.style,
1704 ..Default::default()
1705 };
1706
1707 Some(
1708 h_flex()
1709 .when(selected, |el| el.bg(cx.theme().colors().element_selected))
1710 .font_buffer(cx)
1711 .text_buffer(cx)
1712 .h(theme.buffer_font_size(cx) * theme.line_height())
1713 .px_2()
1714 .child(StyledText::new(left_output).with_default_highlights(&text_style, left_runs))
1715 .child(
1716 StyledText::new(right_output).with_default_highlights(&text_style, right_runs),
1717 ),
1718 )
1719 }
1720}
1721
1722pub struct MarksView {}
1723
1724impl MarksView {
1725 fn register(workspace: &mut Workspace, _window: Option<&mut Window>) {
1726 workspace.register_action(|workspace, _: &ToggleMarksView, window, cx| {
1727 Self::toggle(workspace, window, cx);
1728 });
1729 }
1730
1731 pub fn toggle(workspace: &mut Workspace, window: &mut Window, cx: &mut Context<Workspace>) {
1732 let handle = cx.weak_entity();
1733 workspace.toggle_modal(window, cx, move |window, cx| {
1734 MarksView::new(handle, window, cx)
1735 });
1736 }
1737
1738 fn new(
1739 workspace: WeakEntity<Workspace>,
1740 window: &mut Window,
1741 cx: &mut Context<Picker<MarksViewDelegate>>,
1742 ) -> Picker<MarksViewDelegate> {
1743 let matches = Vec::default();
1744 let delegate = MarksViewDelegate {
1745 selected_index: 0,
1746 point_column_width: 0,
1747 matches,
1748 workspace,
1749 };
1750 Picker::nonsearchable_uniform_list(delegate, window, cx)
1751 .width(rems(36.))
1752 .modal(true)
1753 }
1754}
1755
1756pub struct VimDb(ThreadSafeConnection);
1757
1758impl Domain for VimDb {
1759 const NAME: &str = stringify!(VimDb);
1760
1761 const MIGRATIONS: &[&str] = &[
1762 sql! (
1763 CREATE TABLE vim_marks (
1764 workspace_id INTEGER,
1765 mark_name TEXT,
1766 path BLOB,
1767 value TEXT
1768 );
1769 CREATE UNIQUE INDEX idx_vim_marks ON vim_marks (workspace_id, mark_name, path);
1770 ),
1771 sql! (
1772 CREATE TABLE vim_global_marks_paths(
1773 workspace_id INTEGER,
1774 mark_name TEXT,
1775 path BLOB
1776 );
1777 CREATE UNIQUE INDEX idx_vim_global_marks_paths
1778 ON vim_global_marks_paths(workspace_id, mark_name);
1779 ),
1780 ];
1781}
1782
1783db::static_connection!(VimDb, [WorkspaceDb]);
1784
1785struct SerializedMark {
1786 path: Arc<Path>,
1787 name: String,
1788 points: Vec<Point>,
1789}
1790
1791impl VimDb {
1792 pub(crate) async fn set_marks(
1793 &self,
1794 workspace_id: WorkspaceId,
1795 path: Arc<Path>,
1796 marks: HashMap<String, Vec<Point>>,
1797 ) -> Result<()> {
1798 log::debug!("Setting path {path:?} for {} marks", marks.len());
1799
1800 self.write(move |conn| {
1801 let mut query = conn.exec_bound(sql!(
1802 INSERT OR REPLACE INTO vim_marks
1803 (workspace_id, mark_name, path, value)
1804 VALUES
1805 (?, ?, ?, ?)
1806 ))?;
1807 for (mark_name, value) in marks {
1808 let pairs: Vec<(u32, u32)> = value
1809 .into_iter()
1810 .map(|point| (point.row, point.column))
1811 .collect();
1812 let serialized = serde_json::to_string(&pairs)?;
1813 query((workspace_id, mark_name, path.clone(), serialized))?;
1814 }
1815 Ok(())
1816 })
1817 .await
1818 }
1819
1820 fn get_marks(&self, workspace_id: WorkspaceId) -> Result<Vec<SerializedMark>> {
1821 let result: Vec<(Arc<Path>, String, String)> = self.select_bound(sql!(
1822 SELECT path, mark_name, value FROM vim_marks
1823 WHERE workspace_id = ?
1824 ))?(workspace_id)?;
1825
1826 Ok(result
1827 .into_iter()
1828 .filter_map(|(path, name, value)| {
1829 let pairs: Vec<(u32, u32)> = serde_json::from_str(&value).log_err()?;
1830 Some(SerializedMark {
1831 path,
1832 name,
1833 points: pairs
1834 .into_iter()
1835 .map(|(row, column)| Point { row, column })
1836 .collect(),
1837 })
1838 })
1839 .collect())
1840 }
1841
1842 pub(crate) async fn delete_mark(
1843 &self,
1844 workspace_id: WorkspaceId,
1845 path: Arc<Path>,
1846 mark_name: String,
1847 ) -> Result<()> {
1848 self.write(move |conn| {
1849 conn.exec_bound(sql!(
1850 DELETE FROM vim_marks
1851 WHERE workspace_id = ? AND mark_name = ? AND path = ?
1852 ))?((workspace_id, mark_name, path))
1853 })
1854 .await
1855 }
1856
1857 pub(crate) async fn set_global_mark_path(
1858 &self,
1859 workspace_id: WorkspaceId,
1860 mark_name: String,
1861 path: Arc<Path>,
1862 ) -> Result<()> {
1863 log::debug!("Setting global mark path {path:?} for {mark_name}");
1864 self.write(move |conn| {
1865 conn.exec_bound(sql!(
1866 INSERT OR REPLACE INTO vim_global_marks_paths
1867 (workspace_id, mark_name, path)
1868 VALUES
1869 (?, ?, ?)
1870 ))?((workspace_id, mark_name, path))
1871 })
1872 .await
1873 }
1874
1875 pub fn get_global_marks_paths(
1876 &self,
1877 workspace_id: WorkspaceId,
1878 ) -> Result<Vec<(String, Arc<Path>)>> {
1879 self.select_bound(sql!(
1880 SELECT mark_name, path FROM vim_global_marks_paths
1881 WHERE workspace_id = ?
1882 ))?(workspace_id)
1883 }
1884
1885 pub(crate) async fn delete_global_marks_path(
1886 &self,
1887 workspace_id: WorkspaceId,
1888 mark_name: String,
1889 ) -> Result<()> {
1890 self.write(move |conn| {
1891 conn.exec_bound(sql!(
1892 DELETE FROM vim_global_marks_paths
1893 WHERE workspace_id = ? AND mark_name = ?
1894 ))?((workspace_id, mark_name))
1895 })
1896 .await
1897 }
1898}