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