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