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