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