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        match self {
1032            Operator::Digraph {
1033                first_char: Some(first_char),
1034            } => format!("^K{first_char}"),
1035            Operator::Literal {
1036                prefix: Some(prefix),
1037            } => format!("^V{prefix}"),
1038            Operator::AutoIndent => "=".to_string(),
1039            Operator::ShellCommand => "=".to_string(),
1040            _ => self.id().to_string(),
1041        }
1042    }
1043
1044    pub fn is_waiting(&self, mode: Mode) -> bool {
1045        match self {
1046            Operator::AddSurrounds { target } => target.is_some() || mode.is_visual(),
1047            Operator::FindForward { .. }
1048            | Operator::Mark
1049            | Operator::Jump { .. }
1050            | Operator::FindBackward { .. }
1051            | Operator::Sneak { .. }
1052            | Operator::SneakBackward { .. }
1053            | Operator::Register
1054            | Operator::RecordRegister
1055            | Operator::ReplayRegister
1056            | Operator::Replace
1057            | Operator::Digraph { .. }
1058            | Operator::Literal { .. }
1059            | Operator::ChangeSurrounds { target: Some(_) }
1060            | Operator::DeleteSurrounds => true,
1061            Operator::Change
1062            | Operator::Delete
1063            | Operator::Yank
1064            | Operator::Rewrap
1065            | Operator::Indent
1066            | Operator::Outdent
1067            | Operator::AutoIndent
1068            | Operator::ShellCommand
1069            | Operator::Lowercase
1070            | Operator::Uppercase
1071            | Operator::Rot13
1072            | Operator::Rot47
1073            | Operator::ReplaceWithRegister
1074            | Operator::Exchange
1075            | Operator::Object { .. }
1076            | Operator::ChangeSurrounds { target: None }
1077            | Operator::OppositeCase
1078            | Operator::ToggleComments => false,
1079        }
1080    }
1081
1082    pub fn starts_dot_recording(&self) -> bool {
1083        match self {
1084            Operator::Change
1085            | Operator::Delete
1086            | Operator::Replace
1087            | Operator::Indent
1088            | Operator::Outdent
1089            | Operator::AutoIndent
1090            | Operator::Lowercase
1091            | Operator::Uppercase
1092            | Operator::OppositeCase
1093            | Operator::Rot13
1094            | Operator::Rot47
1095            | Operator::ToggleComments
1096            | Operator::ReplaceWithRegister
1097            | Operator::Rewrap
1098            | Operator::ShellCommand
1099            | Operator::AddSurrounds { target: None }
1100            | Operator::ChangeSurrounds { target: None }
1101            | Operator::DeleteSurrounds
1102            | Operator::Exchange => true,
1103            Operator::Yank
1104            | Operator::Object { .. }
1105            | Operator::FindForward { .. }
1106            | Operator::FindBackward { .. }
1107            | Operator::Sneak { .. }
1108            | Operator::SneakBackward { .. }
1109            | Operator::Mark
1110            | Operator::Digraph { .. }
1111            | Operator::Literal { .. }
1112            | Operator::AddSurrounds { .. }
1113            | Operator::ChangeSurrounds { .. }
1114            | Operator::Jump { .. }
1115            | Operator::Register
1116            | Operator::RecordRegister
1117            | Operator::ReplayRegister => false,
1118        }
1119    }
1120}
1121
1122struct RegisterMatch {
1123    name: char,
1124    contents: SharedString,
1125}
1126
1127pub struct RegistersViewDelegate {
1128    selected_index: usize,
1129    matches: Vec<RegisterMatch>,
1130}
1131
1132impl PickerDelegate for RegistersViewDelegate {
1133    type ListItem = Div;
1134
1135    fn match_count(&self) -> usize {
1136        self.matches.len()
1137    }
1138
1139    fn selected_index(&self) -> usize {
1140        self.selected_index
1141    }
1142
1143    fn set_selected_index(&mut self, ix: usize, _: &mut Window, cx: &mut Context<Picker<Self>>) {
1144        self.selected_index = ix;
1145        cx.notify();
1146    }
1147
1148    fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str> {
1149        Arc::default()
1150    }
1151
1152    fn update_matches(
1153        &mut self,
1154        _: String,
1155        _: &mut Window,
1156        _: &mut Context<Picker<Self>>,
1157    ) -> gpui::Task<()> {
1158        Task::ready(())
1159    }
1160
1161    fn confirm(&mut self, _: bool, _: &mut Window, _: &mut Context<Picker<Self>>) {}
1162
1163    fn dismissed(&mut self, _: &mut Window, _: &mut Context<Picker<Self>>) {}
1164
1165    fn render_match(
1166        &self,
1167        ix: usize,
1168        selected: bool,
1169        _: &mut Window,
1170        cx: &mut Context<Picker<Self>>,
1171    ) -> Option<Self::ListItem> {
1172        let register_match = self
1173            .matches
1174            .get(ix)
1175            .expect("Invalid matches state: no element for index {ix}");
1176
1177        let mut output = String::new();
1178        let mut runs = Vec::new();
1179        output.push('"');
1180        output.push(register_match.name);
1181        runs.push((
1182            0..output.len(),
1183            HighlightStyle::color(cx.theme().colors().text_accent),
1184        ));
1185        output.push(' ');
1186        output.push(' ');
1187        let mut base = output.len();
1188        for (ix, c) in register_match.contents.char_indices() {
1189            if ix > 100 {
1190                break;
1191            }
1192            let replace = match c {
1193                '\t' => Some("\\t".to_string()),
1194                '\n' => Some("\\n".to_string()),
1195                '\r' => Some("\\r".to_string()),
1196                c if is_invisible(c) => {
1197                    if c <= '\x1f' {
1198                        replacement(c).map(|s| s.to_string())
1199                    } else {
1200                        Some(format!("\\u{:04X}", c as u32))
1201                    }
1202                }
1203                _ => None,
1204            };
1205            let Some(replace) = replace else {
1206                output.push(c);
1207                continue;
1208            };
1209            output.push_str(&replace);
1210            runs.push((
1211                base + ix..base + ix + replace.len(),
1212                HighlightStyle::color(cx.theme().colors().text_muted),
1213            ));
1214            base += replace.len() - c.len_utf8();
1215        }
1216
1217        let theme = ThemeSettings::get_global(cx);
1218        let text_style = TextStyle {
1219            color: cx.theme().colors().editor_foreground,
1220            font_family: theme.buffer_font.family.clone(),
1221            font_features: theme.buffer_font.features.clone(),
1222            font_fallbacks: theme.buffer_font.fallbacks.clone(),
1223            font_size: theme.buffer_font_size(cx).into(),
1224            line_height: (theme.line_height() * theme.buffer_font_size(cx)).into(),
1225            font_weight: theme.buffer_font.weight,
1226            font_style: theme.buffer_font.style,
1227            ..Default::default()
1228        };
1229
1230        Some(
1231            h_flex()
1232                .when(selected, |el| el.bg(cx.theme().colors().element_selected))
1233                .font_buffer(cx)
1234                .text_buffer(cx)
1235                .h(theme.buffer_font_size(cx) * theme.line_height())
1236                .px_2()
1237                .gap_1()
1238                .child(StyledText::new(output).with_default_highlights(&text_style, runs)),
1239        )
1240    }
1241}
1242
1243pub struct RegistersView {}
1244
1245impl RegistersView {
1246    fn register(workspace: &mut Workspace, _window: Option<&mut Window>) {
1247        workspace.register_action(|workspace, _: &ToggleRegistersView, window, cx| {
1248            Self::toggle(workspace, window, cx);
1249        });
1250    }
1251
1252    pub fn toggle(workspace: &mut Workspace, window: &mut Window, cx: &mut Context<Workspace>) {
1253        let editor = workspace
1254            .active_item(cx)
1255            .and_then(|item| item.act_as::<Editor>(cx));
1256        workspace.toggle_modal(window, cx, move |window, cx| {
1257            RegistersView::new(editor, window, cx)
1258        });
1259    }
1260
1261    fn new(
1262        editor: Option<Entity<Editor>>,
1263        window: &mut Window,
1264        cx: &mut Context<Picker<RegistersViewDelegate>>,
1265    ) -> Picker<RegistersViewDelegate> {
1266        let mut matches = Vec::default();
1267        cx.update_global(|globals: &mut VimGlobals, cx| {
1268            for name in ['"', '+', '*'] {
1269                if let Some(register) = globals.read_register(Some(name), None, cx) {
1270                    matches.push(RegisterMatch {
1271                        name,
1272                        contents: register.text.clone(),
1273                    })
1274                }
1275            }
1276            if let Some(editor) = editor {
1277                let register = editor.update(cx, |editor, cx| {
1278                    globals.read_register(Some('%'), Some(editor), cx)
1279                });
1280                if let Some(register) = register {
1281                    matches.push(RegisterMatch {
1282                        name: '%',
1283                        contents: register.text.clone(),
1284                    })
1285                }
1286            }
1287            for (name, register) in globals.registers.iter() {
1288                if ['"', '+', '*', '%'].contains(name) {
1289                    continue;
1290                };
1291                matches.push(RegisterMatch {
1292                    name: *name,
1293                    contents: register.text.clone(),
1294                })
1295            }
1296        });
1297        matches.sort_by(|a, b| a.name.cmp(&b.name));
1298        let delegate = RegistersViewDelegate {
1299            selected_index: 0,
1300            matches,
1301        };
1302
1303        Picker::nonsearchable_uniform_list(delegate, window, cx)
1304            .width(rems(36.))
1305            .modal(true)
1306    }
1307}
1308
1309enum MarksMatchInfo {
1310    Path(Arc<Path>),
1311    Title(String),
1312    Content {
1313        line: String,
1314        highlights: Vec<(Range<usize>, HighlightStyle)>,
1315    },
1316}
1317
1318impl MarksMatchInfo {
1319    fn from_chunks<'a>(chunks: impl Iterator<Item = Chunk<'a>>, cx: &App) -> Self {
1320        let mut line = String::new();
1321        let mut highlights = Vec::new();
1322        let mut offset = 0;
1323        for chunk in chunks {
1324            line.push_str(chunk.text);
1325            if let Some(highlight_style) = chunk.syntax_highlight_id {
1326                if let Some(highlight) = highlight_style.style(cx.theme().syntax()) {
1327                    highlights.push((offset..offset + chunk.text.len(), highlight))
1328                }
1329            }
1330            offset += chunk.text.len();
1331        }
1332        MarksMatchInfo::Content { line, highlights }
1333    }
1334}
1335
1336struct MarksMatch {
1337    name: String,
1338    position: Point,
1339    info: MarksMatchInfo,
1340}
1341
1342pub struct MarksViewDelegate {
1343    selected_index: usize,
1344    matches: Vec<MarksMatch>,
1345    point_column_width: usize,
1346    workspace: WeakEntity<Workspace>,
1347}
1348
1349impl PickerDelegate for MarksViewDelegate {
1350    type ListItem = Div;
1351
1352    fn match_count(&self) -> usize {
1353        self.matches.len()
1354    }
1355
1356    fn selected_index(&self) -> usize {
1357        self.selected_index
1358    }
1359
1360    fn set_selected_index(&mut self, ix: usize, _: &mut Window, cx: &mut Context<Picker<Self>>) {
1361        self.selected_index = ix;
1362        cx.notify();
1363    }
1364
1365    fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str> {
1366        Arc::default()
1367    }
1368
1369    fn update_matches(
1370        &mut self,
1371        _: String,
1372        _: &mut Window,
1373        cx: &mut Context<Picker<Self>>,
1374    ) -> gpui::Task<()> {
1375        let Some(workspace) = self.workspace.upgrade().clone() else {
1376            return Task::ready(());
1377        };
1378        cx.spawn(async move |picker, cx| {
1379            let mut matches = Vec::new();
1380            let _ = workspace.update(cx, |workspace, cx| {
1381                let entity_id = cx.entity_id();
1382                let Some(editor) = workspace
1383                    .active_item(cx)
1384                    .and_then(|item| item.act_as::<Editor>(cx))
1385                else {
1386                    return;
1387                };
1388                let editor = editor.read(cx);
1389                let mut has_seen = HashSet::new();
1390                let Some(marks_state) = cx.global::<VimGlobals>().marks.get(&entity_id) else {
1391                    return;
1392                };
1393                let marks_state = marks_state.read(cx);
1394
1395                if let Some(map) = marks_state
1396                    .multibuffer_marks
1397                    .get(&editor.buffer().entity_id())
1398                {
1399                    for (name, anchors) in map {
1400                        if has_seen.contains(name) {
1401                            continue;
1402                        }
1403                        has_seen.insert(name.clone());
1404                        let Some(anchor) = anchors.first() else {
1405                            continue;
1406                        };
1407
1408                        let snapshot = editor.buffer().read(cx).snapshot(cx);
1409                        let position = anchor.to_point(&snapshot);
1410
1411                        let chunks = snapshot.chunks(
1412                            Point::new(position.row, 0)
1413                                ..Point::new(
1414                                    position.row,
1415                                    snapshot.line_len(MultiBufferRow(position.row)),
1416                                ),
1417                            true,
1418                        );
1419                        matches.push(MarksMatch {
1420                            name: name.clone(),
1421                            position,
1422                            info: MarksMatchInfo::from_chunks(chunks, cx),
1423                        })
1424                    }
1425                }
1426
1427                if let Some(buffer) = editor.buffer().read(cx).as_singleton() {
1428                    let buffer = buffer.read(cx);
1429                    if let Some(map) = marks_state.buffer_marks.get(&buffer.remote_id()) {
1430                        for (name, anchors) in map {
1431                            if has_seen.contains(name) {
1432                                continue;
1433                            }
1434                            has_seen.insert(name.clone());
1435                            let Some(anchor) = anchors.first() else {
1436                                continue;
1437                            };
1438                            let snapshot = buffer.snapshot();
1439                            let position = anchor.to_point(&snapshot);
1440                            let chunks = snapshot.chunks(
1441                                Point::new(position.row, 0)
1442                                    ..Point::new(position.row, snapshot.line_len(position.row)),
1443                                true,
1444                            );
1445
1446                            matches.push(MarksMatch {
1447                                name: name.clone(),
1448                                position,
1449                                info: MarksMatchInfo::from_chunks(chunks, cx),
1450                            })
1451                        }
1452                    }
1453                }
1454
1455                for (name, mark_location) in marks_state.global_marks.iter() {
1456                    if has_seen.contains(name) {
1457                        continue;
1458                    }
1459                    has_seen.insert(name.clone());
1460
1461                    match mark_location {
1462                        MarkLocation::Buffer(entity_id) => {
1463                            if let Some(&anchor) = marks_state
1464                                .multibuffer_marks
1465                                .get(entity_id)
1466                                .and_then(|map| map.get(name))
1467                                .and_then(|anchors| anchors.first())
1468                            {
1469                                let Some((info, snapshot)) = workspace
1470                                    .items(cx)
1471                                    .filter_map(|item| item.act_as::<Editor>(cx))
1472                                    .map(|entity| entity.read(cx).buffer())
1473                                    .find(|buffer| buffer.entity_id().eq(entity_id))
1474                                    .map(|buffer| {
1475                                        (
1476                                            MarksMatchInfo::Title(
1477                                                buffer.read(cx).title(cx).to_string(),
1478                                            ),
1479                                            buffer.read(cx).snapshot(cx),
1480                                        )
1481                                    })
1482                                else {
1483                                    continue;
1484                                };
1485                                matches.push(MarksMatch {
1486                                    name: name.clone(),
1487                                    position: anchor.to_point(&snapshot),
1488                                    info,
1489                                });
1490                            }
1491                        }
1492                        MarkLocation::Path(path) => {
1493                            if let Some(&position) = marks_state
1494                                .serialized_marks
1495                                .get(path.as_ref())
1496                                .and_then(|map| map.get(name))
1497                                .and_then(|points| points.first())
1498                            {
1499                                let info = MarksMatchInfo::Path(path.clone());
1500                                matches.push(MarksMatch {
1501                                    name: name.clone(),
1502                                    position,
1503                                    info,
1504                                });
1505                            }
1506                        }
1507                    }
1508                }
1509            });
1510            let _ = picker.update(cx, |picker, cx| {
1511                matches.sort_by_key(|a| {
1512                    (
1513                        a.name.chars().next().map(|c| c.is_ascii_uppercase()),
1514                        a.name.clone(),
1515                    )
1516                });
1517                let digits = matches
1518                    .iter()
1519                    .map(|m| (m.position.row + 1).ilog10() + (m.position.column + 1).ilog10())
1520                    .max()
1521                    .unwrap_or_default();
1522                picker.delegate.matches = matches;
1523                picker.delegate.point_column_width = (digits + 4) as usize;
1524                cx.notify();
1525            });
1526        })
1527    }
1528
1529    fn confirm(&mut self, _: bool, window: &mut Window, cx: &mut Context<Picker<Self>>) {
1530        let Some(vim) = self
1531            .workspace
1532            .upgrade()
1533            .map(|w| w.read(cx))
1534            .and_then(|w| w.focused_pane(window, cx).read(cx).active_item())
1535            .and_then(|item| item.act_as::<Editor>(cx))
1536            .and_then(|editor| editor.read(cx).addon::<VimAddon>().cloned())
1537            .map(|addon| addon.entity)
1538        else {
1539            return;
1540        };
1541        let Some(text): Option<Arc<str>> = self
1542            .matches
1543            .get(self.selected_index)
1544            .map(|m| Arc::from(m.name.to_string().into_boxed_str()))
1545        else {
1546            return;
1547        };
1548        vim.update(cx, |vim, cx| {
1549            vim.jump(text, false, false, window, cx);
1550        });
1551
1552        cx.emit(DismissEvent);
1553    }
1554
1555    fn dismissed(&mut self, _: &mut Window, _: &mut Context<Picker<Self>>) {}
1556
1557    fn render_match(
1558        &self,
1559        ix: usize,
1560        selected: bool,
1561        _: &mut Window,
1562        cx: &mut Context<Picker<Self>>,
1563    ) -> Option<Self::ListItem> {
1564        let mark_match = self
1565            .matches
1566            .get(ix)
1567            .expect("Invalid matches state: no element for index {ix}");
1568
1569        let mut left_output = String::new();
1570        let mut left_runs = Vec::new();
1571        left_output.push('`');
1572        left_output.push_str(&mark_match.name);
1573        left_runs.push((
1574            0..left_output.len(),
1575            HighlightStyle::color(cx.theme().colors().text_accent),
1576        ));
1577        left_output.push(' ');
1578        left_output.push(' ');
1579        let point_column = format!(
1580            "{},{}",
1581            mark_match.position.row + 1,
1582            mark_match.position.column + 1
1583        );
1584        left_output.push_str(&point_column);
1585        if let Some(padding) = self.point_column_width.checked_sub(point_column.len()) {
1586            left_output.push_str(&" ".repeat(padding));
1587        }
1588
1589        let (right_output, right_runs): (String, Vec<_>) = match &mark_match.info {
1590            MarksMatchInfo::Path(path) => {
1591                let s = path.to_string_lossy().to_string();
1592                (
1593                    s.clone(),
1594                    vec![(0..s.len(), HighlightStyle::color(cx.theme().colors().text))],
1595                )
1596            }
1597            MarksMatchInfo::Title(title) => (
1598                title.clone(),
1599                vec![(
1600                    0..title.len(),
1601                    HighlightStyle::color(cx.theme().colors().text),
1602                )],
1603            ),
1604            MarksMatchInfo::Content { line, highlights } => (line.clone(), highlights.clone()),
1605        };
1606
1607        let theme = ThemeSettings::get_global(cx);
1608        let text_style = TextStyle {
1609            color: cx.theme().colors().editor_foreground,
1610            font_family: theme.buffer_font.family.clone(),
1611            font_features: theme.buffer_font.features.clone(),
1612            font_fallbacks: theme.buffer_font.fallbacks.clone(),
1613            font_size: theme.buffer_font_size(cx).into(),
1614            line_height: (theme.line_height() * theme.buffer_font_size(cx)).into(),
1615            font_weight: theme.buffer_font.weight,
1616            font_style: theme.buffer_font.style,
1617            ..Default::default()
1618        };
1619
1620        Some(
1621            h_flex()
1622                .when(selected, |el| el.bg(cx.theme().colors().element_selected))
1623                .font_buffer(cx)
1624                .text_buffer(cx)
1625                .h(theme.buffer_font_size(cx) * theme.line_height())
1626                .px_2()
1627                .child(StyledText::new(left_output).with_default_highlights(&text_style, left_runs))
1628                .child(
1629                    StyledText::new(right_output).with_default_highlights(&text_style, right_runs),
1630                ),
1631        )
1632    }
1633}
1634
1635pub struct MarksView {}
1636
1637impl MarksView {
1638    fn register(workspace: &mut Workspace, _window: Option<&mut Window>) {
1639        workspace.register_action(|workspace, _: &ToggleMarksView, window, cx| {
1640            Self::toggle(workspace, window, cx);
1641        });
1642    }
1643
1644    pub fn toggle(workspace: &mut Workspace, window: &mut Window, cx: &mut Context<Workspace>) {
1645        let handle = cx.weak_entity();
1646        workspace.toggle_modal(window, cx, move |window, cx| {
1647            MarksView::new(handle, window, cx)
1648        });
1649    }
1650
1651    fn new(
1652        workspace: WeakEntity<Workspace>,
1653        window: &mut Window,
1654        cx: &mut Context<Picker<MarksViewDelegate>>,
1655    ) -> Picker<MarksViewDelegate> {
1656        let matches = Vec::default();
1657        let delegate = MarksViewDelegate {
1658            selected_index: 0,
1659            point_column_width: 0,
1660            matches,
1661            workspace,
1662        };
1663        Picker::nonsearchable_uniform_list(delegate, window, cx)
1664            .width(rems(36.))
1665            .modal(true)
1666    }
1667}
1668
1669define_connection! (
1670    pub static ref DB: VimDb<WorkspaceDb> = &[
1671        sql! (
1672            CREATE TABLE vim_marks (
1673              workspace_id INTEGER,
1674              mark_name TEXT,
1675              path BLOB,
1676              value TEXT
1677            );
1678            CREATE UNIQUE INDEX idx_vim_marks ON vim_marks (workspace_id, mark_name, path);
1679        ),
1680        sql! (
1681            CREATE TABLE vim_global_marks_paths(
1682                workspace_id INTEGER,
1683                mark_name TEXT,
1684                path BLOB
1685            );
1686            CREATE UNIQUE INDEX idx_vim_global_marks_paths
1687            ON vim_global_marks_paths(workspace_id, mark_name);
1688        ),
1689    ];
1690);
1691
1692struct SerializedMark {
1693    path: Arc<Path>,
1694    name: String,
1695    points: Vec<Point>,
1696}
1697
1698impl VimDb {
1699    pub(crate) async fn set_marks(
1700        &self,
1701        workspace_id: WorkspaceId,
1702        path: Arc<Path>,
1703        marks: HashMap<String, Vec<Point>>,
1704    ) -> Result<()> {
1705        log::debug!("Setting path {path:?} for {} marks", marks.len());
1706        let result = self
1707            .write(move |conn| {
1708                let mut query = conn.exec_bound(sql!(
1709                    INSERT OR REPLACE INTO vim_marks
1710                        (workspace_id, mark_name, path, value)
1711                    VALUES
1712                        (?, ?, ?, ?)
1713                ))?;
1714                for (mark_name, value) in marks {
1715                    let pairs: Vec<(u32, u32)> = value
1716                        .into_iter()
1717                        .map(|point| (point.row, point.column))
1718                        .collect();
1719                    let serialized = serde_json::to_string(&pairs)?;
1720                    query((workspace_id, mark_name, path.clone(), serialized))?;
1721                }
1722                Ok(())
1723            })
1724            .await;
1725        result
1726    }
1727
1728    fn get_marks(&self, workspace_id: WorkspaceId) -> Result<Vec<SerializedMark>> {
1729        let result: Vec<(Arc<Path>, String, String)> = self.select_bound(sql!(
1730            SELECT path, mark_name, value FROM vim_marks
1731                WHERE workspace_id = ?
1732        ))?(workspace_id)?;
1733
1734        Ok(result
1735            .into_iter()
1736            .filter_map(|(path, name, value)| {
1737                let pairs: Vec<(u32, u32)> = serde_json::from_str(&value).log_err()?;
1738                Some(SerializedMark {
1739                    path,
1740                    name,
1741                    points: pairs
1742                        .into_iter()
1743                        .map(|(row, column)| Point { row, column })
1744                        .collect(),
1745                })
1746            })
1747            .collect())
1748    }
1749
1750    pub(crate) async fn delete_mark(
1751        &self,
1752        workspace_id: WorkspaceId,
1753        path: Arc<Path>,
1754        mark_name: String,
1755    ) -> Result<()> {
1756        self.write(move |conn| {
1757            conn.exec_bound(sql!(
1758                DELETE FROM vim_marks
1759                WHERE workspace_id = ? AND mark_name = ? AND path = ?
1760            ))?((workspace_id, mark_name, path))
1761        })
1762        .await
1763    }
1764
1765    pub(crate) async fn set_global_mark_path(
1766        &self,
1767        workspace_id: WorkspaceId,
1768        mark_name: String,
1769        path: Arc<Path>,
1770    ) -> Result<()> {
1771        log::debug!("Setting global mark path {path:?} for {mark_name}");
1772        self.write(move |conn| {
1773            conn.exec_bound(sql!(
1774                INSERT OR REPLACE INTO vim_global_marks_paths
1775                    (workspace_id, mark_name, path)
1776                VALUES
1777                    (?, ?, ?)
1778            ))?((workspace_id, mark_name, path))
1779        })
1780        .await
1781    }
1782
1783    pub fn get_global_marks_paths(
1784        &self,
1785        workspace_id: WorkspaceId,
1786    ) -> Result<Vec<(String, Arc<Path>)>> {
1787        self.select_bound(sql!(
1788        SELECT mark_name, path FROM vim_global_marks_paths
1789            WHERE workspace_id = ?
1790        ))?(workspace_id)
1791    }
1792
1793    pub(crate) async fn delete_global_marks_path(
1794        &self,
1795        workspace_id: WorkspaceId,
1796        mark_name: String,
1797    ) -> Result<()> {
1798        self.write(move |conn| {
1799            conn.exec_bound(sql!(
1800                DELETE FROM vim_global_marks_paths
1801                WHERE workspace_id = ? AND mark_name = ?
1802            ))?((workspace_id, mark_name))
1803        })
1804        .await
1805    }
1806}