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