state.rs

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