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}
 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 { target: Some(_) }
1079            | Operator::DeleteSurrounds => true,
1080            Operator::Change
1081            | Operator::Delete
1082            | Operator::Yank
1083            | Operator::Rewrap
1084            | Operator::Indent
1085            | Operator::Outdent
1086            | Operator::AutoIndent
1087            | Operator::ShellCommand
1088            | Operator::Lowercase
1089            | Operator::Uppercase
1090            | Operator::Rot13
1091            | Operator::Rot47
1092            | Operator::ReplaceWithRegister
1093            | Operator::Exchange
1094            | Operator::Object { .. }
1095            | Operator::ChangeSurrounds { target: None }
1096            | Operator::OppositeCase
1097            | Operator::ToggleComments
1098            | Operator::HelixMatch
1099            | Operator::HelixNext { .. }
1100            | Operator::HelixPrevious { .. } => false,
1101        }
1102    }
1103
1104    pub fn starts_dot_recording(&self) -> bool {
1105        match self {
1106            Operator::Change
1107            | Operator::Delete
1108            | Operator::Replace
1109            | Operator::Indent
1110            | Operator::Outdent
1111            | Operator::AutoIndent
1112            | Operator::Lowercase
1113            | Operator::Uppercase
1114            | Operator::OppositeCase
1115            | Operator::Rot13
1116            | Operator::Rot47
1117            | Operator::ToggleComments
1118            | Operator::ReplaceWithRegister
1119            | Operator::Rewrap
1120            | Operator::ShellCommand
1121            | Operator::AddSurrounds { target: None }
1122            | Operator::ChangeSurrounds { target: None }
1123            | Operator::DeleteSurrounds
1124            | Operator::Exchange
1125            | Operator::HelixNext { .. }
1126            | Operator::HelixPrevious { .. } => true,
1127            Operator::Yank
1128            | Operator::Object { .. }
1129            | Operator::FindForward { .. }
1130            | Operator::FindBackward { .. }
1131            | Operator::Sneak { .. }
1132            | Operator::SneakBackward { .. }
1133            | Operator::Mark
1134            | Operator::Digraph { .. }
1135            | Operator::Literal { .. }
1136            | Operator::AddSurrounds { .. }
1137            | Operator::ChangeSurrounds { .. }
1138            | Operator::Jump { .. }
1139            | Operator::Register
1140            | Operator::RecordRegister
1141            | Operator::ReplayRegister
1142            | Operator::HelixMatch => false,
1143        }
1144    }
1145}
1146
1147struct RegisterMatch {
1148    name: char,
1149    contents: SharedString,
1150}
1151
1152pub struct RegistersViewDelegate {
1153    selected_index: usize,
1154    matches: Vec<RegisterMatch>,
1155}
1156
1157impl PickerDelegate for RegistersViewDelegate {
1158    type ListItem = Div;
1159
1160    fn match_count(&self) -> usize {
1161        self.matches.len()
1162    }
1163
1164    fn selected_index(&self) -> usize {
1165        self.selected_index
1166    }
1167
1168    fn set_selected_index(&mut self, ix: usize, _: &mut Window, cx: &mut Context<Picker<Self>>) {
1169        self.selected_index = ix;
1170        cx.notify();
1171    }
1172
1173    fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str> {
1174        Arc::default()
1175    }
1176
1177    fn update_matches(
1178        &mut self,
1179        _: String,
1180        _: &mut Window,
1181        _: &mut Context<Picker<Self>>,
1182    ) -> gpui::Task<()> {
1183        Task::ready(())
1184    }
1185
1186    fn confirm(&mut self, _: bool, _: &mut Window, _: &mut Context<Picker<Self>>) {}
1187
1188    fn dismissed(&mut self, _: &mut Window, _: &mut Context<Picker<Self>>) {}
1189
1190    fn render_match(
1191        &self,
1192        ix: usize,
1193        selected: bool,
1194        _: &mut Window,
1195        cx: &mut Context<Picker<Self>>,
1196    ) -> Option<Self::ListItem> {
1197        let register_match = self.matches.get(ix)?;
1198
1199        let mut output = String::new();
1200        let mut runs = Vec::new();
1201        output.push('"');
1202        output.push(register_match.name);
1203        runs.push((
1204            0..output.len(),
1205            HighlightStyle::color(cx.theme().colors().text_accent),
1206        ));
1207        output.push(' ');
1208        output.push(' ');
1209        let mut base = output.len();
1210        for (ix, c) in register_match.contents.char_indices() {
1211            if ix > 100 {
1212                break;
1213            }
1214            let replace = match c {
1215                '\t' => Some("\\t".to_string()),
1216                '\n' => Some("\\n".to_string()),
1217                '\r' => Some("\\r".to_string()),
1218                c if is_invisible(c) => {
1219                    if c <= '\x1f' {
1220                        replacement(c).map(|s| s.to_string())
1221                    } else {
1222                        Some(format!("\\u{:04X}", c as u32))
1223                    }
1224                }
1225                _ => None,
1226            };
1227            let Some(replace) = replace else {
1228                output.push(c);
1229                continue;
1230            };
1231            output.push_str(&replace);
1232            runs.push((
1233                base + ix..base + ix + replace.len(),
1234                HighlightStyle::color(cx.theme().colors().text_muted),
1235            ));
1236            base += replace.len() - c.len_utf8();
1237        }
1238
1239        let theme = ThemeSettings::get_global(cx);
1240        let text_style = TextStyle {
1241            color: cx.theme().colors().editor_foreground,
1242            font_family: theme.buffer_font.family.clone(),
1243            font_features: theme.buffer_font.features.clone(),
1244            font_fallbacks: theme.buffer_font.fallbacks.clone(),
1245            font_size: theme.buffer_font_size(cx).into(),
1246            line_height: (theme.line_height() * theme.buffer_font_size(cx)).into(),
1247            font_weight: theme.buffer_font.weight,
1248            font_style: theme.buffer_font.style,
1249            ..Default::default()
1250        };
1251
1252        Some(
1253            h_flex()
1254                .when(selected, |el| el.bg(cx.theme().colors().element_selected))
1255                .font_buffer(cx)
1256                .text_buffer(cx)
1257                .h(theme.buffer_font_size(cx) * theme.line_height())
1258                .px_2()
1259                .gap_1()
1260                .child(StyledText::new(output).with_default_highlights(&text_style, runs)),
1261        )
1262    }
1263}
1264
1265pub struct RegistersView {}
1266
1267impl RegistersView {
1268    fn register(workspace: &mut Workspace, _window: Option<&mut Window>) {
1269        workspace.register_action(|workspace, _: &ToggleRegistersView, window, cx| {
1270            Self::toggle(workspace, window, cx);
1271        });
1272    }
1273
1274    pub fn toggle(workspace: &mut Workspace, window: &mut Window, cx: &mut Context<Workspace>) {
1275        let editor = workspace
1276            .active_item(cx)
1277            .and_then(|item| item.act_as::<Editor>(cx));
1278        workspace.toggle_modal(window, cx, move |window, cx| {
1279            RegistersView::new(editor, window, cx)
1280        });
1281    }
1282
1283    fn new(
1284        editor: Option<Entity<Editor>>,
1285        window: &mut Window,
1286        cx: &mut Context<Picker<RegistersViewDelegate>>,
1287    ) -> Picker<RegistersViewDelegate> {
1288        let mut matches = Vec::default();
1289        cx.update_global(|globals: &mut VimGlobals, cx| {
1290            for name in ['"', '+', '*'] {
1291                if let Some(register) = globals.read_register(Some(name), None, cx) {
1292                    matches.push(RegisterMatch {
1293                        name,
1294                        contents: register.text.clone(),
1295                    })
1296                }
1297            }
1298            if let Some(editor) = editor {
1299                let register = editor.update(cx, |editor, cx| {
1300                    globals.read_register(Some('%'), Some(editor), cx)
1301                });
1302                if let Some(register) = register {
1303                    matches.push(RegisterMatch {
1304                        name: '%',
1305                        contents: register.text,
1306                    })
1307                }
1308            }
1309            for (name, register) in globals.registers.iter() {
1310                if ['"', '+', '*', '%'].contains(name) {
1311                    continue;
1312                };
1313                matches.push(RegisterMatch {
1314                    name: *name,
1315                    contents: register.text.clone(),
1316                })
1317            }
1318        });
1319        matches.sort_by(|a, b| a.name.cmp(&b.name));
1320        let delegate = RegistersViewDelegate {
1321            selected_index: 0,
1322            matches,
1323        };
1324
1325        Picker::nonsearchable_uniform_list(delegate, window, cx)
1326            .width(rems(36.))
1327            .modal(true)
1328    }
1329}
1330
1331enum MarksMatchInfo {
1332    Path(Arc<Path>),
1333    Title(String),
1334    Content {
1335        line: String,
1336        highlights: Vec<(Range<usize>, HighlightStyle)>,
1337    },
1338}
1339
1340impl MarksMatchInfo {
1341    fn from_chunks<'a>(chunks: impl Iterator<Item = Chunk<'a>>, cx: &App) -> Self {
1342        let mut line = String::new();
1343        let mut highlights = Vec::new();
1344        let mut offset = 0;
1345        for chunk in chunks {
1346            line.push_str(chunk.text);
1347            if let Some(highlight_style) = chunk.syntax_highlight_id
1348                && let Some(highlight) = highlight_style.style(cx.theme().syntax())
1349            {
1350                highlights.push((offset..offset + chunk.text.len(), highlight))
1351            }
1352            offset += chunk.text.len();
1353        }
1354        MarksMatchInfo::Content { line, highlights }
1355    }
1356}
1357
1358struct MarksMatch {
1359    name: String,
1360    position: Point,
1361    info: MarksMatchInfo,
1362}
1363
1364pub struct MarksViewDelegate {
1365    selected_index: usize,
1366    matches: Vec<MarksMatch>,
1367    point_column_width: usize,
1368    workspace: WeakEntity<Workspace>,
1369}
1370
1371impl PickerDelegate for MarksViewDelegate {
1372    type ListItem = Div;
1373
1374    fn match_count(&self) -> usize {
1375        self.matches.len()
1376    }
1377
1378    fn selected_index(&self) -> usize {
1379        self.selected_index
1380    }
1381
1382    fn set_selected_index(&mut self, ix: usize, _: &mut Window, cx: &mut Context<Picker<Self>>) {
1383        self.selected_index = ix;
1384        cx.notify();
1385    }
1386
1387    fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str> {
1388        Arc::default()
1389    }
1390
1391    fn update_matches(
1392        &mut self,
1393        _: String,
1394        _: &mut Window,
1395        cx: &mut Context<Picker<Self>>,
1396    ) -> gpui::Task<()> {
1397        let Some(workspace) = self.workspace.upgrade() else {
1398            return Task::ready(());
1399        };
1400        cx.spawn(async move |picker, cx| {
1401            let mut matches = Vec::new();
1402            let _ = workspace.update(cx, |workspace, cx| {
1403                let entity_id = cx.entity_id();
1404                let Some(editor) = workspace
1405                    .active_item(cx)
1406                    .and_then(|item| item.act_as::<Editor>(cx))
1407                else {
1408                    return;
1409                };
1410                let editor = editor.read(cx);
1411                let mut has_seen = HashSet::new();
1412                let Some(marks_state) = cx.global::<VimGlobals>().marks.get(&entity_id) else {
1413                    return;
1414                };
1415                let marks_state = marks_state.read(cx);
1416
1417                if let Some(map) = marks_state
1418                    .multibuffer_marks
1419                    .get(&editor.buffer().entity_id())
1420                {
1421                    for (name, anchors) in map {
1422                        if has_seen.contains(name) {
1423                            continue;
1424                        }
1425                        has_seen.insert(name.clone());
1426                        let Some(anchor) = anchors.first() else {
1427                            continue;
1428                        };
1429
1430                        let snapshot = editor.buffer().read(cx).snapshot(cx);
1431                        let position = anchor.to_point(&snapshot);
1432
1433                        let chunks = snapshot.chunks(
1434                            Point::new(position.row, 0)
1435                                ..Point::new(
1436                                    position.row,
1437                                    snapshot.line_len(MultiBufferRow(position.row)),
1438                                ),
1439                            true,
1440                        );
1441                        matches.push(MarksMatch {
1442                            name: name.clone(),
1443                            position,
1444                            info: MarksMatchInfo::from_chunks(chunks, cx),
1445                        })
1446                    }
1447                }
1448
1449                if let Some(buffer) = editor.buffer().read(cx).as_singleton() {
1450                    let buffer = buffer.read(cx);
1451                    if let Some(map) = marks_state.buffer_marks.get(&buffer.remote_id()) {
1452                        for (name, anchors) in map {
1453                            if has_seen.contains(name) {
1454                                continue;
1455                            }
1456                            has_seen.insert(name.clone());
1457                            let Some(anchor) = anchors.first() else {
1458                                continue;
1459                            };
1460                            let snapshot = buffer.snapshot();
1461                            let position = anchor.to_point(&snapshot);
1462                            let chunks = snapshot.chunks(
1463                                Point::new(position.row, 0)
1464                                    ..Point::new(position.row, snapshot.line_len(position.row)),
1465                                true,
1466                            );
1467
1468                            matches.push(MarksMatch {
1469                                name: name.clone(),
1470                                position,
1471                                info: MarksMatchInfo::from_chunks(chunks, cx),
1472                            })
1473                        }
1474                    }
1475                }
1476
1477                for (name, mark_location) in marks_state.global_marks.iter() {
1478                    if has_seen.contains(name) {
1479                        continue;
1480                    }
1481                    has_seen.insert(name.clone());
1482
1483                    match mark_location {
1484                        MarkLocation::Buffer(entity_id) => {
1485                            if let Some(&anchor) = marks_state
1486                                .multibuffer_marks
1487                                .get(entity_id)
1488                                .and_then(|map| map.get(name))
1489                                .and_then(|anchors| anchors.first())
1490                            {
1491                                let Some((info, snapshot)) = workspace
1492                                    .items(cx)
1493                                    .filter_map(|item| item.act_as::<Editor>(cx))
1494                                    .map(|entity| entity.read(cx).buffer())
1495                                    .find(|buffer| buffer.entity_id().eq(entity_id))
1496                                    .map(|buffer| {
1497                                        (
1498                                            MarksMatchInfo::Title(
1499                                                buffer.read(cx).title(cx).to_string(),
1500                                            ),
1501                                            buffer.read(cx).snapshot(cx),
1502                                        )
1503                                    })
1504                                else {
1505                                    continue;
1506                                };
1507                                matches.push(MarksMatch {
1508                                    name: name.clone(),
1509                                    position: anchor.to_point(&snapshot),
1510                                    info,
1511                                });
1512                            }
1513                        }
1514                        MarkLocation::Path(path) => {
1515                            if let Some(&position) = marks_state
1516                                .serialized_marks
1517                                .get(path.as_ref())
1518                                .and_then(|map| map.get(name))
1519                                .and_then(|points| points.first())
1520                            {
1521                                let info = MarksMatchInfo::Path(path.clone());
1522                                matches.push(MarksMatch {
1523                                    name: name.clone(),
1524                                    position,
1525                                    info,
1526                                });
1527                            }
1528                        }
1529                    }
1530                }
1531            });
1532            let _ = picker.update(cx, |picker, cx| {
1533                matches.sort_by_key(|a| {
1534                    (
1535                        a.name.chars().next().map(|c| c.is_ascii_uppercase()),
1536                        a.name.clone(),
1537                    )
1538                });
1539                let digits = matches
1540                    .iter()
1541                    .map(|m| (m.position.row + 1).ilog10() + (m.position.column + 1).ilog10())
1542                    .max()
1543                    .unwrap_or_default();
1544                picker.delegate.matches = matches;
1545                picker.delegate.point_column_width = (digits + 4) as usize;
1546                cx.notify();
1547            });
1548        })
1549    }
1550
1551    fn confirm(&mut self, _: bool, window: &mut Window, cx: &mut Context<Picker<Self>>) {
1552        let Some(vim) = self
1553            .workspace
1554            .upgrade()
1555            .map(|w| w.read(cx))
1556            .and_then(|w| w.focused_pane(window, cx).read(cx).active_item())
1557            .and_then(|item| item.act_as::<Editor>(cx))
1558            .and_then(|editor| editor.read(cx).addon::<VimAddon>().cloned())
1559            .map(|addon| addon.entity)
1560        else {
1561            return;
1562        };
1563        let Some(text): Option<Arc<str>> = self
1564            .matches
1565            .get(self.selected_index)
1566            .map(|m| Arc::from(m.name.to_string().into_boxed_str()))
1567        else {
1568            return;
1569        };
1570        vim.update(cx, |vim, cx| {
1571            vim.jump(text, false, false, window, cx);
1572        });
1573
1574        cx.emit(DismissEvent);
1575    }
1576
1577    fn dismissed(&mut self, _: &mut Window, _: &mut Context<Picker<Self>>) {}
1578
1579    fn render_match(
1580        &self,
1581        ix: usize,
1582        selected: bool,
1583        _: &mut Window,
1584        cx: &mut Context<Picker<Self>>,
1585    ) -> Option<Self::ListItem> {
1586        let mark_match = self.matches.get(ix)?;
1587
1588        let mut left_output = String::new();
1589        let mut left_runs = Vec::new();
1590        left_output.push('`');
1591        left_output.push_str(&mark_match.name);
1592        left_runs.push((
1593            0..left_output.len(),
1594            HighlightStyle::color(cx.theme().colors().text_accent),
1595        ));
1596        left_output.push(' ');
1597        left_output.push(' ');
1598        let point_column = format!(
1599            "{},{}",
1600            mark_match.position.row + 1,
1601            mark_match.position.column + 1
1602        );
1603        left_output.push_str(&point_column);
1604        if let Some(padding) = self.point_column_width.checked_sub(point_column.len()) {
1605            left_output.push_str(&" ".repeat(padding));
1606        }
1607
1608        let (right_output, right_runs): (String, Vec<_>) = match &mark_match.info {
1609            MarksMatchInfo::Path(path) => {
1610                let s = path.to_string_lossy().to_string();
1611                (
1612                    s.clone(),
1613                    vec![(0..s.len(), HighlightStyle::color(cx.theme().colors().text))],
1614                )
1615            }
1616            MarksMatchInfo::Title(title) => (
1617                title.clone(),
1618                vec![(
1619                    0..title.len(),
1620                    HighlightStyle::color(cx.theme().colors().text),
1621                )],
1622            ),
1623            MarksMatchInfo::Content { line, highlights } => (line.clone(), highlights.clone()),
1624        };
1625
1626        let theme = ThemeSettings::get_global(cx);
1627        let text_style = TextStyle {
1628            color: cx.theme().colors().editor_foreground,
1629            font_family: theme.buffer_font.family.clone(),
1630            font_features: theme.buffer_font.features.clone(),
1631            font_fallbacks: theme.buffer_font.fallbacks.clone(),
1632            font_size: theme.buffer_font_size(cx).into(),
1633            line_height: (theme.line_height() * theme.buffer_font_size(cx)).into(),
1634            font_weight: theme.buffer_font.weight,
1635            font_style: theme.buffer_font.style,
1636            ..Default::default()
1637        };
1638
1639        Some(
1640            h_flex()
1641                .when(selected, |el| el.bg(cx.theme().colors().element_selected))
1642                .font_buffer(cx)
1643                .text_buffer(cx)
1644                .h(theme.buffer_font_size(cx) * theme.line_height())
1645                .px_2()
1646                .child(StyledText::new(left_output).with_default_highlights(&text_style, left_runs))
1647                .child(
1648                    StyledText::new(right_output).with_default_highlights(&text_style, right_runs),
1649                ),
1650        )
1651    }
1652}
1653
1654pub struct MarksView {}
1655
1656impl MarksView {
1657    fn register(workspace: &mut Workspace, _window: Option<&mut Window>) {
1658        workspace.register_action(|workspace, _: &ToggleMarksView, window, cx| {
1659            Self::toggle(workspace, window, cx);
1660        });
1661    }
1662
1663    pub fn toggle(workspace: &mut Workspace, window: &mut Window, cx: &mut Context<Workspace>) {
1664        let handle = cx.weak_entity();
1665        workspace.toggle_modal(window, cx, move |window, cx| {
1666            MarksView::new(handle, window, cx)
1667        });
1668    }
1669
1670    fn new(
1671        workspace: WeakEntity<Workspace>,
1672        window: &mut Window,
1673        cx: &mut Context<Picker<MarksViewDelegate>>,
1674    ) -> Picker<MarksViewDelegate> {
1675        let matches = Vec::default();
1676        let delegate = MarksViewDelegate {
1677            selected_index: 0,
1678            point_column_width: 0,
1679            matches,
1680            workspace,
1681        };
1682        Picker::nonsearchable_uniform_list(delegate, window, cx)
1683            .width(rems(36.))
1684            .modal(true)
1685    }
1686}
1687
1688pub struct VimDb(ThreadSafeConnection);
1689
1690impl Domain for VimDb {
1691    const NAME: &str = stringify!(VimDb);
1692
1693    const MIGRATIONS: &[&str] = &[
1694        sql! (
1695            CREATE TABLE vim_marks (
1696              workspace_id INTEGER,
1697              mark_name TEXT,
1698              path BLOB,
1699              value TEXT
1700            );
1701            CREATE UNIQUE INDEX idx_vim_marks ON vim_marks (workspace_id, mark_name, path);
1702        ),
1703        sql! (
1704            CREATE TABLE vim_global_marks_paths(
1705                workspace_id INTEGER,
1706                mark_name TEXT,
1707                path BLOB
1708            );
1709            CREATE UNIQUE INDEX idx_vim_global_marks_paths
1710            ON vim_global_marks_paths(workspace_id, mark_name);
1711        ),
1712    ];
1713}
1714
1715db::static_connection!(DB, VimDb, [WorkspaceDb]);
1716
1717struct SerializedMark {
1718    path: Arc<Path>,
1719    name: String,
1720    points: Vec<Point>,
1721}
1722
1723impl VimDb {
1724    pub(crate) async fn set_marks(
1725        &self,
1726        workspace_id: WorkspaceId,
1727        path: Arc<Path>,
1728        marks: HashMap<String, Vec<Point>>,
1729    ) -> Result<()> {
1730        log::debug!("Setting path {path:?} for {} marks", marks.len());
1731
1732        self.write(move |conn| {
1733            let mut query = conn.exec_bound(sql!(
1734                INSERT OR REPLACE INTO vim_marks
1735                    (workspace_id, mark_name, path, value)
1736                VALUES
1737                    (?, ?, ?, ?)
1738            ))?;
1739            for (mark_name, value) in marks {
1740                let pairs: Vec<(u32, u32)> = value
1741                    .into_iter()
1742                    .map(|point| (point.row, point.column))
1743                    .collect();
1744                let serialized = serde_json::to_string(&pairs)?;
1745                query((workspace_id, mark_name, path.clone(), serialized))?;
1746            }
1747            Ok(())
1748        })
1749        .await
1750    }
1751
1752    fn get_marks(&self, workspace_id: WorkspaceId) -> Result<Vec<SerializedMark>> {
1753        let result: Vec<(Arc<Path>, String, String)> = self.select_bound(sql!(
1754            SELECT path, mark_name, value FROM vim_marks
1755                WHERE workspace_id = ?
1756        ))?(workspace_id)?;
1757
1758        Ok(result
1759            .into_iter()
1760            .filter_map(|(path, name, value)| {
1761                let pairs: Vec<(u32, u32)> = serde_json::from_str(&value).log_err()?;
1762                Some(SerializedMark {
1763                    path,
1764                    name,
1765                    points: pairs
1766                        .into_iter()
1767                        .map(|(row, column)| Point { row, column })
1768                        .collect(),
1769                })
1770            })
1771            .collect())
1772    }
1773
1774    pub(crate) async fn delete_mark(
1775        &self,
1776        workspace_id: WorkspaceId,
1777        path: Arc<Path>,
1778        mark_name: String,
1779    ) -> Result<()> {
1780        self.write(move |conn| {
1781            conn.exec_bound(sql!(
1782                DELETE FROM vim_marks
1783                WHERE workspace_id = ? AND mark_name = ? AND path = ?
1784            ))?((workspace_id, mark_name, path))
1785        })
1786        .await
1787    }
1788
1789    pub(crate) async fn set_global_mark_path(
1790        &self,
1791        workspace_id: WorkspaceId,
1792        mark_name: String,
1793        path: Arc<Path>,
1794    ) -> Result<()> {
1795        log::debug!("Setting global mark path {path:?} for {mark_name}");
1796        self.write(move |conn| {
1797            conn.exec_bound(sql!(
1798                INSERT OR REPLACE INTO vim_global_marks_paths
1799                    (workspace_id, mark_name, path)
1800                VALUES
1801                    (?, ?, ?)
1802            ))?((workspace_id, mark_name, path))
1803        })
1804        .await
1805    }
1806
1807    pub fn get_global_marks_paths(
1808        &self,
1809        workspace_id: WorkspaceId,
1810    ) -> Result<Vec<(String, Arc<Path>)>> {
1811        self.select_bound(sql!(
1812        SELECT mark_name, path FROM vim_global_marks_paths
1813            WHERE workspace_id = ?
1814        ))?(workspace_id)
1815    }
1816
1817    pub(crate) async fn delete_global_marks_path(
1818        &self,
1819        workspace_id: WorkspaceId,
1820        mark_name: String,
1821    ) -> Result<()> {
1822        self.write(move |conn| {
1823            conn.exec_bound(sql!(
1824                DELETE FROM vim_global_marks_paths
1825                WHERE workspace_id = ? AND mark_name = ?
1826            ))?((workspace_id, mark_name))
1827        })
1828        .await
1829    }
1830}