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