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