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