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