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