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