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