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