state.rs

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