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