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