state.rs

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