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