state.rs

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