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