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