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