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