editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blink_manager;
   17mod clangd_ext;
   18mod code_context_menus;
   19pub mod display_map;
   20mod editor_settings;
   21mod editor_settings_controls;
   22mod element;
   23mod git;
   24mod highlight_matching_bracket;
   25mod hover_links;
   26pub mod hover_popover;
   27mod indent_guides;
   28mod inlay_hint_cache;
   29pub mod items;
   30mod jsx_tag_auto_close;
   31mod linked_editing_ranges;
   32mod lsp_ext;
   33mod mouse_context_menu;
   34pub mod movement;
   35mod persistence;
   36mod proposed_changes_editor;
   37mod rust_analyzer_ext;
   38pub mod scroll;
   39mod selections_collection;
   40pub mod tasks;
   41
   42#[cfg(test)]
   43mod code_completion_tests;
   44#[cfg(test)]
   45mod editor_tests;
   46#[cfg(test)]
   47mod inline_completion_tests;
   48mod signature_help;
   49#[cfg(any(test, feature = "test-support"))]
   50pub mod test;
   51
   52pub(crate) use actions::*;
   53pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   54use aho_corasick::AhoCorasick;
   55use anyhow::{Context as _, Result, anyhow};
   56use blink_manager::BlinkManager;
   57use buffer_diff::DiffHunkStatus;
   58use client::{Collaborator, ParticipantIndex};
   59use clock::ReplicaId;
   60use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   61use convert_case::{Case, Casing};
   62use display_map::*;
   63pub use display_map::{ChunkRenderer, ChunkRendererContext, DisplayPoint, FoldPlaceholder};
   64use editor_settings::GoToDefinitionFallback;
   65pub use editor_settings::{
   66    CurrentLineHighlight, EditorSettings, HideMouseMode, ScrollBeyondLastLine, SearchSettings,
   67    ShowScrollbar,
   68};
   69pub use editor_settings_controls::*;
   70use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap, layout_line};
   71pub use element::{
   72    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   73};
   74use feature_flags::{Debugger, FeatureFlagAppExt};
   75use futures::{
   76    FutureExt,
   77    future::{self, Shared, join},
   78};
   79use fuzzy::StringMatchCandidate;
   80
   81use ::git::Restore;
   82use code_context_menus::{
   83    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   84    CompletionsMenu, ContextMenuOrigin,
   85};
   86use git::blame::{GitBlame, GlobalBlameRenderer};
   87use gpui::{
   88    Action, Animation, AnimationExt, AnyElement, AnyWeakEntity, App, AppContext,
   89    AsyncWindowContext, AvailableSpace, Background, Bounds, ClickEvent, ClipboardEntry,
   90    ClipboardItem, Context, DispatchPhase, Edges, Entity, EntityInputHandler, EventEmitter,
   91    FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global, HighlightStyle, Hsla,
   92    KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad, ParentElement, Pixels, Render,
   93    SharedString, Size, Stateful, Styled, Subscription, Task, TextStyle, TextStyleRefinement,
   94    UTF16Selection, UnderlineStyle, UniformListScrollHandle, WeakEntity, WeakFocusHandle, Window,
   95    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size,
   96};
   97use highlight_matching_bracket::refresh_matching_bracket_highlights;
   98use hover_links::{HoverLink, HoveredLinkState, InlayHighlight, find_file};
   99pub use hover_popover::hover_markdown_style;
  100use hover_popover::{HoverState, hide_hover};
  101use indent_guides::ActiveIndentGuidesState;
  102use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
  103pub use inline_completion::Direction;
  104use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
  105pub use items::MAX_TAB_TITLE_LEN;
  106use itertools::Itertools;
  107use language::{
  108    AutoindentMode, BracketMatch, BracketPair, Buffer, Capability, CharKind, CodeLabel,
  109    CursorShape, DiagnosticEntry, DiffOptions, EditPredictionsMode, EditPreview, HighlightedText,
  110    IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
  111    TransactionId, TreeSitterOptions, WordsQuery,
  112    language_settings::{
  113        self, InlayHintSettings, LspInsertMode, RewrapBehavior, WordsCompletionMode,
  114        all_language_settings, language_settings,
  115    },
  116    point_from_lsp, text_diff_with_options,
  117};
  118use language::{BufferRow, CharClassifier, Runnable, RunnableRange, point_to_lsp};
  119use linked_editing_ranges::refresh_linked_ranges;
  120use mouse_context_menu::MouseContextMenu;
  121use persistence::DB;
  122use project::{
  123    ProjectPath,
  124    debugger::breakpoint_store::{
  125        BreakpointEditAction, BreakpointState, BreakpointStore, BreakpointStoreEvent,
  126    },
  127};
  128
  129pub use git::blame::BlameRenderer;
  130pub use proposed_changes_editor::{
  131    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  132};
  133use smallvec::smallvec;
  134use std::{cell::OnceCell, iter::Peekable};
  135use task::{ResolvedTask, RunnableTag, TaskTemplate, TaskVariables};
  136
  137pub use lsp::CompletionContext;
  138use lsp::{
  139    CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
  140    InsertTextFormat, InsertTextMode, LanguageServerId, LanguageServerName,
  141};
  142
  143use language::BufferSnapshot;
  144pub use lsp_ext::lsp_tasks;
  145use movement::TextLayoutDetails;
  146pub use multi_buffer::{
  147    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, PathKey,
  148    RowInfo, ToOffset, ToPoint,
  149};
  150use multi_buffer::{
  151    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  152    MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
  153};
  154use parking_lot::Mutex;
  155use project::{
  156    CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
  157    Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
  158    TaskSourceKind,
  159    debugger::breakpoint_store::Breakpoint,
  160    lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  161    project_settings::{GitGutterSetting, ProjectSettings},
  162};
  163use rand::prelude::*;
  164use rpc::{ErrorExt, proto::*};
  165use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  166use selections_collection::{
  167    MutableSelectionsCollection, SelectionsCollection, resolve_selections,
  168};
  169use serde::{Deserialize, Serialize};
  170use settings::{Settings, SettingsLocation, SettingsStore, update_settings_file};
  171use smallvec::SmallVec;
  172use snippet::Snippet;
  173use std::sync::Arc;
  174use std::{
  175    any::TypeId,
  176    borrow::Cow,
  177    cell::RefCell,
  178    cmp::{self, Ordering, Reverse},
  179    mem,
  180    num::NonZeroU32,
  181    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  182    path::{Path, PathBuf},
  183    rc::Rc,
  184    time::{Duration, Instant},
  185};
  186pub use sum_tree::Bias;
  187use sum_tree::TreeMap;
  188use text::{BufferId, FromAnchor, OffsetUtf16, Rope};
  189use theme::{
  190    ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings,
  191    observe_buffer_font_size_adjustment,
  192};
  193use ui::{
  194    ButtonSize, ButtonStyle, ContextMenu, Disclosure, IconButton, IconButtonShape, IconName,
  195    IconSize, Key, Tooltip, h_flex, prelude::*,
  196};
  197use util::{RangeExt, ResultExt, TryFutureExt, maybe, post_inc};
  198use workspace::{
  199    Item as WorkspaceItem, ItemId, ItemNavHistory, OpenInTerminal, OpenTerminal,
  200    RestoreOnStartupBehavior, SERIALIZATION_THROTTLE_TIME, SplitDirection, TabBarSettings, Toast,
  201    ViewId, Workspace, WorkspaceId, WorkspaceSettings,
  202    item::{ItemHandle, PreviewTabsSettings},
  203    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  204    searchable::SearchEvent,
  205};
  206
  207use crate::hover_links::{find_url, find_url_from_range};
  208use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  209
  210pub const FILE_HEADER_HEIGHT: u32 = 2;
  211pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  212pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  213const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  214const MAX_LINE_LEN: usize = 1024;
  215const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  216const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  217pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  218#[doc(hidden)]
  219pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  220const SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(100);
  221
  222pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
  223pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
  224pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  225
  226pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  227pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  228pub(crate) const MIN_LINE_NUMBER_DIGITS: u32 = 4;
  229
  230pub type RenderDiffHunkControlsFn = Arc<
  231    dyn Fn(
  232        u32,
  233        &DiffHunkStatus,
  234        Range<Anchor>,
  235        bool,
  236        Pixels,
  237        &Entity<Editor>,
  238        &mut Window,
  239        &mut App,
  240    ) -> AnyElement,
  241>;
  242
  243const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  244    alt: true,
  245    shift: true,
  246    control: false,
  247    platform: false,
  248    function: false,
  249};
  250
  251#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  252pub enum InlayId {
  253    InlineCompletion(usize),
  254    Hint(usize),
  255}
  256
  257impl InlayId {
  258    fn id(&self) -> usize {
  259        match self {
  260            Self::InlineCompletion(id) => *id,
  261            Self::Hint(id) => *id,
  262        }
  263    }
  264}
  265
  266pub enum DebugCurrentRowHighlight {}
  267enum DocumentHighlightRead {}
  268enum DocumentHighlightWrite {}
  269enum InputComposition {}
  270enum SelectedTextHighlight {}
  271
  272pub enum ConflictsOuter {}
  273pub enum ConflictsOurs {}
  274pub enum ConflictsTheirs {}
  275pub enum ConflictsOursMarker {}
  276pub enum ConflictsTheirsMarker {}
  277
  278#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  279pub enum Navigated {
  280    Yes,
  281    No,
  282}
  283
  284impl Navigated {
  285    pub fn from_bool(yes: bool) -> Navigated {
  286        if yes { Navigated::Yes } else { Navigated::No }
  287    }
  288}
  289
  290#[derive(Debug, Clone, PartialEq, Eq)]
  291enum DisplayDiffHunk {
  292    Folded {
  293        display_row: DisplayRow,
  294    },
  295    Unfolded {
  296        is_created_file: bool,
  297        diff_base_byte_range: Range<usize>,
  298        display_row_range: Range<DisplayRow>,
  299        multi_buffer_range: Range<Anchor>,
  300        status: DiffHunkStatus,
  301    },
  302}
  303
  304pub enum HideMouseCursorOrigin {
  305    TypingAction,
  306    MovementAction,
  307}
  308
  309pub fn init_settings(cx: &mut App) {
  310    EditorSettings::register(cx);
  311}
  312
  313pub fn init(cx: &mut App) {
  314    init_settings(cx);
  315
  316    cx.set_global(GlobalBlameRenderer(Arc::new(())));
  317
  318    workspace::register_project_item::<Editor>(cx);
  319    workspace::FollowableViewRegistry::register::<Editor>(cx);
  320    workspace::register_serializable_item::<Editor>(cx);
  321
  322    cx.observe_new(
  323        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  324            workspace.register_action(Editor::new_file);
  325            workspace.register_action(Editor::new_file_vertical);
  326            workspace.register_action(Editor::new_file_horizontal);
  327            workspace.register_action(Editor::cancel_language_server_work);
  328        },
  329    )
  330    .detach();
  331
  332    cx.on_action(move |_: &workspace::NewFile, cx| {
  333        let app_state = workspace::AppState::global(cx);
  334        if let Some(app_state) = app_state.upgrade() {
  335            workspace::open_new(
  336                Default::default(),
  337                app_state,
  338                cx,
  339                |workspace, window, cx| {
  340                    Editor::new_file(workspace, &Default::default(), window, cx)
  341                },
  342            )
  343            .detach();
  344        }
  345    });
  346    cx.on_action(move |_: &workspace::NewWindow, cx| {
  347        let app_state = workspace::AppState::global(cx);
  348        if let Some(app_state) = app_state.upgrade() {
  349            workspace::open_new(
  350                Default::default(),
  351                app_state,
  352                cx,
  353                |workspace, window, cx| {
  354                    cx.activate(true);
  355                    Editor::new_file(workspace, &Default::default(), window, cx)
  356                },
  357            )
  358            .detach();
  359        }
  360    });
  361}
  362
  363pub fn set_blame_renderer(renderer: impl BlameRenderer + 'static, cx: &mut App) {
  364    cx.set_global(GlobalBlameRenderer(Arc::new(renderer)));
  365}
  366
  367pub trait DiagnosticRenderer {
  368    fn render_group(
  369        &self,
  370        diagnostic_group: Vec<DiagnosticEntry<Point>>,
  371        buffer_id: BufferId,
  372        snapshot: EditorSnapshot,
  373        editor: WeakEntity<Editor>,
  374        cx: &mut App,
  375    ) -> Vec<BlockProperties<Anchor>>;
  376}
  377
  378pub(crate) struct GlobalDiagnosticRenderer(pub Arc<dyn DiagnosticRenderer>);
  379
  380impl gpui::Global for GlobalDiagnosticRenderer {}
  381pub fn set_diagnostic_renderer(renderer: impl DiagnosticRenderer + 'static, cx: &mut App) {
  382    cx.set_global(GlobalDiagnosticRenderer(Arc::new(renderer)));
  383}
  384
  385pub struct SearchWithinRange;
  386
  387trait InvalidationRegion {
  388    fn ranges(&self) -> &[Range<Anchor>];
  389}
  390
  391#[derive(Clone, Debug, PartialEq)]
  392pub enum SelectPhase {
  393    Begin {
  394        position: DisplayPoint,
  395        add: bool,
  396        click_count: usize,
  397    },
  398    BeginColumnar {
  399        position: DisplayPoint,
  400        reset: bool,
  401        goal_column: u32,
  402    },
  403    Extend {
  404        position: DisplayPoint,
  405        click_count: usize,
  406    },
  407    Update {
  408        position: DisplayPoint,
  409        goal_column: u32,
  410        scroll_delta: gpui::Point<f32>,
  411    },
  412    End,
  413}
  414
  415#[derive(Clone, Debug)]
  416pub enum SelectMode {
  417    Character,
  418    Word(Range<Anchor>),
  419    Line(Range<Anchor>),
  420    All,
  421}
  422
  423#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  424pub enum EditorMode {
  425    SingleLine {
  426        auto_width: bool,
  427    },
  428    AutoHeight {
  429        max_lines: usize,
  430    },
  431    Full {
  432        /// When set to `true`, the editor will scale its UI elements with the buffer font size.
  433        scale_ui_elements_with_buffer_font_size: bool,
  434        /// When set to `true`, the editor will render a background for the active line.
  435        show_active_line_background: bool,
  436    },
  437}
  438
  439impl EditorMode {
  440    pub fn full() -> Self {
  441        Self::Full {
  442            scale_ui_elements_with_buffer_font_size: true,
  443            show_active_line_background: true,
  444        }
  445    }
  446
  447    pub fn is_full(&self) -> bool {
  448        matches!(self, Self::Full { .. })
  449    }
  450}
  451
  452#[derive(Copy, Clone, Debug)]
  453pub enum SoftWrap {
  454    /// Prefer not to wrap at all.
  455    ///
  456    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  457    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  458    GitDiff,
  459    /// Prefer a single line generally, unless an overly long line is encountered.
  460    None,
  461    /// Soft wrap lines that exceed the editor width.
  462    EditorWidth,
  463    /// Soft wrap lines at the preferred line length.
  464    Column(u32),
  465    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  466    Bounded(u32),
  467}
  468
  469#[derive(Clone)]
  470pub struct EditorStyle {
  471    pub background: Hsla,
  472    pub local_player: PlayerColor,
  473    pub text: TextStyle,
  474    pub scrollbar_width: Pixels,
  475    pub syntax: Arc<SyntaxTheme>,
  476    pub status: StatusColors,
  477    pub inlay_hints_style: HighlightStyle,
  478    pub inline_completion_styles: InlineCompletionStyles,
  479    pub unnecessary_code_fade: f32,
  480}
  481
  482impl Default for EditorStyle {
  483    fn default() -> Self {
  484        Self {
  485            background: Hsla::default(),
  486            local_player: PlayerColor::default(),
  487            text: TextStyle::default(),
  488            scrollbar_width: Pixels::default(),
  489            syntax: Default::default(),
  490            // HACK: Status colors don't have a real default.
  491            // We should look into removing the status colors from the editor
  492            // style and retrieve them directly from the theme.
  493            status: StatusColors::dark(),
  494            inlay_hints_style: HighlightStyle::default(),
  495            inline_completion_styles: InlineCompletionStyles {
  496                insertion: HighlightStyle::default(),
  497                whitespace: HighlightStyle::default(),
  498            },
  499            unnecessary_code_fade: Default::default(),
  500        }
  501    }
  502}
  503
  504pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  505    let show_background = language_settings::language_settings(None, None, cx)
  506        .inlay_hints
  507        .show_background;
  508
  509    HighlightStyle {
  510        color: Some(cx.theme().status().hint),
  511        background_color: show_background.then(|| cx.theme().status().hint_background),
  512        ..HighlightStyle::default()
  513    }
  514}
  515
  516pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  517    InlineCompletionStyles {
  518        insertion: HighlightStyle {
  519            color: Some(cx.theme().status().predictive),
  520            ..HighlightStyle::default()
  521        },
  522        whitespace: HighlightStyle {
  523            background_color: Some(cx.theme().status().created_background),
  524            ..HighlightStyle::default()
  525        },
  526    }
  527}
  528
  529type CompletionId = usize;
  530
  531pub(crate) enum EditDisplayMode {
  532    TabAccept,
  533    DiffPopover,
  534    Inline,
  535}
  536
  537enum InlineCompletion {
  538    Edit {
  539        edits: Vec<(Range<Anchor>, String)>,
  540        edit_preview: Option<EditPreview>,
  541        display_mode: EditDisplayMode,
  542        snapshot: BufferSnapshot,
  543    },
  544    Move {
  545        target: Anchor,
  546        snapshot: BufferSnapshot,
  547    },
  548}
  549
  550struct InlineCompletionState {
  551    inlay_ids: Vec<InlayId>,
  552    completion: InlineCompletion,
  553    completion_id: Option<SharedString>,
  554    invalidation_range: Range<Anchor>,
  555}
  556
  557enum EditPredictionSettings {
  558    Disabled,
  559    Enabled {
  560        show_in_menu: bool,
  561        preview_requires_modifier: bool,
  562    },
  563}
  564
  565enum InlineCompletionHighlight {}
  566
  567#[derive(Debug, Clone)]
  568struct InlineDiagnostic {
  569    message: SharedString,
  570    group_id: usize,
  571    is_primary: bool,
  572    start: Point,
  573    severity: DiagnosticSeverity,
  574}
  575
  576pub enum MenuInlineCompletionsPolicy {
  577    Never,
  578    ByProvider,
  579}
  580
  581pub enum EditPredictionPreview {
  582    /// Modifier is not pressed
  583    Inactive { released_too_fast: bool },
  584    /// Modifier pressed
  585    Active {
  586        since: Instant,
  587        previous_scroll_position: Option<ScrollAnchor>,
  588    },
  589}
  590
  591impl EditPredictionPreview {
  592    pub fn released_too_fast(&self) -> bool {
  593        match self {
  594            EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
  595            EditPredictionPreview::Active { .. } => false,
  596        }
  597    }
  598
  599    pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
  600        if let EditPredictionPreview::Active {
  601            previous_scroll_position,
  602            ..
  603        } = self
  604        {
  605            *previous_scroll_position = scroll_position;
  606        }
  607    }
  608}
  609
  610pub struct ContextMenuOptions {
  611    pub min_entries_visible: usize,
  612    pub max_entries_visible: usize,
  613    pub placement: Option<ContextMenuPlacement>,
  614}
  615
  616#[derive(Debug, Clone, PartialEq, Eq)]
  617pub enum ContextMenuPlacement {
  618    Above,
  619    Below,
  620}
  621
  622#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  623struct EditorActionId(usize);
  624
  625impl EditorActionId {
  626    pub fn post_inc(&mut self) -> Self {
  627        let answer = self.0;
  628
  629        *self = Self(answer + 1);
  630
  631        Self(answer)
  632    }
  633}
  634
  635// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  636// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  637
  638type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  639type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  640
  641#[derive(Default)]
  642struct ScrollbarMarkerState {
  643    scrollbar_size: Size<Pixels>,
  644    dirty: bool,
  645    markers: Arc<[PaintQuad]>,
  646    pending_refresh: Option<Task<Result<()>>>,
  647}
  648
  649impl ScrollbarMarkerState {
  650    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  651        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  652    }
  653}
  654
  655#[derive(Clone, Debug)]
  656struct RunnableTasks {
  657    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  658    offset: multi_buffer::Anchor,
  659    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  660    column: u32,
  661    // Values of all named captures, including those starting with '_'
  662    extra_variables: HashMap<String, String>,
  663    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  664    context_range: Range<BufferOffset>,
  665}
  666
  667impl RunnableTasks {
  668    fn resolve<'a>(
  669        &'a self,
  670        cx: &'a task::TaskContext,
  671    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  672        self.templates.iter().filter_map(|(kind, template)| {
  673            template
  674                .resolve_task(&kind.to_id_base(), cx)
  675                .map(|task| (kind.clone(), task))
  676        })
  677    }
  678}
  679
  680#[derive(Clone)]
  681struct ResolvedTasks {
  682    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  683    position: Anchor,
  684}
  685
  686#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  687struct BufferOffset(usize);
  688
  689// Addons allow storing per-editor state in other crates (e.g. Vim)
  690pub trait Addon: 'static {
  691    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  692
  693    fn render_buffer_header_controls(
  694        &self,
  695        _: &ExcerptInfo,
  696        _: &Window,
  697        _: &App,
  698    ) -> Option<AnyElement> {
  699        None
  700    }
  701
  702    fn to_any(&self) -> &dyn std::any::Any;
  703
  704    fn to_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
  705        None
  706    }
  707}
  708
  709/// A set of caret positions, registered when the editor was edited.
  710pub struct ChangeList {
  711    changes: Vec<Vec<Anchor>>,
  712    /// Currently "selected" change.
  713    position: Option<usize>,
  714}
  715
  716impl ChangeList {
  717    pub fn new() -> Self {
  718        Self {
  719            changes: Vec::new(),
  720            position: None,
  721        }
  722    }
  723
  724    /// Moves to the next change in the list (based on the direction given) and returns the caret positions for the next change.
  725    /// If reaches the end of the list in the direction, returns the corresponding change until called for a different direction.
  726    pub fn next_change(&mut self, count: usize, direction: Direction) -> Option<&[Anchor]> {
  727        if self.changes.is_empty() {
  728            return None;
  729        }
  730
  731        let prev = self.position.unwrap_or(self.changes.len());
  732        let next = if direction == Direction::Prev {
  733            prev.saturating_sub(count)
  734        } else {
  735            (prev + count).min(self.changes.len() - 1)
  736        };
  737        self.position = Some(next);
  738        self.changes.get(next).map(|anchors| anchors.as_slice())
  739    }
  740
  741    /// Adds a new change to the list, resetting the change list position.
  742    pub fn push_to_change_list(&mut self, pop_state: bool, new_positions: Vec<Anchor>) {
  743        self.position.take();
  744        if pop_state {
  745            self.changes.pop();
  746        }
  747        self.changes.push(new_positions.clone());
  748    }
  749
  750    pub fn last(&self) -> Option<&[Anchor]> {
  751        self.changes.last().map(|anchors| anchors.as_slice())
  752    }
  753}
  754
  755/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  756///
  757/// See the [module level documentation](self) for more information.
  758pub struct Editor {
  759    focus_handle: FocusHandle,
  760    last_focused_descendant: Option<WeakFocusHandle>,
  761    /// The text buffer being edited
  762    buffer: Entity<MultiBuffer>,
  763    /// Map of how text in the buffer should be displayed.
  764    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  765    pub display_map: Entity<DisplayMap>,
  766    pub selections: SelectionsCollection,
  767    pub scroll_manager: ScrollManager,
  768    /// When inline assist editors are linked, they all render cursors because
  769    /// typing enters text into each of them, even the ones that aren't focused.
  770    pub(crate) show_cursor_when_unfocused: bool,
  771    columnar_selection_tail: Option<Anchor>,
  772    add_selections_state: Option<AddSelectionsState>,
  773    select_next_state: Option<SelectNextState>,
  774    select_prev_state: Option<SelectNextState>,
  775    selection_history: SelectionHistory,
  776    autoclose_regions: Vec<AutocloseRegion>,
  777    snippet_stack: InvalidationStack<SnippetState>,
  778    select_syntax_node_history: SelectSyntaxNodeHistory,
  779    ime_transaction: Option<TransactionId>,
  780    active_diagnostics: ActiveDiagnostic,
  781    show_inline_diagnostics: bool,
  782    inline_diagnostics_update: Task<()>,
  783    inline_diagnostics_enabled: bool,
  784    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  785    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  786    hard_wrap: Option<usize>,
  787
  788    // TODO: make this a access method
  789    pub project: Option<Entity<Project>>,
  790    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  791    completion_provider: Option<Box<dyn CompletionProvider>>,
  792    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  793    blink_manager: Entity<BlinkManager>,
  794    show_cursor_names: bool,
  795    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  796    pub show_local_selections: bool,
  797    mode: EditorMode,
  798    show_breadcrumbs: bool,
  799    show_gutter: bool,
  800    show_scrollbars: bool,
  801    show_line_numbers: Option<bool>,
  802    use_relative_line_numbers: Option<bool>,
  803    show_git_diff_gutter: Option<bool>,
  804    show_code_actions: Option<bool>,
  805    show_runnables: Option<bool>,
  806    show_breakpoints: Option<bool>,
  807    show_wrap_guides: Option<bool>,
  808    show_indent_guides: Option<bool>,
  809    placeholder_text: Option<Arc<str>>,
  810    highlight_order: usize,
  811    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  812    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  813    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  814    scrollbar_marker_state: ScrollbarMarkerState,
  815    active_indent_guides_state: ActiveIndentGuidesState,
  816    nav_history: Option<ItemNavHistory>,
  817    context_menu: RefCell<Option<CodeContextMenu>>,
  818    context_menu_options: Option<ContextMenuOptions>,
  819    mouse_context_menu: Option<MouseContextMenu>,
  820    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  821    signature_help_state: SignatureHelpState,
  822    auto_signature_help: Option<bool>,
  823    find_all_references_task_sources: Vec<Anchor>,
  824    next_completion_id: CompletionId,
  825    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  826    code_actions_task: Option<Task<Result<()>>>,
  827    quick_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
  828    debounced_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
  829    document_highlights_task: Option<Task<()>>,
  830    linked_editing_range_task: Option<Task<Option<()>>>,
  831    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  832    pending_rename: Option<RenameState>,
  833    searchable: bool,
  834    cursor_shape: CursorShape,
  835    current_line_highlight: Option<CurrentLineHighlight>,
  836    collapse_matches: bool,
  837    autoindent_mode: Option<AutoindentMode>,
  838    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  839    input_enabled: bool,
  840    use_modal_editing: bool,
  841    read_only: bool,
  842    leader_peer_id: Option<PeerId>,
  843    remote_id: Option<ViewId>,
  844    hover_state: HoverState,
  845    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  846    gutter_hovered: bool,
  847    hovered_link_state: Option<HoveredLinkState>,
  848    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  849    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  850    active_inline_completion: Option<InlineCompletionState>,
  851    /// Used to prevent flickering as the user types while the menu is open
  852    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  853    edit_prediction_settings: EditPredictionSettings,
  854    inline_completions_hidden_for_vim_mode: bool,
  855    show_inline_completions_override: Option<bool>,
  856    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  857    edit_prediction_preview: EditPredictionPreview,
  858    edit_prediction_indent_conflict: bool,
  859    edit_prediction_requires_modifier_in_indent_conflict: bool,
  860    inlay_hint_cache: InlayHintCache,
  861    next_inlay_id: usize,
  862    _subscriptions: Vec<Subscription>,
  863    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  864    gutter_dimensions: GutterDimensions,
  865    style: Option<EditorStyle>,
  866    text_style_refinement: Option<TextStyleRefinement>,
  867    next_editor_action_id: EditorActionId,
  868    editor_actions:
  869        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  870    use_autoclose: bool,
  871    use_auto_surround: bool,
  872    auto_replace_emoji_shortcode: bool,
  873    jsx_tag_auto_close_enabled_in_any_buffer: bool,
  874    show_git_blame_gutter: bool,
  875    show_git_blame_inline: bool,
  876    show_git_blame_inline_delay_task: Option<Task<()>>,
  877    pub git_blame_inline_tooltip: Option<AnyWeakEntity>,
  878    git_blame_inline_enabled: bool,
  879    render_diff_hunk_controls: RenderDiffHunkControlsFn,
  880    serialize_dirty_buffers: bool,
  881    show_selection_menu: Option<bool>,
  882    blame: Option<Entity<GitBlame>>,
  883    blame_subscription: Option<Subscription>,
  884    custom_context_menu: Option<
  885        Box<
  886            dyn 'static
  887                + Fn(
  888                    &mut Self,
  889                    DisplayPoint,
  890                    &mut Window,
  891                    &mut Context<Self>,
  892                ) -> Option<Entity<ui::ContextMenu>>,
  893        >,
  894    >,
  895    last_bounds: Option<Bounds<Pixels>>,
  896    last_position_map: Option<Rc<PositionMap>>,
  897    expect_bounds_change: Option<Bounds<Pixels>>,
  898    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  899    tasks_update_task: Option<Task<()>>,
  900    breakpoint_store: Option<Entity<BreakpointStore>>,
  901    /// Allow's a user to create a breakpoint by selecting this indicator
  902    /// It should be None while a user is not hovering over the gutter
  903    /// Otherwise it represents the point that the breakpoint will be shown
  904    gutter_breakpoint_indicator: (Option<(DisplayPoint, bool)>, Option<Task<()>>),
  905    in_project_search: bool,
  906    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  907    breadcrumb_header: Option<String>,
  908    focused_block: Option<FocusedBlock>,
  909    next_scroll_position: NextScrollCursorCenterTopBottom,
  910    addons: HashMap<TypeId, Box<dyn Addon>>,
  911    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  912    load_diff_task: Option<Shared<Task<()>>>,
  913    selection_mark_mode: bool,
  914    toggle_fold_multiple_buffers: Task<()>,
  915    _scroll_cursor_center_top_bottom_task: Task<()>,
  916    serialize_selections: Task<()>,
  917    serialize_folds: Task<()>,
  918    mouse_cursor_hidden: bool,
  919    hide_mouse_mode: HideMouseMode,
  920    pub change_list: ChangeList,
  921}
  922
  923#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  924enum NextScrollCursorCenterTopBottom {
  925    #[default]
  926    Center,
  927    Top,
  928    Bottom,
  929}
  930
  931impl NextScrollCursorCenterTopBottom {
  932    fn next(&self) -> Self {
  933        match self {
  934            Self::Center => Self::Top,
  935            Self::Top => Self::Bottom,
  936            Self::Bottom => Self::Center,
  937        }
  938    }
  939}
  940
  941#[derive(Clone)]
  942pub struct EditorSnapshot {
  943    pub mode: EditorMode,
  944    show_gutter: bool,
  945    show_line_numbers: Option<bool>,
  946    show_git_diff_gutter: Option<bool>,
  947    show_code_actions: Option<bool>,
  948    show_runnables: Option<bool>,
  949    show_breakpoints: Option<bool>,
  950    git_blame_gutter_max_author_length: Option<usize>,
  951    pub display_snapshot: DisplaySnapshot,
  952    pub placeholder_text: Option<Arc<str>>,
  953    is_focused: bool,
  954    scroll_anchor: ScrollAnchor,
  955    ongoing_scroll: OngoingScroll,
  956    current_line_highlight: CurrentLineHighlight,
  957    gutter_hovered: bool,
  958}
  959
  960#[derive(Default, Debug, Clone, Copy)]
  961pub struct GutterDimensions {
  962    pub left_padding: Pixels,
  963    pub right_padding: Pixels,
  964    pub width: Pixels,
  965    pub margin: Pixels,
  966    pub git_blame_entries_width: Option<Pixels>,
  967}
  968
  969impl GutterDimensions {
  970    /// The full width of the space taken up by the gutter.
  971    pub fn full_width(&self) -> Pixels {
  972        self.margin + self.width
  973    }
  974
  975    /// The width of the space reserved for the fold indicators,
  976    /// use alongside 'justify_end' and `gutter_width` to
  977    /// right align content with the line numbers
  978    pub fn fold_area_width(&self) -> Pixels {
  979        self.margin + self.right_padding
  980    }
  981}
  982
  983#[derive(Debug)]
  984pub struct RemoteSelection {
  985    pub replica_id: ReplicaId,
  986    pub selection: Selection<Anchor>,
  987    pub cursor_shape: CursorShape,
  988    pub peer_id: PeerId,
  989    pub line_mode: bool,
  990    pub participant_index: Option<ParticipantIndex>,
  991    pub user_name: Option<SharedString>,
  992}
  993
  994#[derive(Clone, Debug)]
  995struct SelectionHistoryEntry {
  996    selections: Arc<[Selection<Anchor>]>,
  997    select_next_state: Option<SelectNextState>,
  998    select_prev_state: Option<SelectNextState>,
  999    add_selections_state: Option<AddSelectionsState>,
 1000}
 1001
 1002enum SelectionHistoryMode {
 1003    Normal,
 1004    Undoing,
 1005    Redoing,
 1006}
 1007
 1008#[derive(Clone, PartialEq, Eq, Hash)]
 1009struct HoveredCursor {
 1010    replica_id: u16,
 1011    selection_id: usize,
 1012}
 1013
 1014impl Default for SelectionHistoryMode {
 1015    fn default() -> Self {
 1016        Self::Normal
 1017    }
 1018}
 1019
 1020#[derive(Default)]
 1021struct SelectionHistory {
 1022    #[allow(clippy::type_complexity)]
 1023    selections_by_transaction:
 1024        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
 1025    mode: SelectionHistoryMode,
 1026    undo_stack: VecDeque<SelectionHistoryEntry>,
 1027    redo_stack: VecDeque<SelectionHistoryEntry>,
 1028}
 1029
 1030impl SelectionHistory {
 1031    fn insert_transaction(
 1032        &mut self,
 1033        transaction_id: TransactionId,
 1034        selections: Arc<[Selection<Anchor>]>,
 1035    ) {
 1036        self.selections_by_transaction
 1037            .insert(transaction_id, (selections, None));
 1038    }
 1039
 1040    #[allow(clippy::type_complexity)]
 1041    fn transaction(
 1042        &self,
 1043        transaction_id: TransactionId,
 1044    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
 1045        self.selections_by_transaction.get(&transaction_id)
 1046    }
 1047
 1048    #[allow(clippy::type_complexity)]
 1049    fn transaction_mut(
 1050        &mut self,
 1051        transaction_id: TransactionId,
 1052    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
 1053        self.selections_by_transaction.get_mut(&transaction_id)
 1054    }
 1055
 1056    fn push(&mut self, entry: SelectionHistoryEntry) {
 1057        if !entry.selections.is_empty() {
 1058            match self.mode {
 1059                SelectionHistoryMode::Normal => {
 1060                    self.push_undo(entry);
 1061                    self.redo_stack.clear();
 1062                }
 1063                SelectionHistoryMode::Undoing => self.push_redo(entry),
 1064                SelectionHistoryMode::Redoing => self.push_undo(entry),
 1065            }
 1066        }
 1067    }
 1068
 1069    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
 1070        if self
 1071            .undo_stack
 1072            .back()
 1073            .map_or(true, |e| e.selections != entry.selections)
 1074        {
 1075            self.undo_stack.push_back(entry);
 1076            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 1077                self.undo_stack.pop_front();
 1078            }
 1079        }
 1080    }
 1081
 1082    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
 1083        if self
 1084            .redo_stack
 1085            .back()
 1086            .map_or(true, |e| e.selections != entry.selections)
 1087        {
 1088            self.redo_stack.push_back(entry);
 1089            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 1090                self.redo_stack.pop_front();
 1091            }
 1092        }
 1093    }
 1094}
 1095
 1096#[derive(Clone, Copy)]
 1097pub struct RowHighlightOptions {
 1098    pub autoscroll: bool,
 1099    pub include_gutter: bool,
 1100}
 1101
 1102impl Default for RowHighlightOptions {
 1103    fn default() -> Self {
 1104        Self {
 1105            autoscroll: Default::default(),
 1106            include_gutter: true,
 1107        }
 1108    }
 1109}
 1110
 1111struct RowHighlight {
 1112    index: usize,
 1113    range: Range<Anchor>,
 1114    color: Hsla,
 1115    options: RowHighlightOptions,
 1116    type_id: TypeId,
 1117}
 1118
 1119#[derive(Clone, Debug)]
 1120struct AddSelectionsState {
 1121    above: bool,
 1122    stack: Vec<usize>,
 1123}
 1124
 1125#[derive(Clone)]
 1126struct SelectNextState {
 1127    query: AhoCorasick,
 1128    wordwise: bool,
 1129    done: bool,
 1130}
 1131
 1132impl std::fmt::Debug for SelectNextState {
 1133    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 1134        f.debug_struct(std::any::type_name::<Self>())
 1135            .field("wordwise", &self.wordwise)
 1136            .field("done", &self.done)
 1137            .finish()
 1138    }
 1139}
 1140
 1141#[derive(Debug)]
 1142struct AutocloseRegion {
 1143    selection_id: usize,
 1144    range: Range<Anchor>,
 1145    pair: BracketPair,
 1146}
 1147
 1148#[derive(Debug)]
 1149struct SnippetState {
 1150    ranges: Vec<Vec<Range<Anchor>>>,
 1151    active_index: usize,
 1152    choices: Vec<Option<Vec<String>>>,
 1153}
 1154
 1155#[doc(hidden)]
 1156pub struct RenameState {
 1157    pub range: Range<Anchor>,
 1158    pub old_name: Arc<str>,
 1159    pub editor: Entity<Editor>,
 1160    block_id: CustomBlockId,
 1161}
 1162
 1163struct InvalidationStack<T>(Vec<T>);
 1164
 1165struct RegisteredInlineCompletionProvider {
 1166    provider: Arc<dyn InlineCompletionProviderHandle>,
 1167    _subscription: Subscription,
 1168}
 1169
 1170#[derive(Debug, PartialEq, Eq)]
 1171pub struct ActiveDiagnosticGroup {
 1172    pub active_range: Range<Anchor>,
 1173    pub active_message: String,
 1174    pub group_id: usize,
 1175    pub blocks: HashSet<CustomBlockId>,
 1176}
 1177
 1178#[derive(Debug, PartialEq, Eq)]
 1179#[allow(clippy::large_enum_variant)]
 1180pub(crate) enum ActiveDiagnostic {
 1181    None,
 1182    All,
 1183    Group(ActiveDiagnosticGroup),
 1184}
 1185
 1186#[derive(Serialize, Deserialize, Clone, Debug)]
 1187pub struct ClipboardSelection {
 1188    /// The number of bytes in this selection.
 1189    pub len: usize,
 1190    /// Whether this was a full-line selection.
 1191    pub is_entire_line: bool,
 1192    /// The indentation of the first line when this content was originally copied.
 1193    pub first_line_indent: u32,
 1194}
 1195
 1196// selections, scroll behavior, was newest selection reversed
 1197type SelectSyntaxNodeHistoryState = (
 1198    Box<[Selection<usize>]>,
 1199    SelectSyntaxNodeScrollBehavior,
 1200    bool,
 1201);
 1202
 1203#[derive(Default)]
 1204struct SelectSyntaxNodeHistory {
 1205    stack: Vec<SelectSyntaxNodeHistoryState>,
 1206    // disable temporarily to allow changing selections without losing the stack
 1207    pub disable_clearing: bool,
 1208}
 1209
 1210impl SelectSyntaxNodeHistory {
 1211    pub fn try_clear(&mut self) {
 1212        if !self.disable_clearing {
 1213            self.stack.clear();
 1214        }
 1215    }
 1216
 1217    pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
 1218        self.stack.push(selection);
 1219    }
 1220
 1221    pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
 1222        self.stack.pop()
 1223    }
 1224}
 1225
 1226enum SelectSyntaxNodeScrollBehavior {
 1227    CursorTop,
 1228    FitSelection,
 1229    CursorBottom,
 1230}
 1231
 1232#[derive(Debug)]
 1233pub(crate) struct NavigationData {
 1234    cursor_anchor: Anchor,
 1235    cursor_position: Point,
 1236    scroll_anchor: ScrollAnchor,
 1237    scroll_top_row: u32,
 1238}
 1239
 1240#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1241pub enum GotoDefinitionKind {
 1242    Symbol,
 1243    Declaration,
 1244    Type,
 1245    Implementation,
 1246}
 1247
 1248#[derive(Debug, Clone)]
 1249enum InlayHintRefreshReason {
 1250    ModifiersChanged(bool),
 1251    Toggle(bool),
 1252    SettingsChange(InlayHintSettings),
 1253    NewLinesShown,
 1254    BufferEdited(HashSet<Arc<Language>>),
 1255    RefreshRequested,
 1256    ExcerptsRemoved(Vec<ExcerptId>),
 1257}
 1258
 1259impl InlayHintRefreshReason {
 1260    fn description(&self) -> &'static str {
 1261        match self {
 1262            Self::ModifiersChanged(_) => "modifiers changed",
 1263            Self::Toggle(_) => "toggle",
 1264            Self::SettingsChange(_) => "settings change",
 1265            Self::NewLinesShown => "new lines shown",
 1266            Self::BufferEdited(_) => "buffer edited",
 1267            Self::RefreshRequested => "refresh requested",
 1268            Self::ExcerptsRemoved(_) => "excerpts removed",
 1269        }
 1270    }
 1271}
 1272
 1273pub enum FormatTarget {
 1274    Buffers,
 1275    Ranges(Vec<Range<MultiBufferPoint>>),
 1276}
 1277
 1278pub(crate) struct FocusedBlock {
 1279    id: BlockId,
 1280    focus_handle: WeakFocusHandle,
 1281}
 1282
 1283#[derive(Clone)]
 1284enum JumpData {
 1285    MultiBufferRow {
 1286        row: MultiBufferRow,
 1287        line_offset_from_top: u32,
 1288    },
 1289    MultiBufferPoint {
 1290        excerpt_id: ExcerptId,
 1291        position: Point,
 1292        anchor: text::Anchor,
 1293        line_offset_from_top: u32,
 1294    },
 1295}
 1296
 1297pub enum MultibufferSelectionMode {
 1298    First,
 1299    All,
 1300}
 1301
 1302#[derive(Clone, Copy, Debug, Default)]
 1303pub struct RewrapOptions {
 1304    pub override_language_settings: bool,
 1305    pub preserve_existing_whitespace: bool,
 1306}
 1307
 1308impl Editor {
 1309    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1310        let buffer = cx.new(|cx| Buffer::local("", cx));
 1311        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1312        Self::new(
 1313            EditorMode::SingleLine { auto_width: false },
 1314            buffer,
 1315            None,
 1316            window,
 1317            cx,
 1318        )
 1319    }
 1320
 1321    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1322        let buffer = cx.new(|cx| Buffer::local("", cx));
 1323        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1324        Self::new(EditorMode::full(), buffer, None, window, cx)
 1325    }
 1326
 1327    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1328        let buffer = cx.new(|cx| Buffer::local("", cx));
 1329        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1330        Self::new(
 1331            EditorMode::SingleLine { auto_width: true },
 1332            buffer,
 1333            None,
 1334            window,
 1335            cx,
 1336        )
 1337    }
 1338
 1339    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1340        let buffer = cx.new(|cx| Buffer::local("", cx));
 1341        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1342        Self::new(
 1343            EditorMode::AutoHeight { max_lines },
 1344            buffer,
 1345            None,
 1346            window,
 1347            cx,
 1348        )
 1349    }
 1350
 1351    pub fn for_buffer(
 1352        buffer: Entity<Buffer>,
 1353        project: Option<Entity<Project>>,
 1354        window: &mut Window,
 1355        cx: &mut Context<Self>,
 1356    ) -> Self {
 1357        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1358        Self::new(EditorMode::full(), buffer, project, window, cx)
 1359    }
 1360
 1361    pub fn for_multibuffer(
 1362        buffer: Entity<MultiBuffer>,
 1363        project: Option<Entity<Project>>,
 1364        window: &mut Window,
 1365        cx: &mut Context<Self>,
 1366    ) -> Self {
 1367        Self::new(EditorMode::full(), buffer, project, window, cx)
 1368    }
 1369
 1370    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1371        let mut clone = Self::new(
 1372            self.mode,
 1373            self.buffer.clone(),
 1374            self.project.clone(),
 1375            window,
 1376            cx,
 1377        );
 1378        self.display_map.update(cx, |display_map, cx| {
 1379            let snapshot = display_map.snapshot(cx);
 1380            clone.display_map.update(cx, |display_map, cx| {
 1381                display_map.set_state(&snapshot, cx);
 1382            });
 1383        });
 1384        clone.folds_did_change(cx);
 1385        clone.selections.clone_state(&self.selections);
 1386        clone.scroll_manager.clone_state(&self.scroll_manager);
 1387        clone.searchable = self.searchable;
 1388        clone.read_only = self.read_only;
 1389        clone
 1390    }
 1391
 1392    pub fn new(
 1393        mode: EditorMode,
 1394        buffer: Entity<MultiBuffer>,
 1395        project: Option<Entity<Project>>,
 1396        window: &mut Window,
 1397        cx: &mut Context<Self>,
 1398    ) -> Self {
 1399        let style = window.text_style();
 1400        let font_size = style.font_size.to_pixels(window.rem_size());
 1401        let editor = cx.entity().downgrade();
 1402        let fold_placeholder = FoldPlaceholder {
 1403            constrain_width: true,
 1404            render: Arc::new(move |fold_id, fold_range, cx| {
 1405                let editor = editor.clone();
 1406                div()
 1407                    .id(fold_id)
 1408                    .bg(cx.theme().colors().ghost_element_background)
 1409                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1410                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1411                    .rounded_xs()
 1412                    .size_full()
 1413                    .cursor_pointer()
 1414                    .child("")
 1415                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1416                    .on_click(move |_, _window, cx| {
 1417                        editor
 1418                            .update(cx, |editor, cx| {
 1419                                editor.unfold_ranges(
 1420                                    &[fold_range.start..fold_range.end],
 1421                                    true,
 1422                                    false,
 1423                                    cx,
 1424                                );
 1425                                cx.stop_propagation();
 1426                            })
 1427                            .ok();
 1428                    })
 1429                    .into_any()
 1430            }),
 1431            merge_adjacent: true,
 1432            ..Default::default()
 1433        };
 1434        let display_map = cx.new(|cx| {
 1435            DisplayMap::new(
 1436                buffer.clone(),
 1437                style.font(),
 1438                font_size,
 1439                None,
 1440                FILE_HEADER_HEIGHT,
 1441                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1442                fold_placeholder,
 1443                cx,
 1444            )
 1445        });
 1446
 1447        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1448
 1449        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1450
 1451        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1452            .then(|| language_settings::SoftWrap::None);
 1453
 1454        let mut project_subscriptions = Vec::new();
 1455        if mode.is_full() {
 1456            if let Some(project) = project.as_ref() {
 1457                project_subscriptions.push(cx.subscribe_in(
 1458                    project,
 1459                    window,
 1460                    |editor, _, event, window, cx| match event {
 1461                        project::Event::RefreshCodeLens => {
 1462                            // we always query lens with actions, without storing them, always refreshing them
 1463                        }
 1464                        project::Event::RefreshInlayHints => {
 1465                            editor
 1466                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1467                        }
 1468                        project::Event::SnippetEdit(id, snippet_edits) => {
 1469                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1470                                let focus_handle = editor.focus_handle(cx);
 1471                                if focus_handle.is_focused(window) {
 1472                                    let snapshot = buffer.read(cx).snapshot();
 1473                                    for (range, snippet) in snippet_edits {
 1474                                        let editor_range =
 1475                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1476                                        editor
 1477                                            .insert_snippet(
 1478                                                &[editor_range],
 1479                                                snippet.clone(),
 1480                                                window,
 1481                                                cx,
 1482                                            )
 1483                                            .ok();
 1484                                    }
 1485                                }
 1486                            }
 1487                        }
 1488                        _ => {}
 1489                    },
 1490                ));
 1491                if let Some(task_inventory) = project
 1492                    .read(cx)
 1493                    .task_store()
 1494                    .read(cx)
 1495                    .task_inventory()
 1496                    .cloned()
 1497                {
 1498                    project_subscriptions.push(cx.observe_in(
 1499                        &task_inventory,
 1500                        window,
 1501                        |editor, _, window, cx| {
 1502                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1503                        },
 1504                    ));
 1505                };
 1506
 1507                project_subscriptions.push(cx.subscribe_in(
 1508                    &project.read(cx).breakpoint_store(),
 1509                    window,
 1510                    |editor, _, event, window, cx| match event {
 1511                        BreakpointStoreEvent::ActiveDebugLineChanged => {
 1512                            if editor.go_to_active_debug_line(window, cx) {
 1513                                cx.stop_propagation();
 1514                            }
 1515                        }
 1516                        _ => {}
 1517                    },
 1518                ));
 1519            }
 1520        }
 1521
 1522        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1523
 1524        let inlay_hint_settings =
 1525            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1526        let focus_handle = cx.focus_handle();
 1527        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1528            .detach();
 1529        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1530            .detach();
 1531        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1532            .detach();
 1533        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1534            .detach();
 1535
 1536        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1537            Some(false)
 1538        } else {
 1539            None
 1540        };
 1541
 1542        let breakpoint_store = match (mode, project.as_ref()) {
 1543            (EditorMode::Full { .. }, Some(project)) => Some(project.read(cx).breakpoint_store()),
 1544            _ => None,
 1545        };
 1546
 1547        let mut code_action_providers = Vec::new();
 1548        let mut load_uncommitted_diff = None;
 1549        if let Some(project) = project.clone() {
 1550            load_uncommitted_diff = Some(
 1551                get_uncommitted_diff_for_buffer(
 1552                    &project,
 1553                    buffer.read(cx).all_buffers(),
 1554                    buffer.clone(),
 1555                    cx,
 1556                )
 1557                .shared(),
 1558            );
 1559            code_action_providers.push(Rc::new(project) as Rc<_>);
 1560        }
 1561
 1562        let mut this = Self {
 1563            focus_handle,
 1564            show_cursor_when_unfocused: false,
 1565            last_focused_descendant: None,
 1566            buffer: buffer.clone(),
 1567            display_map: display_map.clone(),
 1568            selections,
 1569            scroll_manager: ScrollManager::new(cx),
 1570            columnar_selection_tail: None,
 1571            add_selections_state: None,
 1572            select_next_state: None,
 1573            select_prev_state: None,
 1574            selection_history: Default::default(),
 1575            autoclose_regions: Default::default(),
 1576            snippet_stack: Default::default(),
 1577            select_syntax_node_history: SelectSyntaxNodeHistory::default(),
 1578            ime_transaction: Default::default(),
 1579            active_diagnostics: ActiveDiagnostic::None,
 1580            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1581            inline_diagnostics_update: Task::ready(()),
 1582            inline_diagnostics: Vec::new(),
 1583            soft_wrap_mode_override,
 1584            hard_wrap: None,
 1585            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1586            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1587            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1588            project,
 1589            blink_manager: blink_manager.clone(),
 1590            show_local_selections: true,
 1591            show_scrollbars: true,
 1592            mode,
 1593            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1594            show_gutter: mode.is_full(),
 1595            show_line_numbers: None,
 1596            use_relative_line_numbers: None,
 1597            show_git_diff_gutter: None,
 1598            show_code_actions: None,
 1599            show_runnables: None,
 1600            show_breakpoints: None,
 1601            show_wrap_guides: None,
 1602            show_indent_guides,
 1603            placeholder_text: None,
 1604            highlight_order: 0,
 1605            highlighted_rows: HashMap::default(),
 1606            background_highlights: Default::default(),
 1607            gutter_highlights: TreeMap::default(),
 1608            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1609            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1610            nav_history: None,
 1611            context_menu: RefCell::new(None),
 1612            context_menu_options: None,
 1613            mouse_context_menu: None,
 1614            completion_tasks: Default::default(),
 1615            signature_help_state: SignatureHelpState::default(),
 1616            auto_signature_help: None,
 1617            find_all_references_task_sources: Vec::new(),
 1618            next_completion_id: 0,
 1619            next_inlay_id: 0,
 1620            code_action_providers,
 1621            available_code_actions: Default::default(),
 1622            code_actions_task: Default::default(),
 1623            quick_selection_highlight_task: Default::default(),
 1624            debounced_selection_highlight_task: Default::default(),
 1625            document_highlights_task: Default::default(),
 1626            linked_editing_range_task: Default::default(),
 1627            pending_rename: Default::default(),
 1628            searchable: true,
 1629            cursor_shape: EditorSettings::get_global(cx)
 1630                .cursor_shape
 1631                .unwrap_or_default(),
 1632            current_line_highlight: None,
 1633            autoindent_mode: Some(AutoindentMode::EachLine),
 1634            collapse_matches: false,
 1635            workspace: None,
 1636            input_enabled: true,
 1637            use_modal_editing: mode.is_full(),
 1638            read_only: false,
 1639            use_autoclose: true,
 1640            use_auto_surround: true,
 1641            auto_replace_emoji_shortcode: false,
 1642            jsx_tag_auto_close_enabled_in_any_buffer: false,
 1643            leader_peer_id: None,
 1644            remote_id: None,
 1645            hover_state: Default::default(),
 1646            pending_mouse_down: None,
 1647            hovered_link_state: Default::default(),
 1648            edit_prediction_provider: None,
 1649            active_inline_completion: None,
 1650            stale_inline_completion_in_menu: None,
 1651            edit_prediction_preview: EditPredictionPreview::Inactive {
 1652                released_too_fast: false,
 1653            },
 1654            inline_diagnostics_enabled: mode.is_full(),
 1655            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1656
 1657            gutter_hovered: false,
 1658            pixel_position_of_newest_cursor: None,
 1659            last_bounds: None,
 1660            last_position_map: None,
 1661            expect_bounds_change: None,
 1662            gutter_dimensions: GutterDimensions::default(),
 1663            style: None,
 1664            show_cursor_names: false,
 1665            hovered_cursors: Default::default(),
 1666            next_editor_action_id: EditorActionId::default(),
 1667            editor_actions: Rc::default(),
 1668            inline_completions_hidden_for_vim_mode: false,
 1669            show_inline_completions_override: None,
 1670            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1671            edit_prediction_settings: EditPredictionSettings::Disabled,
 1672            edit_prediction_indent_conflict: false,
 1673            edit_prediction_requires_modifier_in_indent_conflict: true,
 1674            custom_context_menu: None,
 1675            show_git_blame_gutter: false,
 1676            show_git_blame_inline: false,
 1677            show_selection_menu: None,
 1678            show_git_blame_inline_delay_task: None,
 1679            git_blame_inline_tooltip: None,
 1680            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1681            render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
 1682            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1683                .session
 1684                .restore_unsaved_buffers,
 1685            blame: None,
 1686            blame_subscription: None,
 1687            tasks: Default::default(),
 1688
 1689            breakpoint_store,
 1690            gutter_breakpoint_indicator: (None, None),
 1691            _subscriptions: vec![
 1692                cx.observe(&buffer, Self::on_buffer_changed),
 1693                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1694                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1695                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1696                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1697                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1698                cx.observe_window_activation(window, |editor, window, cx| {
 1699                    let active = window.is_window_active();
 1700                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1701                        if active {
 1702                            blink_manager.enable(cx);
 1703                        } else {
 1704                            blink_manager.disable(cx);
 1705                        }
 1706                    });
 1707                }),
 1708            ],
 1709            tasks_update_task: None,
 1710            linked_edit_ranges: Default::default(),
 1711            in_project_search: false,
 1712            previous_search_ranges: None,
 1713            breadcrumb_header: None,
 1714            focused_block: None,
 1715            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1716            addons: HashMap::default(),
 1717            registered_buffers: HashMap::default(),
 1718            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1719            selection_mark_mode: false,
 1720            toggle_fold_multiple_buffers: Task::ready(()),
 1721            serialize_selections: Task::ready(()),
 1722            serialize_folds: Task::ready(()),
 1723            text_style_refinement: None,
 1724            load_diff_task: load_uncommitted_diff,
 1725            mouse_cursor_hidden: false,
 1726            hide_mouse_mode: EditorSettings::get_global(cx)
 1727                .hide_mouse
 1728                .unwrap_or_default(),
 1729            change_list: ChangeList::new(),
 1730        };
 1731        if let Some(breakpoints) = this.breakpoint_store.as_ref() {
 1732            this._subscriptions
 1733                .push(cx.observe(breakpoints, |_, _, cx| {
 1734                    cx.notify();
 1735                }));
 1736        }
 1737        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1738        this._subscriptions.extend(project_subscriptions);
 1739
 1740        this._subscriptions.push(cx.subscribe_in(
 1741            &cx.entity(),
 1742            window,
 1743            |editor, _, e: &EditorEvent, window, cx| match e {
 1744                EditorEvent::ScrollPositionChanged { local, .. } => {
 1745                    if *local {
 1746                        let new_anchor = editor.scroll_manager.anchor();
 1747                        let snapshot = editor.snapshot(window, cx);
 1748                        editor.update_restoration_data(cx, move |data| {
 1749                            data.scroll_position = (
 1750                                new_anchor.top_row(&snapshot.buffer_snapshot),
 1751                                new_anchor.offset,
 1752                            );
 1753                        });
 1754                        editor.hide_signature_help(cx, SignatureHelpHiddenBy::Escape);
 1755                    }
 1756                }
 1757                EditorEvent::Edited { .. } => {
 1758                    if !vim_enabled(cx) {
 1759                        let (map, selections) = editor.selections.all_adjusted_display(cx);
 1760                        let pop_state = editor
 1761                            .change_list
 1762                            .last()
 1763                            .map(|previous| {
 1764                                previous.len() == selections.len()
 1765                                    && previous.iter().enumerate().all(|(ix, p)| {
 1766                                        p.to_display_point(&map).row()
 1767                                            == selections[ix].head().row()
 1768                                    })
 1769                            })
 1770                            .unwrap_or(false);
 1771                        let new_positions = selections
 1772                            .into_iter()
 1773                            .map(|s| map.display_point_to_anchor(s.head(), Bias::Left))
 1774                            .collect();
 1775                        editor
 1776                            .change_list
 1777                            .push_to_change_list(pop_state, new_positions);
 1778                    }
 1779                }
 1780                _ => (),
 1781            },
 1782        ));
 1783
 1784        this.end_selection(window, cx);
 1785        this.scroll_manager.show_scrollbars(window, cx);
 1786        jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
 1787
 1788        if mode.is_full() {
 1789            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1790            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1791
 1792            if this.git_blame_inline_enabled {
 1793                this.git_blame_inline_enabled = true;
 1794                this.start_git_blame_inline(false, window, cx);
 1795            }
 1796
 1797            this.go_to_active_debug_line(window, cx);
 1798
 1799            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1800                if let Some(project) = this.project.as_ref() {
 1801                    let handle = project.update(cx, |project, cx| {
 1802                        project.register_buffer_with_language_servers(&buffer, cx)
 1803                    });
 1804                    this.registered_buffers
 1805                        .insert(buffer.read(cx).remote_id(), handle);
 1806                }
 1807            }
 1808        }
 1809
 1810        this.report_editor_event("Editor Opened", None, cx);
 1811        this
 1812    }
 1813
 1814    pub fn deploy_mouse_context_menu(
 1815        &mut self,
 1816        position: gpui::Point<Pixels>,
 1817        context_menu: Entity<ContextMenu>,
 1818        window: &mut Window,
 1819        cx: &mut Context<Self>,
 1820    ) {
 1821        self.mouse_context_menu = Some(MouseContextMenu::new(
 1822            self,
 1823            crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
 1824            context_menu,
 1825            window,
 1826            cx,
 1827        ));
 1828    }
 1829
 1830    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1831        self.mouse_context_menu
 1832            .as_ref()
 1833            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1834    }
 1835
 1836    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1837        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1838    }
 1839
 1840    fn key_context_internal(
 1841        &self,
 1842        has_active_edit_prediction: bool,
 1843        window: &Window,
 1844        cx: &App,
 1845    ) -> KeyContext {
 1846        let mut key_context = KeyContext::new_with_defaults();
 1847        key_context.add("Editor");
 1848        let mode = match self.mode {
 1849            EditorMode::SingleLine { .. } => "single_line",
 1850            EditorMode::AutoHeight { .. } => "auto_height",
 1851            EditorMode::Full { .. } => "full",
 1852        };
 1853
 1854        if EditorSettings::jupyter_enabled(cx) {
 1855            key_context.add("jupyter");
 1856        }
 1857
 1858        key_context.set("mode", mode);
 1859        if self.pending_rename.is_some() {
 1860            key_context.add("renaming");
 1861        }
 1862
 1863        match self.context_menu.borrow().as_ref() {
 1864            Some(CodeContextMenu::Completions(_)) => {
 1865                key_context.add("menu");
 1866                key_context.add("showing_completions");
 1867            }
 1868            Some(CodeContextMenu::CodeActions(_)) => {
 1869                key_context.add("menu");
 1870                key_context.add("showing_code_actions")
 1871            }
 1872            None => {}
 1873        }
 1874
 1875        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1876        if !self.focus_handle(cx).contains_focused(window, cx)
 1877            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1878        {
 1879            for addon in self.addons.values() {
 1880                addon.extend_key_context(&mut key_context, cx)
 1881            }
 1882        }
 1883
 1884        if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
 1885            if let Some(extension) = singleton_buffer
 1886                .read(cx)
 1887                .file()
 1888                .and_then(|file| file.path().extension()?.to_str())
 1889            {
 1890                key_context.set("extension", extension.to_string());
 1891            }
 1892        } else {
 1893            key_context.add("multibuffer");
 1894        }
 1895
 1896        if has_active_edit_prediction {
 1897            if self.edit_prediction_in_conflict() {
 1898                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1899            } else {
 1900                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1901                key_context.add("copilot_suggestion");
 1902            }
 1903        }
 1904
 1905        if self.selection_mark_mode {
 1906            key_context.add("selection_mode");
 1907        }
 1908
 1909        key_context
 1910    }
 1911
 1912    pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
 1913        self.mouse_cursor_hidden = match origin {
 1914            HideMouseCursorOrigin::TypingAction => {
 1915                matches!(
 1916                    self.hide_mouse_mode,
 1917                    HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
 1918                )
 1919            }
 1920            HideMouseCursorOrigin::MovementAction => {
 1921                matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
 1922            }
 1923        };
 1924    }
 1925
 1926    pub fn edit_prediction_in_conflict(&self) -> bool {
 1927        if !self.show_edit_predictions_in_menu() {
 1928            return false;
 1929        }
 1930
 1931        let showing_completions = self
 1932            .context_menu
 1933            .borrow()
 1934            .as_ref()
 1935            .map_or(false, |context| {
 1936                matches!(context, CodeContextMenu::Completions(_))
 1937            });
 1938
 1939        showing_completions
 1940            || self.edit_prediction_requires_modifier()
 1941            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1942            // bindings to insert tab characters.
 1943            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 1944    }
 1945
 1946    pub fn accept_edit_prediction_keybind(
 1947        &self,
 1948        window: &Window,
 1949        cx: &App,
 1950    ) -> AcceptEditPredictionBinding {
 1951        let key_context = self.key_context_internal(true, window, cx);
 1952        let in_conflict = self.edit_prediction_in_conflict();
 1953
 1954        AcceptEditPredictionBinding(
 1955            window
 1956                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1957                .into_iter()
 1958                .filter(|binding| {
 1959                    !in_conflict
 1960                        || binding
 1961                            .keystrokes()
 1962                            .first()
 1963                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1964                })
 1965                .rev()
 1966                .min_by_key(|binding| {
 1967                    binding
 1968                        .keystrokes()
 1969                        .first()
 1970                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1971                }),
 1972        )
 1973    }
 1974
 1975    pub fn new_file(
 1976        workspace: &mut Workspace,
 1977        _: &workspace::NewFile,
 1978        window: &mut Window,
 1979        cx: &mut Context<Workspace>,
 1980    ) {
 1981        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1982            "Failed to create buffer",
 1983            window,
 1984            cx,
 1985            |e, _, _| match e.error_code() {
 1986                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1987                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1988                e.error_tag("required").unwrap_or("the latest version")
 1989            )),
 1990                _ => None,
 1991            },
 1992        );
 1993    }
 1994
 1995    pub fn new_in_workspace(
 1996        workspace: &mut Workspace,
 1997        window: &mut Window,
 1998        cx: &mut Context<Workspace>,
 1999    ) -> Task<Result<Entity<Editor>>> {
 2000        let project = workspace.project().clone();
 2001        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2002
 2003        cx.spawn_in(window, async move |workspace, cx| {
 2004            let buffer = create.await?;
 2005            workspace.update_in(cx, |workspace, window, cx| {
 2006                let editor =
 2007                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 2008                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 2009                editor
 2010            })
 2011        })
 2012    }
 2013
 2014    fn new_file_vertical(
 2015        workspace: &mut Workspace,
 2016        _: &workspace::NewFileSplitVertical,
 2017        window: &mut Window,
 2018        cx: &mut Context<Workspace>,
 2019    ) {
 2020        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 2021    }
 2022
 2023    fn new_file_horizontal(
 2024        workspace: &mut Workspace,
 2025        _: &workspace::NewFileSplitHorizontal,
 2026        window: &mut Window,
 2027        cx: &mut Context<Workspace>,
 2028    ) {
 2029        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 2030    }
 2031
 2032    fn new_file_in_direction(
 2033        workspace: &mut Workspace,
 2034        direction: SplitDirection,
 2035        window: &mut Window,
 2036        cx: &mut Context<Workspace>,
 2037    ) {
 2038        let project = workspace.project().clone();
 2039        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2040
 2041        cx.spawn_in(window, async move |workspace, cx| {
 2042            let buffer = create.await?;
 2043            workspace.update_in(cx, move |workspace, window, cx| {
 2044                workspace.split_item(
 2045                    direction,
 2046                    Box::new(
 2047                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 2048                    ),
 2049                    window,
 2050                    cx,
 2051                )
 2052            })?;
 2053            anyhow::Ok(())
 2054        })
 2055        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 2056            match e.error_code() {
 2057                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2058                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2059                e.error_tag("required").unwrap_or("the latest version")
 2060            )),
 2061                _ => None,
 2062            }
 2063        });
 2064    }
 2065
 2066    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2067        self.leader_peer_id
 2068    }
 2069
 2070    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 2071        &self.buffer
 2072    }
 2073
 2074    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 2075        self.workspace.as_ref()?.0.upgrade()
 2076    }
 2077
 2078    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 2079        self.buffer().read(cx).title(cx)
 2080    }
 2081
 2082    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 2083        let git_blame_gutter_max_author_length = self
 2084            .render_git_blame_gutter(cx)
 2085            .then(|| {
 2086                if let Some(blame) = self.blame.as_ref() {
 2087                    let max_author_length =
 2088                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2089                    Some(max_author_length)
 2090                } else {
 2091                    None
 2092                }
 2093            })
 2094            .flatten();
 2095
 2096        EditorSnapshot {
 2097            mode: self.mode,
 2098            show_gutter: self.show_gutter,
 2099            show_line_numbers: self.show_line_numbers,
 2100            show_git_diff_gutter: self.show_git_diff_gutter,
 2101            show_code_actions: self.show_code_actions,
 2102            show_runnables: self.show_runnables,
 2103            show_breakpoints: self.show_breakpoints,
 2104            git_blame_gutter_max_author_length,
 2105            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2106            scroll_anchor: self.scroll_manager.anchor(),
 2107            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2108            placeholder_text: self.placeholder_text.clone(),
 2109            is_focused: self.focus_handle.is_focused(window),
 2110            current_line_highlight: self
 2111                .current_line_highlight
 2112                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2113            gutter_hovered: self.gutter_hovered,
 2114        }
 2115    }
 2116
 2117    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 2118        self.buffer.read(cx).language_at(point, cx)
 2119    }
 2120
 2121    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 2122        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2123    }
 2124
 2125    pub fn active_excerpt(
 2126        &self,
 2127        cx: &App,
 2128    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 2129        self.buffer
 2130            .read(cx)
 2131            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2132    }
 2133
 2134    pub fn mode(&self) -> EditorMode {
 2135        self.mode
 2136    }
 2137
 2138    pub fn set_mode(&mut self, mode: EditorMode) {
 2139        self.mode = mode;
 2140    }
 2141
 2142    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2143        self.collaboration_hub.as_deref()
 2144    }
 2145
 2146    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2147        self.collaboration_hub = Some(hub);
 2148    }
 2149
 2150    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 2151        self.in_project_search = in_project_search;
 2152    }
 2153
 2154    pub fn set_custom_context_menu(
 2155        &mut self,
 2156        f: impl 'static
 2157        + Fn(
 2158            &mut Self,
 2159            DisplayPoint,
 2160            &mut Window,
 2161            &mut Context<Self>,
 2162        ) -> Option<Entity<ui::ContextMenu>>,
 2163    ) {
 2164        self.custom_context_menu = Some(Box::new(f))
 2165    }
 2166
 2167    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2168        self.completion_provider = provider;
 2169    }
 2170
 2171    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2172        self.semantics_provider.clone()
 2173    }
 2174
 2175    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2176        self.semantics_provider = provider;
 2177    }
 2178
 2179    pub fn set_edit_prediction_provider<T>(
 2180        &mut self,
 2181        provider: Option<Entity<T>>,
 2182        window: &mut Window,
 2183        cx: &mut Context<Self>,
 2184    ) where
 2185        T: EditPredictionProvider,
 2186    {
 2187        self.edit_prediction_provider =
 2188            provider.map(|provider| RegisteredInlineCompletionProvider {
 2189                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 2190                    if this.focus_handle.is_focused(window) {
 2191                        this.update_visible_inline_completion(window, cx);
 2192                    }
 2193                }),
 2194                provider: Arc::new(provider),
 2195            });
 2196        self.update_edit_prediction_settings(cx);
 2197        self.refresh_inline_completion(false, false, window, cx);
 2198    }
 2199
 2200    pub fn placeholder_text(&self) -> Option<&str> {
 2201        self.placeholder_text.as_deref()
 2202    }
 2203
 2204    pub fn set_placeholder_text(
 2205        &mut self,
 2206        placeholder_text: impl Into<Arc<str>>,
 2207        cx: &mut Context<Self>,
 2208    ) {
 2209        let placeholder_text = Some(placeholder_text.into());
 2210        if self.placeholder_text != placeholder_text {
 2211            self.placeholder_text = placeholder_text;
 2212            cx.notify();
 2213        }
 2214    }
 2215
 2216    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 2217        self.cursor_shape = cursor_shape;
 2218
 2219        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2220        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2221
 2222        cx.notify();
 2223    }
 2224
 2225    pub fn set_current_line_highlight(
 2226        &mut self,
 2227        current_line_highlight: Option<CurrentLineHighlight>,
 2228    ) {
 2229        self.current_line_highlight = current_line_highlight;
 2230    }
 2231
 2232    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2233        self.collapse_matches = collapse_matches;
 2234    }
 2235
 2236    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 2237        let buffers = self.buffer.read(cx).all_buffers();
 2238        let Some(project) = self.project.as_ref() else {
 2239            return;
 2240        };
 2241        project.update(cx, |project, cx| {
 2242            for buffer in buffers {
 2243                self.registered_buffers
 2244                    .entry(buffer.read(cx).remote_id())
 2245                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 2246            }
 2247        })
 2248    }
 2249
 2250    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2251        if self.collapse_matches {
 2252            return range.start..range.start;
 2253        }
 2254        range.clone()
 2255    }
 2256
 2257    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 2258        if self.display_map.read(cx).clip_at_line_ends != clip {
 2259            self.display_map
 2260                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2261        }
 2262    }
 2263
 2264    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2265        self.input_enabled = input_enabled;
 2266    }
 2267
 2268    pub fn set_inline_completions_hidden_for_vim_mode(
 2269        &mut self,
 2270        hidden: bool,
 2271        window: &mut Window,
 2272        cx: &mut Context<Self>,
 2273    ) {
 2274        if hidden != self.inline_completions_hidden_for_vim_mode {
 2275            self.inline_completions_hidden_for_vim_mode = hidden;
 2276            if hidden {
 2277                self.update_visible_inline_completion(window, cx);
 2278            } else {
 2279                self.refresh_inline_completion(true, false, window, cx);
 2280            }
 2281        }
 2282    }
 2283
 2284    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 2285        self.menu_inline_completions_policy = value;
 2286    }
 2287
 2288    pub fn set_autoindent(&mut self, autoindent: bool) {
 2289        if autoindent {
 2290            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2291        } else {
 2292            self.autoindent_mode = None;
 2293        }
 2294    }
 2295
 2296    pub fn read_only(&self, cx: &App) -> bool {
 2297        self.read_only || self.buffer.read(cx).read_only()
 2298    }
 2299
 2300    pub fn set_read_only(&mut self, read_only: bool) {
 2301        self.read_only = read_only;
 2302    }
 2303
 2304    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2305        self.use_autoclose = autoclose;
 2306    }
 2307
 2308    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2309        self.use_auto_surround = auto_surround;
 2310    }
 2311
 2312    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2313        self.auto_replace_emoji_shortcode = auto_replace;
 2314    }
 2315
 2316    pub fn toggle_edit_predictions(
 2317        &mut self,
 2318        _: &ToggleEditPrediction,
 2319        window: &mut Window,
 2320        cx: &mut Context<Self>,
 2321    ) {
 2322        if self.show_inline_completions_override.is_some() {
 2323            self.set_show_edit_predictions(None, window, cx);
 2324        } else {
 2325            let show_edit_predictions = !self.edit_predictions_enabled();
 2326            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 2327        }
 2328    }
 2329
 2330    pub fn set_show_edit_predictions(
 2331        &mut self,
 2332        show_edit_predictions: Option<bool>,
 2333        window: &mut Window,
 2334        cx: &mut Context<Self>,
 2335    ) {
 2336        self.show_inline_completions_override = show_edit_predictions;
 2337        self.update_edit_prediction_settings(cx);
 2338
 2339        if let Some(false) = show_edit_predictions {
 2340            self.discard_inline_completion(false, cx);
 2341        } else {
 2342            self.refresh_inline_completion(false, true, window, cx);
 2343        }
 2344    }
 2345
 2346    fn inline_completions_disabled_in_scope(
 2347        &self,
 2348        buffer: &Entity<Buffer>,
 2349        buffer_position: language::Anchor,
 2350        cx: &App,
 2351    ) -> bool {
 2352        let snapshot = buffer.read(cx).snapshot();
 2353        let settings = snapshot.settings_at(buffer_position, cx);
 2354
 2355        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2356            return false;
 2357        };
 2358
 2359        scope.override_name().map_or(false, |scope_name| {
 2360            settings
 2361                .edit_predictions_disabled_in
 2362                .iter()
 2363                .any(|s| s == scope_name)
 2364        })
 2365    }
 2366
 2367    pub fn set_use_modal_editing(&mut self, to: bool) {
 2368        self.use_modal_editing = to;
 2369    }
 2370
 2371    pub fn use_modal_editing(&self) -> bool {
 2372        self.use_modal_editing
 2373    }
 2374
 2375    fn selections_did_change(
 2376        &mut self,
 2377        local: bool,
 2378        old_cursor_position: &Anchor,
 2379        show_completions: bool,
 2380        window: &mut Window,
 2381        cx: &mut Context<Self>,
 2382    ) {
 2383        window.invalidate_character_coordinates();
 2384
 2385        // Copy selections to primary selection buffer
 2386        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2387        if local {
 2388            let selections = self.selections.all::<usize>(cx);
 2389            let buffer_handle = self.buffer.read(cx).read(cx);
 2390
 2391            let mut text = String::new();
 2392            for (index, selection) in selections.iter().enumerate() {
 2393                let text_for_selection = buffer_handle
 2394                    .text_for_range(selection.start..selection.end)
 2395                    .collect::<String>();
 2396
 2397                text.push_str(&text_for_selection);
 2398                if index != selections.len() - 1 {
 2399                    text.push('\n');
 2400                }
 2401            }
 2402
 2403            if !text.is_empty() {
 2404                cx.write_to_primary(ClipboardItem::new_string(text));
 2405            }
 2406        }
 2407
 2408        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2409            self.buffer.update(cx, |buffer, cx| {
 2410                buffer.set_active_selections(
 2411                    &self.selections.disjoint_anchors(),
 2412                    self.selections.line_mode,
 2413                    self.cursor_shape,
 2414                    cx,
 2415                )
 2416            });
 2417        }
 2418        let display_map = self
 2419            .display_map
 2420            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2421        let buffer = &display_map.buffer_snapshot;
 2422        self.add_selections_state = None;
 2423        self.select_next_state = None;
 2424        self.select_prev_state = None;
 2425        self.select_syntax_node_history.try_clear();
 2426        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2427        self.snippet_stack
 2428            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2429        self.take_rename(false, window, cx);
 2430
 2431        let new_cursor_position = self.selections.newest_anchor().head();
 2432
 2433        self.push_to_nav_history(
 2434            *old_cursor_position,
 2435            Some(new_cursor_position.to_point(buffer)),
 2436            false,
 2437            cx,
 2438        );
 2439
 2440        if local {
 2441            let new_cursor_position = self.selections.newest_anchor().head();
 2442            let mut context_menu = self.context_menu.borrow_mut();
 2443            let completion_menu = match context_menu.as_ref() {
 2444                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2445                _ => {
 2446                    *context_menu = None;
 2447                    None
 2448                }
 2449            };
 2450            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2451                if !self.registered_buffers.contains_key(&buffer_id) {
 2452                    if let Some(project) = self.project.as_ref() {
 2453                        project.update(cx, |project, cx| {
 2454                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2455                                return;
 2456                            };
 2457                            self.registered_buffers.insert(
 2458                                buffer_id,
 2459                                project.register_buffer_with_language_servers(&buffer, cx),
 2460                            );
 2461                        })
 2462                    }
 2463                }
 2464            }
 2465
 2466            if let Some(completion_menu) = completion_menu {
 2467                let cursor_position = new_cursor_position.to_offset(buffer);
 2468                let (word_range, kind) =
 2469                    buffer.surrounding_word(completion_menu.initial_position, true);
 2470                if kind == Some(CharKind::Word)
 2471                    && word_range.to_inclusive().contains(&cursor_position)
 2472                {
 2473                    let mut completion_menu = completion_menu.clone();
 2474                    drop(context_menu);
 2475
 2476                    let query = Self::completion_query(buffer, cursor_position);
 2477                    cx.spawn(async move |this, cx| {
 2478                        completion_menu
 2479                            .filter(query.as_deref(), cx.background_executor().clone())
 2480                            .await;
 2481
 2482                        this.update(cx, |this, cx| {
 2483                            let mut context_menu = this.context_menu.borrow_mut();
 2484                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2485                            else {
 2486                                return;
 2487                            };
 2488
 2489                            if menu.id > completion_menu.id {
 2490                                return;
 2491                            }
 2492
 2493                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2494                            drop(context_menu);
 2495                            cx.notify();
 2496                        })
 2497                    })
 2498                    .detach();
 2499
 2500                    if show_completions {
 2501                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2502                    }
 2503                } else {
 2504                    drop(context_menu);
 2505                    self.hide_context_menu(window, cx);
 2506                }
 2507            } else {
 2508                drop(context_menu);
 2509            }
 2510
 2511            hide_hover(self, cx);
 2512
 2513            if old_cursor_position.to_display_point(&display_map).row()
 2514                != new_cursor_position.to_display_point(&display_map).row()
 2515            {
 2516                self.available_code_actions.take();
 2517            }
 2518            self.refresh_code_actions(window, cx);
 2519            self.refresh_document_highlights(cx);
 2520            self.refresh_selected_text_highlights(window, cx);
 2521            refresh_matching_bracket_highlights(self, window, cx);
 2522            self.update_visible_inline_completion(window, cx);
 2523            self.edit_prediction_requires_modifier_in_indent_conflict = true;
 2524            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2525            if self.git_blame_inline_enabled {
 2526                self.start_inline_blame_timer(window, cx);
 2527            }
 2528        }
 2529
 2530        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2531        cx.emit(EditorEvent::SelectionsChanged { local });
 2532
 2533        let selections = &self.selections.disjoint;
 2534        if selections.len() == 1 {
 2535            cx.emit(SearchEvent::ActiveMatchChanged)
 2536        }
 2537        if local {
 2538            if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
 2539                let inmemory_selections = selections
 2540                    .iter()
 2541                    .map(|s| {
 2542                        text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
 2543                            ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
 2544                    })
 2545                    .collect();
 2546                self.update_restoration_data(cx, |data| {
 2547                    data.selections = inmemory_selections;
 2548                });
 2549
 2550                if WorkspaceSettings::get(None, cx).restore_on_startup
 2551                    != RestoreOnStartupBehavior::None
 2552                {
 2553                    if let Some(workspace_id) =
 2554                        self.workspace.as_ref().and_then(|workspace| workspace.1)
 2555                    {
 2556                        let snapshot = self.buffer().read(cx).snapshot(cx);
 2557                        let selections = selections.clone();
 2558                        let background_executor = cx.background_executor().clone();
 2559                        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2560                        self.serialize_selections = cx.background_spawn(async move {
 2561                    background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2562                    let db_selections = selections
 2563                        .iter()
 2564                        .map(|selection| {
 2565                            (
 2566                                selection.start.to_offset(&snapshot),
 2567                                selection.end.to_offset(&snapshot),
 2568                            )
 2569                        })
 2570                        .collect();
 2571
 2572                    DB.save_editor_selections(editor_id, workspace_id, db_selections)
 2573                        .await
 2574                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2575                        .log_err();
 2576                });
 2577                    }
 2578                }
 2579            }
 2580        }
 2581
 2582        cx.notify();
 2583    }
 2584
 2585    fn folds_did_change(&mut self, cx: &mut Context<Self>) {
 2586        use text::ToOffset as _;
 2587        use text::ToPoint as _;
 2588
 2589        if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
 2590            return;
 2591        }
 2592
 2593        let Some(singleton) = self.buffer().read(cx).as_singleton() else {
 2594            return;
 2595        };
 2596
 2597        let snapshot = singleton.read(cx).snapshot();
 2598        let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
 2599            let display_snapshot = display_map.snapshot(cx);
 2600
 2601            display_snapshot
 2602                .folds_in_range(0..display_snapshot.buffer_snapshot.len())
 2603                .map(|fold| {
 2604                    fold.range.start.text_anchor.to_point(&snapshot)
 2605                        ..fold.range.end.text_anchor.to_point(&snapshot)
 2606                })
 2607                .collect()
 2608        });
 2609        self.update_restoration_data(cx, |data| {
 2610            data.folds = inmemory_folds;
 2611        });
 2612
 2613        let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
 2614            return;
 2615        };
 2616        let background_executor = cx.background_executor().clone();
 2617        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2618        let db_folds = self.display_map.update(cx, |display_map, cx| {
 2619            display_map
 2620                .snapshot(cx)
 2621                .folds_in_range(0..snapshot.len())
 2622                .map(|fold| {
 2623                    (
 2624                        fold.range.start.text_anchor.to_offset(&snapshot),
 2625                        fold.range.end.text_anchor.to_offset(&snapshot),
 2626                    )
 2627                })
 2628                .collect()
 2629        });
 2630        self.serialize_folds = cx.background_spawn(async move {
 2631            background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2632            DB.save_editor_folds(editor_id, workspace_id, db_folds)
 2633                .await
 2634                .with_context(|| {
 2635                    format!(
 2636                        "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
 2637                    )
 2638                })
 2639                .log_err();
 2640        });
 2641    }
 2642
 2643    pub fn sync_selections(
 2644        &mut self,
 2645        other: Entity<Editor>,
 2646        cx: &mut Context<Self>,
 2647    ) -> gpui::Subscription {
 2648        let other_selections = other.read(cx).selections.disjoint.to_vec();
 2649        self.selections.change_with(cx, |selections| {
 2650            selections.select_anchors(other_selections);
 2651        });
 2652
 2653        let other_subscription =
 2654            cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
 2655                EditorEvent::SelectionsChanged { local: true } => {
 2656                    let other_selections = other.read(cx).selections.disjoint.to_vec();
 2657                    if other_selections.is_empty() {
 2658                        return;
 2659                    }
 2660                    this.selections.change_with(cx, |selections| {
 2661                        selections.select_anchors(other_selections);
 2662                    });
 2663                }
 2664                _ => {}
 2665            });
 2666
 2667        let this_subscription =
 2668            cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
 2669                EditorEvent::SelectionsChanged { local: true } => {
 2670                    let these_selections = this.selections.disjoint.to_vec();
 2671                    if these_selections.is_empty() {
 2672                        return;
 2673                    }
 2674                    other.update(cx, |other_editor, cx| {
 2675                        other_editor.selections.change_with(cx, |selections| {
 2676                            selections.select_anchors(these_selections);
 2677                        })
 2678                    });
 2679                }
 2680                _ => {}
 2681            });
 2682
 2683        Subscription::join(other_subscription, this_subscription)
 2684    }
 2685
 2686    pub fn change_selections<R>(
 2687        &mut self,
 2688        autoscroll: Option<Autoscroll>,
 2689        window: &mut Window,
 2690        cx: &mut Context<Self>,
 2691        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2692    ) -> R {
 2693        self.change_selections_inner(autoscroll, true, window, cx, change)
 2694    }
 2695
 2696    fn change_selections_inner<R>(
 2697        &mut self,
 2698        autoscroll: Option<Autoscroll>,
 2699        request_completions: bool,
 2700        window: &mut Window,
 2701        cx: &mut Context<Self>,
 2702        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2703    ) -> R {
 2704        let old_cursor_position = self.selections.newest_anchor().head();
 2705        self.push_to_selection_history();
 2706
 2707        let (changed, result) = self.selections.change_with(cx, change);
 2708
 2709        if changed {
 2710            if let Some(autoscroll) = autoscroll {
 2711                self.request_autoscroll(autoscroll, cx);
 2712            }
 2713            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2714
 2715            if self.should_open_signature_help_automatically(
 2716                &old_cursor_position,
 2717                self.signature_help_state.backspace_pressed(),
 2718                cx,
 2719            ) {
 2720                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2721            }
 2722            self.signature_help_state.set_backspace_pressed(false);
 2723        }
 2724
 2725        result
 2726    }
 2727
 2728    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2729    where
 2730        I: IntoIterator<Item = (Range<S>, T)>,
 2731        S: ToOffset,
 2732        T: Into<Arc<str>>,
 2733    {
 2734        if self.read_only(cx) {
 2735            return;
 2736        }
 2737
 2738        self.buffer
 2739            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2740    }
 2741
 2742    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2743    where
 2744        I: IntoIterator<Item = (Range<S>, T)>,
 2745        S: ToOffset,
 2746        T: Into<Arc<str>>,
 2747    {
 2748        if self.read_only(cx) {
 2749            return;
 2750        }
 2751
 2752        self.buffer.update(cx, |buffer, cx| {
 2753            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2754        });
 2755    }
 2756
 2757    pub fn edit_with_block_indent<I, S, T>(
 2758        &mut self,
 2759        edits: I,
 2760        original_indent_columns: Vec<Option<u32>>,
 2761        cx: &mut Context<Self>,
 2762    ) where
 2763        I: IntoIterator<Item = (Range<S>, T)>,
 2764        S: ToOffset,
 2765        T: Into<Arc<str>>,
 2766    {
 2767        if self.read_only(cx) {
 2768            return;
 2769        }
 2770
 2771        self.buffer.update(cx, |buffer, cx| {
 2772            buffer.edit(
 2773                edits,
 2774                Some(AutoindentMode::Block {
 2775                    original_indent_columns,
 2776                }),
 2777                cx,
 2778            )
 2779        });
 2780    }
 2781
 2782    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2783        self.hide_context_menu(window, cx);
 2784
 2785        match phase {
 2786            SelectPhase::Begin {
 2787                position,
 2788                add,
 2789                click_count,
 2790            } => self.begin_selection(position, add, click_count, window, cx),
 2791            SelectPhase::BeginColumnar {
 2792                position,
 2793                goal_column,
 2794                reset,
 2795            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2796            SelectPhase::Extend {
 2797                position,
 2798                click_count,
 2799            } => self.extend_selection(position, click_count, window, cx),
 2800            SelectPhase::Update {
 2801                position,
 2802                goal_column,
 2803                scroll_delta,
 2804            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2805            SelectPhase::End => self.end_selection(window, cx),
 2806        }
 2807    }
 2808
 2809    fn extend_selection(
 2810        &mut self,
 2811        position: DisplayPoint,
 2812        click_count: usize,
 2813        window: &mut Window,
 2814        cx: &mut Context<Self>,
 2815    ) {
 2816        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2817        let tail = self.selections.newest::<usize>(cx).tail();
 2818        self.begin_selection(position, false, click_count, window, cx);
 2819
 2820        let position = position.to_offset(&display_map, Bias::Left);
 2821        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2822
 2823        let mut pending_selection = self
 2824            .selections
 2825            .pending_anchor()
 2826            .expect("extend_selection not called with pending selection");
 2827        if position >= tail {
 2828            pending_selection.start = tail_anchor;
 2829        } else {
 2830            pending_selection.end = tail_anchor;
 2831            pending_selection.reversed = true;
 2832        }
 2833
 2834        let mut pending_mode = self.selections.pending_mode().unwrap();
 2835        match &mut pending_mode {
 2836            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2837            _ => {}
 2838        }
 2839
 2840        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2841            s.set_pending(pending_selection, pending_mode)
 2842        });
 2843    }
 2844
 2845    fn begin_selection(
 2846        &mut self,
 2847        position: DisplayPoint,
 2848        add: bool,
 2849        click_count: usize,
 2850        window: &mut Window,
 2851        cx: &mut Context<Self>,
 2852    ) {
 2853        if !self.focus_handle.is_focused(window) {
 2854            self.last_focused_descendant = None;
 2855            window.focus(&self.focus_handle);
 2856        }
 2857
 2858        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2859        let buffer = &display_map.buffer_snapshot;
 2860        let newest_selection = self.selections.newest_anchor().clone();
 2861        let position = display_map.clip_point(position, Bias::Left);
 2862
 2863        let start;
 2864        let end;
 2865        let mode;
 2866        let mut auto_scroll;
 2867        match click_count {
 2868            1 => {
 2869                start = buffer.anchor_before(position.to_point(&display_map));
 2870                end = start;
 2871                mode = SelectMode::Character;
 2872                auto_scroll = true;
 2873            }
 2874            2 => {
 2875                let range = movement::surrounding_word(&display_map, position);
 2876                start = buffer.anchor_before(range.start.to_point(&display_map));
 2877                end = buffer.anchor_before(range.end.to_point(&display_map));
 2878                mode = SelectMode::Word(start..end);
 2879                auto_scroll = true;
 2880            }
 2881            3 => {
 2882                let position = display_map
 2883                    .clip_point(position, Bias::Left)
 2884                    .to_point(&display_map);
 2885                let line_start = display_map.prev_line_boundary(position).0;
 2886                let next_line_start = buffer.clip_point(
 2887                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2888                    Bias::Left,
 2889                );
 2890                start = buffer.anchor_before(line_start);
 2891                end = buffer.anchor_before(next_line_start);
 2892                mode = SelectMode::Line(start..end);
 2893                auto_scroll = true;
 2894            }
 2895            _ => {
 2896                start = buffer.anchor_before(0);
 2897                end = buffer.anchor_before(buffer.len());
 2898                mode = SelectMode::All;
 2899                auto_scroll = false;
 2900            }
 2901        }
 2902        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2903
 2904        let point_to_delete: Option<usize> = {
 2905            let selected_points: Vec<Selection<Point>> =
 2906                self.selections.disjoint_in_range(start..end, cx);
 2907
 2908            if !add || click_count > 1 {
 2909                None
 2910            } else if !selected_points.is_empty() {
 2911                Some(selected_points[0].id)
 2912            } else {
 2913                let clicked_point_already_selected =
 2914                    self.selections.disjoint.iter().find(|selection| {
 2915                        selection.start.to_point(buffer) == start.to_point(buffer)
 2916                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2917                    });
 2918
 2919                clicked_point_already_selected.map(|selection| selection.id)
 2920            }
 2921        };
 2922
 2923        let selections_count = self.selections.count();
 2924
 2925        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2926            if let Some(point_to_delete) = point_to_delete {
 2927                s.delete(point_to_delete);
 2928
 2929                if selections_count == 1 {
 2930                    s.set_pending_anchor_range(start..end, mode);
 2931                }
 2932            } else {
 2933                if !add {
 2934                    s.clear_disjoint();
 2935                } else if click_count > 1 {
 2936                    s.delete(newest_selection.id)
 2937                }
 2938
 2939                s.set_pending_anchor_range(start..end, mode);
 2940            }
 2941        });
 2942    }
 2943
 2944    fn begin_columnar_selection(
 2945        &mut self,
 2946        position: DisplayPoint,
 2947        goal_column: u32,
 2948        reset: bool,
 2949        window: &mut Window,
 2950        cx: &mut Context<Self>,
 2951    ) {
 2952        if !self.focus_handle.is_focused(window) {
 2953            self.last_focused_descendant = None;
 2954            window.focus(&self.focus_handle);
 2955        }
 2956
 2957        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2958
 2959        if reset {
 2960            let pointer_position = display_map
 2961                .buffer_snapshot
 2962                .anchor_before(position.to_point(&display_map));
 2963
 2964            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2965                s.clear_disjoint();
 2966                s.set_pending_anchor_range(
 2967                    pointer_position..pointer_position,
 2968                    SelectMode::Character,
 2969                );
 2970            });
 2971        }
 2972
 2973        let tail = self.selections.newest::<Point>(cx).tail();
 2974        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2975
 2976        if !reset {
 2977            self.select_columns(
 2978                tail.to_display_point(&display_map),
 2979                position,
 2980                goal_column,
 2981                &display_map,
 2982                window,
 2983                cx,
 2984            );
 2985        }
 2986    }
 2987
 2988    fn update_selection(
 2989        &mut self,
 2990        position: DisplayPoint,
 2991        goal_column: u32,
 2992        scroll_delta: gpui::Point<f32>,
 2993        window: &mut Window,
 2994        cx: &mut Context<Self>,
 2995    ) {
 2996        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2997
 2998        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2999            let tail = tail.to_display_point(&display_map);
 3000            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 3001        } else if let Some(mut pending) = self.selections.pending_anchor() {
 3002            let buffer = self.buffer.read(cx).snapshot(cx);
 3003            let head;
 3004            let tail;
 3005            let mode = self.selections.pending_mode().unwrap();
 3006            match &mode {
 3007                SelectMode::Character => {
 3008                    head = position.to_point(&display_map);
 3009                    tail = pending.tail().to_point(&buffer);
 3010                }
 3011                SelectMode::Word(original_range) => {
 3012                    let original_display_range = original_range.start.to_display_point(&display_map)
 3013                        ..original_range.end.to_display_point(&display_map);
 3014                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 3015                        ..original_display_range.end.to_point(&display_map);
 3016                    if movement::is_inside_word(&display_map, position)
 3017                        || original_display_range.contains(&position)
 3018                    {
 3019                        let word_range = movement::surrounding_word(&display_map, position);
 3020                        if word_range.start < original_display_range.start {
 3021                            head = word_range.start.to_point(&display_map);
 3022                        } else {
 3023                            head = word_range.end.to_point(&display_map);
 3024                        }
 3025                    } else {
 3026                        head = position.to_point(&display_map);
 3027                    }
 3028
 3029                    if head <= original_buffer_range.start {
 3030                        tail = original_buffer_range.end;
 3031                    } else {
 3032                        tail = original_buffer_range.start;
 3033                    }
 3034                }
 3035                SelectMode::Line(original_range) => {
 3036                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 3037
 3038                    let position = display_map
 3039                        .clip_point(position, Bias::Left)
 3040                        .to_point(&display_map);
 3041                    let line_start = display_map.prev_line_boundary(position).0;
 3042                    let next_line_start = buffer.clip_point(
 3043                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3044                        Bias::Left,
 3045                    );
 3046
 3047                    if line_start < original_range.start {
 3048                        head = line_start
 3049                    } else {
 3050                        head = next_line_start
 3051                    }
 3052
 3053                    if head <= original_range.start {
 3054                        tail = original_range.end;
 3055                    } else {
 3056                        tail = original_range.start;
 3057                    }
 3058                }
 3059                SelectMode::All => {
 3060                    return;
 3061                }
 3062            };
 3063
 3064            if head < tail {
 3065                pending.start = buffer.anchor_before(head);
 3066                pending.end = buffer.anchor_before(tail);
 3067                pending.reversed = true;
 3068            } else {
 3069                pending.start = buffer.anchor_before(tail);
 3070                pending.end = buffer.anchor_before(head);
 3071                pending.reversed = false;
 3072            }
 3073
 3074            self.change_selections(None, window, cx, |s| {
 3075                s.set_pending(pending, mode);
 3076            });
 3077        } else {
 3078            log::error!("update_selection dispatched with no pending selection");
 3079            return;
 3080        }
 3081
 3082        self.apply_scroll_delta(scroll_delta, window, cx);
 3083        cx.notify();
 3084    }
 3085
 3086    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3087        self.columnar_selection_tail.take();
 3088        if self.selections.pending_anchor().is_some() {
 3089            let selections = self.selections.all::<usize>(cx);
 3090            self.change_selections(None, window, cx, |s| {
 3091                s.select(selections);
 3092                s.clear_pending();
 3093            });
 3094        }
 3095    }
 3096
 3097    fn select_columns(
 3098        &mut self,
 3099        tail: DisplayPoint,
 3100        head: DisplayPoint,
 3101        goal_column: u32,
 3102        display_map: &DisplaySnapshot,
 3103        window: &mut Window,
 3104        cx: &mut Context<Self>,
 3105    ) {
 3106        let start_row = cmp::min(tail.row(), head.row());
 3107        let end_row = cmp::max(tail.row(), head.row());
 3108        let start_column = cmp::min(tail.column(), goal_column);
 3109        let end_column = cmp::max(tail.column(), goal_column);
 3110        let reversed = start_column < tail.column();
 3111
 3112        let selection_ranges = (start_row.0..=end_row.0)
 3113            .map(DisplayRow)
 3114            .filter_map(|row| {
 3115                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3116                    let start = display_map
 3117                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3118                        .to_point(display_map);
 3119                    let end = display_map
 3120                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3121                        .to_point(display_map);
 3122                    if reversed {
 3123                        Some(end..start)
 3124                    } else {
 3125                        Some(start..end)
 3126                    }
 3127                } else {
 3128                    None
 3129                }
 3130            })
 3131            .collect::<Vec<_>>();
 3132
 3133        self.change_selections(None, window, cx, |s| {
 3134            s.select_ranges(selection_ranges);
 3135        });
 3136        cx.notify();
 3137    }
 3138
 3139    pub fn has_non_empty_selection(&self, cx: &mut App) -> bool {
 3140        self.selections
 3141            .all_adjusted(cx)
 3142            .iter()
 3143            .any(|selection| !selection.is_empty())
 3144    }
 3145
 3146    pub fn has_pending_nonempty_selection(&self) -> bool {
 3147        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3148            Some(Selection { start, end, .. }) => start != end,
 3149            None => false,
 3150        };
 3151
 3152        pending_nonempty_selection
 3153            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3154    }
 3155
 3156    pub fn has_pending_selection(&self) -> bool {
 3157        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3158    }
 3159
 3160    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 3161        self.selection_mark_mode = false;
 3162
 3163        if self.clear_expanded_diff_hunks(cx) {
 3164            cx.notify();
 3165            return;
 3166        }
 3167        if self.dismiss_menus_and_popups(true, window, cx) {
 3168            return;
 3169        }
 3170
 3171        if self.mode.is_full()
 3172            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 3173        {
 3174            return;
 3175        }
 3176
 3177        cx.propagate();
 3178    }
 3179
 3180    pub fn dismiss_menus_and_popups(
 3181        &mut self,
 3182        is_user_requested: bool,
 3183        window: &mut Window,
 3184        cx: &mut Context<Self>,
 3185    ) -> bool {
 3186        if self.take_rename(false, window, cx).is_some() {
 3187            return true;
 3188        }
 3189
 3190        if hide_hover(self, cx) {
 3191            return true;
 3192        }
 3193
 3194        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3195            return true;
 3196        }
 3197
 3198        if self.hide_context_menu(window, cx).is_some() {
 3199            return true;
 3200        }
 3201
 3202        if self.mouse_context_menu.take().is_some() {
 3203            return true;
 3204        }
 3205
 3206        if is_user_requested && self.discard_inline_completion(true, cx) {
 3207            return true;
 3208        }
 3209
 3210        if self.snippet_stack.pop().is_some() {
 3211            return true;
 3212        }
 3213
 3214        if self.mode.is_full() && matches!(self.active_diagnostics, ActiveDiagnostic::Group(_)) {
 3215            self.dismiss_diagnostics(cx);
 3216            return true;
 3217        }
 3218
 3219        false
 3220    }
 3221
 3222    fn linked_editing_ranges_for(
 3223        &self,
 3224        selection: Range<text::Anchor>,
 3225        cx: &App,
 3226    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 3227        if self.linked_edit_ranges.is_empty() {
 3228            return None;
 3229        }
 3230        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3231            selection.end.buffer_id.and_then(|end_buffer_id| {
 3232                if selection.start.buffer_id != Some(end_buffer_id) {
 3233                    return None;
 3234                }
 3235                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3236                let snapshot = buffer.read(cx).snapshot();
 3237                self.linked_edit_ranges
 3238                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3239                    .map(|ranges| (ranges, snapshot, buffer))
 3240            })?;
 3241        use text::ToOffset as TO;
 3242        // find offset from the start of current range to current cursor position
 3243        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3244
 3245        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3246        let start_difference = start_offset - start_byte_offset;
 3247        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3248        let end_difference = end_offset - start_byte_offset;
 3249        // Current range has associated linked ranges.
 3250        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3251        for range in linked_ranges.iter() {
 3252            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3253            let end_offset = start_offset + end_difference;
 3254            let start_offset = start_offset + start_difference;
 3255            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3256                continue;
 3257            }
 3258            if self.selections.disjoint_anchor_ranges().any(|s| {
 3259                if s.start.buffer_id != selection.start.buffer_id
 3260                    || s.end.buffer_id != selection.end.buffer_id
 3261                {
 3262                    return false;
 3263                }
 3264                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3265                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3266            }) {
 3267                continue;
 3268            }
 3269            let start = buffer_snapshot.anchor_after(start_offset);
 3270            let end = buffer_snapshot.anchor_after(end_offset);
 3271            linked_edits
 3272                .entry(buffer.clone())
 3273                .or_default()
 3274                .push(start..end);
 3275        }
 3276        Some(linked_edits)
 3277    }
 3278
 3279    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3280        let text: Arc<str> = text.into();
 3281
 3282        if self.read_only(cx) {
 3283            return;
 3284        }
 3285
 3286        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3287
 3288        let selections = self.selections.all_adjusted(cx);
 3289        let mut bracket_inserted = false;
 3290        let mut edits = Vec::new();
 3291        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3292        let mut new_selections = Vec::with_capacity(selections.len());
 3293        let mut new_autoclose_regions = Vec::new();
 3294        let snapshot = self.buffer.read(cx).read(cx);
 3295        let mut clear_linked_edit_ranges = false;
 3296
 3297        for (selection, autoclose_region) in
 3298            self.selections_with_autoclose_regions(selections, &snapshot)
 3299        {
 3300            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3301                // Determine if the inserted text matches the opening or closing
 3302                // bracket of any of this language's bracket pairs.
 3303                let mut bracket_pair = None;
 3304                let mut is_bracket_pair_start = false;
 3305                let mut is_bracket_pair_end = false;
 3306                if !text.is_empty() {
 3307                    let mut bracket_pair_matching_end = None;
 3308                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3309                    //  and they are removing the character that triggered IME popup.
 3310                    for (pair, enabled) in scope.brackets() {
 3311                        if !pair.close && !pair.surround {
 3312                            continue;
 3313                        }
 3314
 3315                        if enabled && pair.start.ends_with(text.as_ref()) {
 3316                            let prefix_len = pair.start.len() - text.len();
 3317                            let preceding_text_matches_prefix = prefix_len == 0
 3318                                || (selection.start.column >= (prefix_len as u32)
 3319                                    && snapshot.contains_str_at(
 3320                                        Point::new(
 3321                                            selection.start.row,
 3322                                            selection.start.column - (prefix_len as u32),
 3323                                        ),
 3324                                        &pair.start[..prefix_len],
 3325                                    ));
 3326                            if preceding_text_matches_prefix {
 3327                                bracket_pair = Some(pair.clone());
 3328                                is_bracket_pair_start = true;
 3329                                break;
 3330                            }
 3331                        }
 3332                        if pair.end.as_str() == text.as_ref() && bracket_pair_matching_end.is_none()
 3333                        {
 3334                            // take first bracket pair matching end, but don't break in case a later bracket
 3335                            // pair matches start
 3336                            bracket_pair_matching_end = Some(pair.clone());
 3337                        }
 3338                    }
 3339                    if bracket_pair.is_none() && bracket_pair_matching_end.is_some() {
 3340                        bracket_pair = Some(bracket_pair_matching_end.unwrap());
 3341                        is_bracket_pair_end = true;
 3342                    }
 3343                }
 3344
 3345                if let Some(bracket_pair) = bracket_pair {
 3346                    let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
 3347                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3348                    let auto_surround =
 3349                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3350                    if selection.is_empty() {
 3351                        if is_bracket_pair_start {
 3352                            // If the inserted text is a suffix of an opening bracket and the
 3353                            // selection is preceded by the rest of the opening bracket, then
 3354                            // insert the closing bracket.
 3355                            let following_text_allows_autoclose = snapshot
 3356                                .chars_at(selection.start)
 3357                                .next()
 3358                                .map_or(true, |c| scope.should_autoclose_before(c));
 3359
 3360                            let preceding_text_allows_autoclose = selection.start.column == 0
 3361                                || snapshot.reversed_chars_at(selection.start).next().map_or(
 3362                                    true,
 3363                                    |c| {
 3364                                        bracket_pair.start != bracket_pair.end
 3365                                            || !snapshot
 3366                                                .char_classifier_at(selection.start)
 3367                                                .is_word(c)
 3368                                    },
 3369                                );
 3370
 3371                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3372                                && bracket_pair.start.len() == 1
 3373                            {
 3374                                let target = bracket_pair.start.chars().next().unwrap();
 3375                                let current_line_count = snapshot
 3376                                    .reversed_chars_at(selection.start)
 3377                                    .take_while(|&c| c != '\n')
 3378                                    .filter(|&c| c == target)
 3379                                    .count();
 3380                                current_line_count % 2 == 1
 3381                            } else {
 3382                                false
 3383                            };
 3384
 3385                            if autoclose
 3386                                && bracket_pair.close
 3387                                && following_text_allows_autoclose
 3388                                && preceding_text_allows_autoclose
 3389                                && !is_closing_quote
 3390                            {
 3391                                let anchor = snapshot.anchor_before(selection.end);
 3392                                new_selections.push((selection.map(|_| anchor), text.len()));
 3393                                new_autoclose_regions.push((
 3394                                    anchor,
 3395                                    text.len(),
 3396                                    selection.id,
 3397                                    bracket_pair.clone(),
 3398                                ));
 3399                                edits.push((
 3400                                    selection.range(),
 3401                                    format!("{}{}", text, bracket_pair.end).into(),
 3402                                ));
 3403                                bracket_inserted = true;
 3404                                continue;
 3405                            }
 3406                        }
 3407
 3408                        if let Some(region) = autoclose_region {
 3409                            // If the selection is followed by an auto-inserted closing bracket,
 3410                            // then don't insert that closing bracket again; just move the selection
 3411                            // past the closing bracket.
 3412                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3413                                && text.as_ref() == region.pair.end.as_str();
 3414                            if should_skip {
 3415                                let anchor = snapshot.anchor_after(selection.end);
 3416                                new_selections
 3417                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3418                                continue;
 3419                            }
 3420                        }
 3421
 3422                        let always_treat_brackets_as_autoclosed = snapshot
 3423                            .language_settings_at(selection.start, cx)
 3424                            .always_treat_brackets_as_autoclosed;
 3425                        if always_treat_brackets_as_autoclosed
 3426                            && is_bracket_pair_end
 3427                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3428                        {
 3429                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3430                            // and the inserted text is a closing bracket and the selection is followed
 3431                            // by the closing bracket then move the selection past the closing bracket.
 3432                            let anchor = snapshot.anchor_after(selection.end);
 3433                            new_selections.push((selection.map(|_| anchor), text.len()));
 3434                            continue;
 3435                        }
 3436                    }
 3437                    // If an opening bracket is 1 character long and is typed while
 3438                    // text is selected, then surround that text with the bracket pair.
 3439                    else if auto_surround
 3440                        && bracket_pair.surround
 3441                        && is_bracket_pair_start
 3442                        && bracket_pair.start.chars().count() == 1
 3443                    {
 3444                        edits.push((selection.start..selection.start, text.clone()));
 3445                        edits.push((
 3446                            selection.end..selection.end,
 3447                            bracket_pair.end.as_str().into(),
 3448                        ));
 3449                        bracket_inserted = true;
 3450                        new_selections.push((
 3451                            Selection {
 3452                                id: selection.id,
 3453                                start: snapshot.anchor_after(selection.start),
 3454                                end: snapshot.anchor_before(selection.end),
 3455                                reversed: selection.reversed,
 3456                                goal: selection.goal,
 3457                            },
 3458                            0,
 3459                        ));
 3460                        continue;
 3461                    }
 3462                }
 3463            }
 3464
 3465            if self.auto_replace_emoji_shortcode
 3466                && selection.is_empty()
 3467                && text.as_ref().ends_with(':')
 3468            {
 3469                if let Some(possible_emoji_short_code) =
 3470                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3471                {
 3472                    if !possible_emoji_short_code.is_empty() {
 3473                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3474                            let emoji_shortcode_start = Point::new(
 3475                                selection.start.row,
 3476                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3477                            );
 3478
 3479                            // Remove shortcode from buffer
 3480                            edits.push((
 3481                                emoji_shortcode_start..selection.start,
 3482                                "".to_string().into(),
 3483                            ));
 3484                            new_selections.push((
 3485                                Selection {
 3486                                    id: selection.id,
 3487                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3488                                    end: snapshot.anchor_before(selection.start),
 3489                                    reversed: selection.reversed,
 3490                                    goal: selection.goal,
 3491                                },
 3492                                0,
 3493                            ));
 3494
 3495                            // Insert emoji
 3496                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3497                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3498                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3499
 3500                            continue;
 3501                        }
 3502                    }
 3503                }
 3504            }
 3505
 3506            // If not handling any auto-close operation, then just replace the selected
 3507            // text with the given input and move the selection to the end of the
 3508            // newly inserted text.
 3509            let anchor = snapshot.anchor_after(selection.end);
 3510            if !self.linked_edit_ranges.is_empty() {
 3511                let start_anchor = snapshot.anchor_before(selection.start);
 3512
 3513                let is_word_char = text.chars().next().map_or(true, |char| {
 3514                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3515                    classifier.is_word(char)
 3516                });
 3517
 3518                if is_word_char {
 3519                    if let Some(ranges) = self
 3520                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3521                    {
 3522                        for (buffer, edits) in ranges {
 3523                            linked_edits
 3524                                .entry(buffer.clone())
 3525                                .or_default()
 3526                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3527                        }
 3528                    }
 3529                } else {
 3530                    clear_linked_edit_ranges = true;
 3531                }
 3532            }
 3533
 3534            new_selections.push((selection.map(|_| anchor), 0));
 3535            edits.push((selection.start..selection.end, text.clone()));
 3536        }
 3537
 3538        drop(snapshot);
 3539
 3540        self.transact(window, cx, |this, window, cx| {
 3541            if clear_linked_edit_ranges {
 3542                this.linked_edit_ranges.clear();
 3543            }
 3544            let initial_buffer_versions =
 3545                jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
 3546
 3547            this.buffer.update(cx, |buffer, cx| {
 3548                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3549            });
 3550            for (buffer, edits) in linked_edits {
 3551                buffer.update(cx, |buffer, cx| {
 3552                    let snapshot = buffer.snapshot();
 3553                    let edits = edits
 3554                        .into_iter()
 3555                        .map(|(range, text)| {
 3556                            use text::ToPoint as TP;
 3557                            let end_point = TP::to_point(&range.end, &snapshot);
 3558                            let start_point = TP::to_point(&range.start, &snapshot);
 3559                            (start_point..end_point, text)
 3560                        })
 3561                        .sorted_by_key(|(range, _)| range.start);
 3562                    buffer.edit(edits, None, cx);
 3563                })
 3564            }
 3565            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3566            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3567            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3568            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3569                .zip(new_selection_deltas)
 3570                .map(|(selection, delta)| Selection {
 3571                    id: selection.id,
 3572                    start: selection.start + delta,
 3573                    end: selection.end + delta,
 3574                    reversed: selection.reversed,
 3575                    goal: SelectionGoal::None,
 3576                })
 3577                .collect::<Vec<_>>();
 3578
 3579            let mut i = 0;
 3580            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3581                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3582                let start = map.buffer_snapshot.anchor_before(position);
 3583                let end = map.buffer_snapshot.anchor_after(position);
 3584                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3585                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3586                        Ordering::Less => i += 1,
 3587                        Ordering::Greater => break,
 3588                        Ordering::Equal => {
 3589                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3590                                Ordering::Less => i += 1,
 3591                                Ordering::Equal => break,
 3592                                Ordering::Greater => break,
 3593                            }
 3594                        }
 3595                    }
 3596                }
 3597                this.autoclose_regions.insert(
 3598                    i,
 3599                    AutocloseRegion {
 3600                        selection_id,
 3601                        range: start..end,
 3602                        pair,
 3603                    },
 3604                );
 3605            }
 3606
 3607            let had_active_inline_completion = this.has_active_inline_completion();
 3608            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3609                s.select(new_selections)
 3610            });
 3611
 3612            if !bracket_inserted {
 3613                if let Some(on_type_format_task) =
 3614                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3615                {
 3616                    on_type_format_task.detach_and_log_err(cx);
 3617                }
 3618            }
 3619
 3620            let editor_settings = EditorSettings::get_global(cx);
 3621            if bracket_inserted
 3622                && (editor_settings.auto_signature_help
 3623                    || editor_settings.show_signature_help_after_edits)
 3624            {
 3625                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3626            }
 3627
 3628            let trigger_in_words =
 3629                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3630            if this.hard_wrap.is_some() {
 3631                let latest: Range<Point> = this.selections.newest(cx).range();
 3632                if latest.is_empty()
 3633                    && this
 3634                        .buffer()
 3635                        .read(cx)
 3636                        .snapshot(cx)
 3637                        .line_len(MultiBufferRow(latest.start.row))
 3638                        == latest.start.column
 3639                {
 3640                    this.rewrap_impl(
 3641                        RewrapOptions {
 3642                            override_language_settings: true,
 3643                            preserve_existing_whitespace: true,
 3644                        },
 3645                        cx,
 3646                    )
 3647                }
 3648            }
 3649            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3650            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3651            this.refresh_inline_completion(true, false, window, cx);
 3652            jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
 3653        });
 3654    }
 3655
 3656    fn find_possible_emoji_shortcode_at_position(
 3657        snapshot: &MultiBufferSnapshot,
 3658        position: Point,
 3659    ) -> Option<String> {
 3660        let mut chars = Vec::new();
 3661        let mut found_colon = false;
 3662        for char in snapshot.reversed_chars_at(position).take(100) {
 3663            // Found a possible emoji shortcode in the middle of the buffer
 3664            if found_colon {
 3665                if char.is_whitespace() {
 3666                    chars.reverse();
 3667                    return Some(chars.iter().collect());
 3668                }
 3669                // If the previous character is not a whitespace, we are in the middle of a word
 3670                // and we only want to complete the shortcode if the word is made up of other emojis
 3671                let mut containing_word = String::new();
 3672                for ch in snapshot
 3673                    .reversed_chars_at(position)
 3674                    .skip(chars.len() + 1)
 3675                    .take(100)
 3676                {
 3677                    if ch.is_whitespace() {
 3678                        break;
 3679                    }
 3680                    containing_word.push(ch);
 3681                }
 3682                let containing_word = containing_word.chars().rev().collect::<String>();
 3683                if util::word_consists_of_emojis(containing_word.as_str()) {
 3684                    chars.reverse();
 3685                    return Some(chars.iter().collect());
 3686                }
 3687            }
 3688
 3689            if char.is_whitespace() || !char.is_ascii() {
 3690                return None;
 3691            }
 3692            if char == ':' {
 3693                found_colon = true;
 3694            } else {
 3695                chars.push(char);
 3696            }
 3697        }
 3698        // Found a possible emoji shortcode at the beginning of the buffer
 3699        chars.reverse();
 3700        Some(chars.iter().collect())
 3701    }
 3702
 3703    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3704        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3705        self.transact(window, cx, |this, window, cx| {
 3706            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3707                let selections = this.selections.all::<usize>(cx);
 3708                let multi_buffer = this.buffer.read(cx);
 3709                let buffer = multi_buffer.snapshot(cx);
 3710                selections
 3711                    .iter()
 3712                    .map(|selection| {
 3713                        let start_point = selection.start.to_point(&buffer);
 3714                        let mut indent =
 3715                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3716                        indent.len = cmp::min(indent.len, start_point.column);
 3717                        let start = selection.start;
 3718                        let end = selection.end;
 3719                        let selection_is_empty = start == end;
 3720                        let language_scope = buffer.language_scope_at(start);
 3721                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3722                            &language_scope
 3723                        {
 3724                            let insert_extra_newline =
 3725                                insert_extra_newline_brackets(&buffer, start..end, language)
 3726                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3727
 3728                            // Comment extension on newline is allowed only for cursor selections
 3729                            let comment_delimiter = maybe!({
 3730                                if !selection_is_empty {
 3731                                    return None;
 3732                                }
 3733
 3734                                if !multi_buffer.language_settings(cx).extend_comment_on_newline {
 3735                                    return None;
 3736                                }
 3737
 3738                                let delimiters = language.line_comment_prefixes();
 3739                                let max_len_of_delimiter =
 3740                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3741                                let (snapshot, range) =
 3742                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3743
 3744                                let mut index_of_first_non_whitespace = 0;
 3745                                let comment_candidate = snapshot
 3746                                    .chars_for_range(range)
 3747                                    .skip_while(|c| {
 3748                                        let should_skip = c.is_whitespace();
 3749                                        if should_skip {
 3750                                            index_of_first_non_whitespace += 1;
 3751                                        }
 3752                                        should_skip
 3753                                    })
 3754                                    .take(max_len_of_delimiter)
 3755                                    .collect::<String>();
 3756                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3757                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3758                                })?;
 3759                                let cursor_is_placed_after_comment_marker =
 3760                                    index_of_first_non_whitespace + comment_prefix.len()
 3761                                        <= start_point.column as usize;
 3762                                if cursor_is_placed_after_comment_marker {
 3763                                    Some(comment_prefix.clone())
 3764                                } else {
 3765                                    None
 3766                                }
 3767                            });
 3768                            (comment_delimiter, insert_extra_newline)
 3769                        } else {
 3770                            (None, false)
 3771                        };
 3772
 3773                        let capacity_for_delimiter = comment_delimiter
 3774                            .as_deref()
 3775                            .map(str::len)
 3776                            .unwrap_or_default();
 3777                        let mut new_text =
 3778                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3779                        new_text.push('\n');
 3780                        new_text.extend(indent.chars());
 3781                        if let Some(delimiter) = &comment_delimiter {
 3782                            new_text.push_str(delimiter);
 3783                        }
 3784                        if insert_extra_newline {
 3785                            new_text = new_text.repeat(2);
 3786                        }
 3787
 3788                        let anchor = buffer.anchor_after(end);
 3789                        let new_selection = selection.map(|_| anchor);
 3790                        (
 3791                            (start..end, new_text),
 3792                            (insert_extra_newline, new_selection),
 3793                        )
 3794                    })
 3795                    .unzip()
 3796            };
 3797
 3798            this.edit_with_autoindent(edits, cx);
 3799            let buffer = this.buffer.read(cx).snapshot(cx);
 3800            let new_selections = selection_fixup_info
 3801                .into_iter()
 3802                .map(|(extra_newline_inserted, new_selection)| {
 3803                    let mut cursor = new_selection.end.to_point(&buffer);
 3804                    if extra_newline_inserted {
 3805                        cursor.row -= 1;
 3806                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3807                    }
 3808                    new_selection.map(|_| cursor)
 3809                })
 3810                .collect();
 3811
 3812            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3813                s.select(new_selections)
 3814            });
 3815            this.refresh_inline_completion(true, false, window, cx);
 3816        });
 3817    }
 3818
 3819    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3820        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3821
 3822        let buffer = self.buffer.read(cx);
 3823        let snapshot = buffer.snapshot(cx);
 3824
 3825        let mut edits = Vec::new();
 3826        let mut rows = Vec::new();
 3827
 3828        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3829            let cursor = selection.head();
 3830            let row = cursor.row;
 3831
 3832            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3833
 3834            let newline = "\n".to_string();
 3835            edits.push((start_of_line..start_of_line, newline));
 3836
 3837            rows.push(row + rows_inserted as u32);
 3838        }
 3839
 3840        self.transact(window, cx, |editor, window, cx| {
 3841            editor.edit(edits, cx);
 3842
 3843            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3844                let mut index = 0;
 3845                s.move_cursors_with(|map, _, _| {
 3846                    let row = rows[index];
 3847                    index += 1;
 3848
 3849                    let point = Point::new(row, 0);
 3850                    let boundary = map.next_line_boundary(point).1;
 3851                    let clipped = map.clip_point(boundary, Bias::Left);
 3852
 3853                    (clipped, SelectionGoal::None)
 3854                });
 3855            });
 3856
 3857            let mut indent_edits = Vec::new();
 3858            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3859            for row in rows {
 3860                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3861                for (row, indent) in indents {
 3862                    if indent.len == 0 {
 3863                        continue;
 3864                    }
 3865
 3866                    let text = match indent.kind {
 3867                        IndentKind::Space => " ".repeat(indent.len as usize),
 3868                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3869                    };
 3870                    let point = Point::new(row.0, 0);
 3871                    indent_edits.push((point..point, text));
 3872                }
 3873            }
 3874            editor.edit(indent_edits, cx);
 3875        });
 3876    }
 3877
 3878    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3879        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3880
 3881        let buffer = self.buffer.read(cx);
 3882        let snapshot = buffer.snapshot(cx);
 3883
 3884        let mut edits = Vec::new();
 3885        let mut rows = Vec::new();
 3886        let mut rows_inserted = 0;
 3887
 3888        for selection in self.selections.all_adjusted(cx) {
 3889            let cursor = selection.head();
 3890            let row = cursor.row;
 3891
 3892            let point = Point::new(row + 1, 0);
 3893            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3894
 3895            let newline = "\n".to_string();
 3896            edits.push((start_of_line..start_of_line, newline));
 3897
 3898            rows_inserted += 1;
 3899            rows.push(row + rows_inserted);
 3900        }
 3901
 3902        self.transact(window, cx, |editor, window, cx| {
 3903            editor.edit(edits, cx);
 3904
 3905            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3906                let mut index = 0;
 3907                s.move_cursors_with(|map, _, _| {
 3908                    let row = rows[index];
 3909                    index += 1;
 3910
 3911                    let point = Point::new(row, 0);
 3912                    let boundary = map.next_line_boundary(point).1;
 3913                    let clipped = map.clip_point(boundary, Bias::Left);
 3914
 3915                    (clipped, SelectionGoal::None)
 3916                });
 3917            });
 3918
 3919            let mut indent_edits = Vec::new();
 3920            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3921            for row in rows {
 3922                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3923                for (row, indent) in indents {
 3924                    if indent.len == 0 {
 3925                        continue;
 3926                    }
 3927
 3928                    let text = match indent.kind {
 3929                        IndentKind::Space => " ".repeat(indent.len as usize),
 3930                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3931                    };
 3932                    let point = Point::new(row.0, 0);
 3933                    indent_edits.push((point..point, text));
 3934                }
 3935            }
 3936            editor.edit(indent_edits, cx);
 3937        });
 3938    }
 3939
 3940    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3941        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3942            original_indent_columns: Vec::new(),
 3943        });
 3944        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3945    }
 3946
 3947    fn insert_with_autoindent_mode(
 3948        &mut self,
 3949        text: &str,
 3950        autoindent_mode: Option<AutoindentMode>,
 3951        window: &mut Window,
 3952        cx: &mut Context<Self>,
 3953    ) {
 3954        if self.read_only(cx) {
 3955            return;
 3956        }
 3957
 3958        let text: Arc<str> = text.into();
 3959        self.transact(window, cx, |this, window, cx| {
 3960            let old_selections = this.selections.all_adjusted(cx);
 3961            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3962                let anchors = {
 3963                    let snapshot = buffer.read(cx);
 3964                    old_selections
 3965                        .iter()
 3966                        .map(|s| {
 3967                            let anchor = snapshot.anchor_after(s.head());
 3968                            s.map(|_| anchor)
 3969                        })
 3970                        .collect::<Vec<_>>()
 3971                };
 3972                buffer.edit(
 3973                    old_selections
 3974                        .iter()
 3975                        .map(|s| (s.start..s.end, text.clone())),
 3976                    autoindent_mode,
 3977                    cx,
 3978                );
 3979                anchors
 3980            });
 3981
 3982            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3983                s.select_anchors(selection_anchors);
 3984            });
 3985
 3986            cx.notify();
 3987        });
 3988    }
 3989
 3990    fn trigger_completion_on_input(
 3991        &mut self,
 3992        text: &str,
 3993        trigger_in_words: bool,
 3994        window: &mut Window,
 3995        cx: &mut Context<Self>,
 3996    ) {
 3997        let ignore_completion_provider = self
 3998            .context_menu
 3999            .borrow()
 4000            .as_ref()
 4001            .map(|menu| match menu {
 4002                CodeContextMenu::Completions(completions_menu) => {
 4003                    completions_menu.ignore_completion_provider
 4004                }
 4005                CodeContextMenu::CodeActions(_) => false,
 4006            })
 4007            .unwrap_or(false);
 4008
 4009        if ignore_completion_provider {
 4010            self.show_word_completions(&ShowWordCompletions, window, cx);
 4011        } else if self.is_completion_trigger(text, trigger_in_words, cx) {
 4012            self.show_completions(
 4013                &ShowCompletions {
 4014                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 4015                },
 4016                window,
 4017                cx,
 4018            );
 4019        } else {
 4020            self.hide_context_menu(window, cx);
 4021        }
 4022    }
 4023
 4024    fn is_completion_trigger(
 4025        &self,
 4026        text: &str,
 4027        trigger_in_words: bool,
 4028        cx: &mut Context<Self>,
 4029    ) -> bool {
 4030        let position = self.selections.newest_anchor().head();
 4031        let multibuffer = self.buffer.read(cx);
 4032        let Some(buffer) = position
 4033            .buffer_id
 4034            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 4035        else {
 4036            return false;
 4037        };
 4038
 4039        if let Some(completion_provider) = &self.completion_provider {
 4040            completion_provider.is_completion_trigger(
 4041                &buffer,
 4042                position.text_anchor,
 4043                text,
 4044                trigger_in_words,
 4045                cx,
 4046            )
 4047        } else {
 4048            false
 4049        }
 4050    }
 4051
 4052    /// If any empty selections is touching the start of its innermost containing autoclose
 4053    /// region, expand it to select the brackets.
 4054    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4055        let selections = self.selections.all::<usize>(cx);
 4056        let buffer = self.buffer.read(cx).read(cx);
 4057        let new_selections = self
 4058            .selections_with_autoclose_regions(selections, &buffer)
 4059            .map(|(mut selection, region)| {
 4060                if !selection.is_empty() {
 4061                    return selection;
 4062                }
 4063
 4064                if let Some(region) = region {
 4065                    let mut range = region.range.to_offset(&buffer);
 4066                    if selection.start == range.start && range.start >= region.pair.start.len() {
 4067                        range.start -= region.pair.start.len();
 4068                        if buffer.contains_str_at(range.start, &region.pair.start)
 4069                            && buffer.contains_str_at(range.end, &region.pair.end)
 4070                        {
 4071                            range.end += region.pair.end.len();
 4072                            selection.start = range.start;
 4073                            selection.end = range.end;
 4074
 4075                            return selection;
 4076                        }
 4077                    }
 4078                }
 4079
 4080                let always_treat_brackets_as_autoclosed = buffer
 4081                    .language_settings_at(selection.start, cx)
 4082                    .always_treat_brackets_as_autoclosed;
 4083
 4084                if !always_treat_brackets_as_autoclosed {
 4085                    return selection;
 4086                }
 4087
 4088                if let Some(scope) = buffer.language_scope_at(selection.start) {
 4089                    for (pair, enabled) in scope.brackets() {
 4090                        if !enabled || !pair.close {
 4091                            continue;
 4092                        }
 4093
 4094                        if buffer.contains_str_at(selection.start, &pair.end) {
 4095                            let pair_start_len = pair.start.len();
 4096                            if buffer.contains_str_at(
 4097                                selection.start.saturating_sub(pair_start_len),
 4098                                &pair.start,
 4099                            ) {
 4100                                selection.start -= pair_start_len;
 4101                                selection.end += pair.end.len();
 4102
 4103                                return selection;
 4104                            }
 4105                        }
 4106                    }
 4107                }
 4108
 4109                selection
 4110            })
 4111            .collect();
 4112
 4113        drop(buffer);
 4114        self.change_selections(None, window, cx, |selections| {
 4115            selections.select(new_selections)
 4116        });
 4117    }
 4118
 4119    /// Iterate the given selections, and for each one, find the smallest surrounding
 4120    /// autoclose region. This uses the ordering of the selections and the autoclose
 4121    /// regions to avoid repeated comparisons.
 4122    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4123        &'a self,
 4124        selections: impl IntoIterator<Item = Selection<D>>,
 4125        buffer: &'a MultiBufferSnapshot,
 4126    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4127        let mut i = 0;
 4128        let mut regions = self.autoclose_regions.as_slice();
 4129        selections.into_iter().map(move |selection| {
 4130            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4131
 4132            let mut enclosing = None;
 4133            while let Some(pair_state) = regions.get(i) {
 4134                if pair_state.range.end.to_offset(buffer) < range.start {
 4135                    regions = &regions[i + 1..];
 4136                    i = 0;
 4137                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4138                    break;
 4139                } else {
 4140                    if pair_state.selection_id == selection.id {
 4141                        enclosing = Some(pair_state);
 4142                    }
 4143                    i += 1;
 4144                }
 4145            }
 4146
 4147            (selection, enclosing)
 4148        })
 4149    }
 4150
 4151    /// Remove any autoclose regions that no longer contain their selection.
 4152    fn invalidate_autoclose_regions(
 4153        &mut self,
 4154        mut selections: &[Selection<Anchor>],
 4155        buffer: &MultiBufferSnapshot,
 4156    ) {
 4157        self.autoclose_regions.retain(|state| {
 4158            let mut i = 0;
 4159            while let Some(selection) = selections.get(i) {
 4160                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4161                    selections = &selections[1..];
 4162                    continue;
 4163                }
 4164                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4165                    break;
 4166                }
 4167                if selection.id == state.selection_id {
 4168                    return true;
 4169                } else {
 4170                    i += 1;
 4171                }
 4172            }
 4173            false
 4174        });
 4175    }
 4176
 4177    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4178        let offset = position.to_offset(buffer);
 4179        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4180        if offset > word_range.start && kind == Some(CharKind::Word) {
 4181            Some(
 4182                buffer
 4183                    .text_for_range(word_range.start..offset)
 4184                    .collect::<String>(),
 4185            )
 4186        } else {
 4187            None
 4188        }
 4189    }
 4190
 4191    pub fn toggle_inlay_hints(
 4192        &mut self,
 4193        _: &ToggleInlayHints,
 4194        _: &mut Window,
 4195        cx: &mut Context<Self>,
 4196    ) {
 4197        self.refresh_inlay_hints(
 4198            InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
 4199            cx,
 4200        );
 4201    }
 4202
 4203    pub fn inlay_hints_enabled(&self) -> bool {
 4204        self.inlay_hint_cache.enabled
 4205    }
 4206
 4207    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 4208        if self.semantics_provider.is_none() || !self.mode.is_full() {
 4209            return;
 4210        }
 4211
 4212        let reason_description = reason.description();
 4213        let ignore_debounce = matches!(
 4214            reason,
 4215            InlayHintRefreshReason::SettingsChange(_)
 4216                | InlayHintRefreshReason::Toggle(_)
 4217                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4218                | InlayHintRefreshReason::ModifiersChanged(_)
 4219        );
 4220        let (invalidate_cache, required_languages) = match reason {
 4221            InlayHintRefreshReason::ModifiersChanged(enabled) => {
 4222                match self.inlay_hint_cache.modifiers_override(enabled) {
 4223                    Some(enabled) => {
 4224                        if enabled {
 4225                            (InvalidationStrategy::RefreshRequested, None)
 4226                        } else {
 4227                            self.splice_inlays(
 4228                                &self
 4229                                    .visible_inlay_hints(cx)
 4230                                    .iter()
 4231                                    .map(|inlay| inlay.id)
 4232                                    .collect::<Vec<InlayId>>(),
 4233                                Vec::new(),
 4234                                cx,
 4235                            );
 4236                            return;
 4237                        }
 4238                    }
 4239                    None => return,
 4240                }
 4241            }
 4242            InlayHintRefreshReason::Toggle(enabled) => {
 4243                if self.inlay_hint_cache.toggle(enabled) {
 4244                    if enabled {
 4245                        (InvalidationStrategy::RefreshRequested, None)
 4246                    } else {
 4247                        self.splice_inlays(
 4248                            &self
 4249                                .visible_inlay_hints(cx)
 4250                                .iter()
 4251                                .map(|inlay| inlay.id)
 4252                                .collect::<Vec<InlayId>>(),
 4253                            Vec::new(),
 4254                            cx,
 4255                        );
 4256                        return;
 4257                    }
 4258                } else {
 4259                    return;
 4260                }
 4261            }
 4262            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4263                match self.inlay_hint_cache.update_settings(
 4264                    &self.buffer,
 4265                    new_settings,
 4266                    self.visible_inlay_hints(cx),
 4267                    cx,
 4268                ) {
 4269                    ControlFlow::Break(Some(InlaySplice {
 4270                        to_remove,
 4271                        to_insert,
 4272                    })) => {
 4273                        self.splice_inlays(&to_remove, to_insert, cx);
 4274                        return;
 4275                    }
 4276                    ControlFlow::Break(None) => return,
 4277                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4278                }
 4279            }
 4280            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4281                if let Some(InlaySplice {
 4282                    to_remove,
 4283                    to_insert,
 4284                }) = self.inlay_hint_cache.remove_excerpts(&excerpts_removed)
 4285                {
 4286                    self.splice_inlays(&to_remove, to_insert, cx);
 4287                }
 4288                self.display_map.update(cx, |display_map, _| {
 4289                    display_map.remove_inlays_for_excerpts(&excerpts_removed)
 4290                });
 4291                return;
 4292            }
 4293            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4294            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4295                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4296            }
 4297            InlayHintRefreshReason::RefreshRequested => {
 4298                (InvalidationStrategy::RefreshRequested, None)
 4299            }
 4300        };
 4301
 4302        if let Some(InlaySplice {
 4303            to_remove,
 4304            to_insert,
 4305        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4306            reason_description,
 4307            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4308            invalidate_cache,
 4309            ignore_debounce,
 4310            cx,
 4311        ) {
 4312            self.splice_inlays(&to_remove, to_insert, cx);
 4313        }
 4314    }
 4315
 4316    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 4317        self.display_map
 4318            .read(cx)
 4319            .current_inlays()
 4320            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4321            .cloned()
 4322            .collect()
 4323    }
 4324
 4325    pub fn excerpts_for_inlay_hints_query(
 4326        &self,
 4327        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4328        cx: &mut Context<Editor>,
 4329    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 4330        let Some(project) = self.project.as_ref() else {
 4331            return HashMap::default();
 4332        };
 4333        let project = project.read(cx);
 4334        let multi_buffer = self.buffer().read(cx);
 4335        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4336        let multi_buffer_visible_start = self
 4337            .scroll_manager
 4338            .anchor()
 4339            .anchor
 4340            .to_point(&multi_buffer_snapshot);
 4341        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4342            multi_buffer_visible_start
 4343                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4344            Bias::Left,
 4345        );
 4346        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4347        multi_buffer_snapshot
 4348            .range_to_buffer_ranges(multi_buffer_visible_range)
 4349            .into_iter()
 4350            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4351            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 4352                let buffer_file = project::File::from_dyn(buffer.file())?;
 4353                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4354                let worktree_entry = buffer_worktree
 4355                    .read(cx)
 4356                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4357                if worktree_entry.is_ignored {
 4358                    return None;
 4359                }
 4360
 4361                let language = buffer.language()?;
 4362                if let Some(restrict_to_languages) = restrict_to_languages {
 4363                    if !restrict_to_languages.contains(language) {
 4364                        return None;
 4365                    }
 4366                }
 4367                Some((
 4368                    excerpt_id,
 4369                    (
 4370                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 4371                        buffer.version().clone(),
 4372                        excerpt_visible_range,
 4373                    ),
 4374                ))
 4375            })
 4376            .collect()
 4377    }
 4378
 4379    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 4380        TextLayoutDetails {
 4381            text_system: window.text_system().clone(),
 4382            editor_style: self.style.clone().unwrap(),
 4383            rem_size: window.rem_size(),
 4384            scroll_anchor: self.scroll_manager.anchor(),
 4385            visible_rows: self.visible_line_count(),
 4386            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4387        }
 4388    }
 4389
 4390    pub fn splice_inlays(
 4391        &self,
 4392        to_remove: &[InlayId],
 4393        to_insert: Vec<Inlay>,
 4394        cx: &mut Context<Self>,
 4395    ) {
 4396        self.display_map.update(cx, |display_map, cx| {
 4397            display_map.splice_inlays(to_remove, to_insert, cx)
 4398        });
 4399        cx.notify();
 4400    }
 4401
 4402    fn trigger_on_type_formatting(
 4403        &self,
 4404        input: String,
 4405        window: &mut Window,
 4406        cx: &mut Context<Self>,
 4407    ) -> Option<Task<Result<()>>> {
 4408        if input.len() != 1 {
 4409            return None;
 4410        }
 4411
 4412        let project = self.project.as_ref()?;
 4413        let position = self.selections.newest_anchor().head();
 4414        let (buffer, buffer_position) = self
 4415            .buffer
 4416            .read(cx)
 4417            .text_anchor_for_position(position, cx)?;
 4418
 4419        let settings = language_settings::language_settings(
 4420            buffer
 4421                .read(cx)
 4422                .language_at(buffer_position)
 4423                .map(|l| l.name()),
 4424            buffer.read(cx).file(),
 4425            cx,
 4426        );
 4427        if !settings.use_on_type_format {
 4428            return None;
 4429        }
 4430
 4431        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4432        // hence we do LSP request & edit on host side only — add formats to host's history.
 4433        let push_to_lsp_host_history = true;
 4434        // If this is not the host, append its history with new edits.
 4435        let push_to_client_history = project.read(cx).is_via_collab();
 4436
 4437        let on_type_formatting = project.update(cx, |project, cx| {
 4438            project.on_type_format(
 4439                buffer.clone(),
 4440                buffer_position,
 4441                input,
 4442                push_to_lsp_host_history,
 4443                cx,
 4444            )
 4445        });
 4446        Some(cx.spawn_in(window, async move |editor, cx| {
 4447            if let Some(transaction) = on_type_formatting.await? {
 4448                if push_to_client_history {
 4449                    buffer
 4450                        .update(cx, |buffer, _| {
 4451                            buffer.push_transaction(transaction, Instant::now());
 4452                            buffer.finalize_last_transaction();
 4453                        })
 4454                        .ok();
 4455                }
 4456                editor.update(cx, |editor, cx| {
 4457                    editor.refresh_document_highlights(cx);
 4458                })?;
 4459            }
 4460            Ok(())
 4461        }))
 4462    }
 4463
 4464    pub fn show_word_completions(
 4465        &mut self,
 4466        _: &ShowWordCompletions,
 4467        window: &mut Window,
 4468        cx: &mut Context<Self>,
 4469    ) {
 4470        self.open_completions_menu(true, None, window, cx);
 4471    }
 4472
 4473    pub fn show_completions(
 4474        &mut self,
 4475        options: &ShowCompletions,
 4476        window: &mut Window,
 4477        cx: &mut Context<Self>,
 4478    ) {
 4479        self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
 4480    }
 4481
 4482    fn open_completions_menu(
 4483        &mut self,
 4484        ignore_completion_provider: bool,
 4485        trigger: Option<&str>,
 4486        window: &mut Window,
 4487        cx: &mut Context<Self>,
 4488    ) {
 4489        if self.pending_rename.is_some() {
 4490            return;
 4491        }
 4492        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 4493            return;
 4494        }
 4495
 4496        let position = self.selections.newest_anchor().head();
 4497        if position.diff_base_anchor.is_some() {
 4498            return;
 4499        }
 4500        let (buffer, buffer_position) =
 4501            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4502                output
 4503            } else {
 4504                return;
 4505            };
 4506        let buffer_snapshot = buffer.read(cx).snapshot();
 4507        let show_completion_documentation = buffer_snapshot
 4508            .settings_at(buffer_position, cx)
 4509            .show_completion_documentation;
 4510
 4511        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4512
 4513        let trigger_kind = match trigger {
 4514            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4515                CompletionTriggerKind::TRIGGER_CHARACTER
 4516            }
 4517            _ => CompletionTriggerKind::INVOKED,
 4518        };
 4519        let completion_context = CompletionContext {
 4520            trigger_character: trigger.and_then(|trigger| {
 4521                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4522                    Some(String::from(trigger))
 4523                } else {
 4524                    None
 4525                }
 4526            }),
 4527            trigger_kind,
 4528        };
 4529
 4530        let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
 4531        let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
 4532            let word_to_exclude = buffer_snapshot
 4533                .text_for_range(old_range.clone())
 4534                .collect::<String>();
 4535            (
 4536                buffer_snapshot.anchor_before(old_range.start)
 4537                    ..buffer_snapshot.anchor_after(old_range.end),
 4538                Some(word_to_exclude),
 4539            )
 4540        } else {
 4541            (buffer_position..buffer_position, None)
 4542        };
 4543
 4544        let completion_settings = language_settings(
 4545            buffer_snapshot
 4546                .language_at(buffer_position)
 4547                .map(|language| language.name()),
 4548            buffer_snapshot.file(),
 4549            cx,
 4550        )
 4551        .completions;
 4552
 4553        // The document can be large, so stay in reasonable bounds when searching for words,
 4554        // otherwise completion pop-up might be slow to appear.
 4555        const WORD_LOOKUP_ROWS: u32 = 5_000;
 4556        let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
 4557        let min_word_search = buffer_snapshot.clip_point(
 4558            Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
 4559            Bias::Left,
 4560        );
 4561        let max_word_search = buffer_snapshot.clip_point(
 4562            Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
 4563            Bias::Right,
 4564        );
 4565        let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
 4566            ..buffer_snapshot.point_to_offset(max_word_search);
 4567
 4568        let provider = self
 4569            .completion_provider
 4570            .as_ref()
 4571            .filter(|_| !ignore_completion_provider);
 4572        let skip_digits = query
 4573            .as_ref()
 4574            .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
 4575
 4576        let (mut words, provided_completions) = match provider {
 4577            Some(provider) => {
 4578                let completions = provider.completions(
 4579                    position.excerpt_id,
 4580                    &buffer,
 4581                    buffer_position,
 4582                    completion_context,
 4583                    window,
 4584                    cx,
 4585                );
 4586
 4587                let words = match completion_settings.words {
 4588                    WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
 4589                    WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
 4590                        .background_spawn(async move {
 4591                            buffer_snapshot.words_in_range(WordsQuery {
 4592                                fuzzy_contents: None,
 4593                                range: word_search_range,
 4594                                skip_digits,
 4595                            })
 4596                        }),
 4597                };
 4598
 4599                (words, completions)
 4600            }
 4601            None => (
 4602                cx.background_spawn(async move {
 4603                    buffer_snapshot.words_in_range(WordsQuery {
 4604                        fuzzy_contents: None,
 4605                        range: word_search_range,
 4606                        skip_digits,
 4607                    })
 4608                }),
 4609                Task::ready(Ok(None)),
 4610            ),
 4611        };
 4612
 4613        let sort_completions = provider
 4614            .as_ref()
 4615            .map_or(false, |provider| provider.sort_completions());
 4616
 4617        let filter_completions = provider
 4618            .as_ref()
 4619            .map_or(true, |provider| provider.filter_completions());
 4620
 4621        let id = post_inc(&mut self.next_completion_id);
 4622        let task = cx.spawn_in(window, async move |editor, cx| {
 4623            async move {
 4624                editor.update(cx, |this, _| {
 4625                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4626                })?;
 4627
 4628                let mut completions = Vec::new();
 4629                if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
 4630                    completions.extend(provided_completions);
 4631                    if completion_settings.words == WordsCompletionMode::Fallback {
 4632                        words = Task::ready(BTreeMap::default());
 4633                    }
 4634                }
 4635
 4636                let mut words = words.await;
 4637                if let Some(word_to_exclude) = &word_to_exclude {
 4638                    words.remove(word_to_exclude);
 4639                }
 4640                for lsp_completion in &completions {
 4641                    words.remove(&lsp_completion.new_text);
 4642                }
 4643                completions.extend(words.into_iter().map(|(word, word_range)| Completion {
 4644                    replace_range: old_range.clone(),
 4645                    new_text: word.clone(),
 4646                    label: CodeLabel::plain(word, None),
 4647                    icon_path: None,
 4648                    documentation: None,
 4649                    source: CompletionSource::BufferWord {
 4650                        word_range,
 4651                        resolved: false,
 4652                    },
 4653                    insert_text_mode: Some(InsertTextMode::AS_IS),
 4654                    confirm: None,
 4655                }));
 4656
 4657                let menu = if completions.is_empty() {
 4658                    None
 4659                } else {
 4660                    let mut menu = CompletionsMenu::new(
 4661                        id,
 4662                        sort_completions,
 4663                        show_completion_documentation,
 4664                        ignore_completion_provider,
 4665                        position,
 4666                        buffer.clone(),
 4667                        completions.into(),
 4668                    );
 4669
 4670                    menu.filter(
 4671                        if filter_completions {
 4672                            query.as_deref()
 4673                        } else {
 4674                            None
 4675                        },
 4676                        cx.background_executor().clone(),
 4677                    )
 4678                    .await;
 4679
 4680                    menu.visible().then_some(menu)
 4681                };
 4682
 4683                editor.update_in(cx, |editor, window, cx| {
 4684                    match editor.context_menu.borrow().as_ref() {
 4685                        None => {}
 4686                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4687                            if prev_menu.id > id {
 4688                                return;
 4689                            }
 4690                        }
 4691                        _ => return,
 4692                    }
 4693
 4694                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4695                        let mut menu = menu.unwrap();
 4696                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4697
 4698                        *editor.context_menu.borrow_mut() =
 4699                            Some(CodeContextMenu::Completions(menu));
 4700
 4701                        if editor.show_edit_predictions_in_menu() {
 4702                            editor.update_visible_inline_completion(window, cx);
 4703                        } else {
 4704                            editor.discard_inline_completion(false, cx);
 4705                        }
 4706
 4707                        cx.notify();
 4708                    } else if editor.completion_tasks.len() <= 1 {
 4709                        // If there are no more completion tasks and the last menu was
 4710                        // empty, we should hide it.
 4711                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4712                        // If it was already hidden and we don't show inline
 4713                        // completions in the menu, we should also show the
 4714                        // inline-completion when available.
 4715                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4716                            editor.update_visible_inline_completion(window, cx);
 4717                        }
 4718                    }
 4719                })?;
 4720
 4721                anyhow::Ok(())
 4722            }
 4723            .log_err()
 4724            .await
 4725        });
 4726
 4727        self.completion_tasks.push((id, task));
 4728    }
 4729
 4730    #[cfg(feature = "test-support")]
 4731    pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
 4732        let menu = self.context_menu.borrow();
 4733        if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
 4734            let completions = menu.completions.borrow();
 4735            Some(completions.to_vec())
 4736        } else {
 4737            None
 4738        }
 4739    }
 4740
 4741    pub fn confirm_completion(
 4742        &mut self,
 4743        action: &ConfirmCompletion,
 4744        window: &mut Window,
 4745        cx: &mut Context<Self>,
 4746    ) -> Option<Task<Result<()>>> {
 4747        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4748        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4749    }
 4750
 4751    pub fn confirm_completion_insert(
 4752        &mut self,
 4753        _: &ConfirmCompletionInsert,
 4754        window: &mut Window,
 4755        cx: &mut Context<Self>,
 4756    ) -> Option<Task<Result<()>>> {
 4757        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4758        self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
 4759    }
 4760
 4761    pub fn confirm_completion_replace(
 4762        &mut self,
 4763        _: &ConfirmCompletionReplace,
 4764        window: &mut Window,
 4765        cx: &mut Context<Self>,
 4766    ) -> Option<Task<Result<()>>> {
 4767        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4768        self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
 4769    }
 4770
 4771    pub fn compose_completion(
 4772        &mut self,
 4773        action: &ComposeCompletion,
 4774        window: &mut Window,
 4775        cx: &mut Context<Self>,
 4776    ) -> Option<Task<Result<()>>> {
 4777        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4778        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4779    }
 4780
 4781    fn do_completion(
 4782        &mut self,
 4783        item_ix: Option<usize>,
 4784        intent: CompletionIntent,
 4785        window: &mut Window,
 4786        cx: &mut Context<Editor>,
 4787    ) -> Option<Task<Result<()>>> {
 4788        use language::ToOffset as _;
 4789
 4790        let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
 4791        else {
 4792            return None;
 4793        };
 4794
 4795        let candidate_id = {
 4796            let entries = completions_menu.entries.borrow();
 4797            let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4798            if self.show_edit_predictions_in_menu() {
 4799                self.discard_inline_completion(true, cx);
 4800            }
 4801            mat.candidate_id
 4802        };
 4803
 4804        let buffer_handle = completions_menu.buffer;
 4805        let completion = completions_menu
 4806            .completions
 4807            .borrow()
 4808            .get(candidate_id)?
 4809            .clone();
 4810        cx.stop_propagation();
 4811
 4812        let snippet;
 4813        let new_text;
 4814        if completion.is_snippet() {
 4815            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4816            new_text = snippet.as_ref().unwrap().text.clone();
 4817        } else {
 4818            snippet = None;
 4819            new_text = completion.new_text.clone();
 4820        };
 4821
 4822        let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
 4823        let buffer = buffer_handle.read(cx);
 4824        let snapshot = self.buffer.read(cx).snapshot(cx);
 4825        let replace_range_multibuffer = {
 4826            let excerpt = snapshot
 4827                .excerpt_containing(self.selections.newest_anchor().range())
 4828                .unwrap();
 4829            let multibuffer_anchor = snapshot
 4830                .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.start))
 4831                .unwrap()
 4832                ..snapshot
 4833                    .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.end))
 4834                    .unwrap();
 4835            multibuffer_anchor.start.to_offset(&snapshot)
 4836                ..multibuffer_anchor.end.to_offset(&snapshot)
 4837        };
 4838        let newest_anchor = self.selections.newest_anchor();
 4839        if newest_anchor.head().buffer_id != Some(buffer.remote_id()) {
 4840            return None;
 4841        }
 4842
 4843        let old_text = buffer
 4844            .text_for_range(replace_range.clone())
 4845            .collect::<String>();
 4846        let lookbehind = newest_anchor
 4847            .start
 4848            .text_anchor
 4849            .to_offset(buffer)
 4850            .saturating_sub(replace_range.start);
 4851        let lookahead = replace_range
 4852            .end
 4853            .saturating_sub(newest_anchor.end.text_anchor.to_offset(buffer));
 4854        let prefix = &old_text[..old_text.len().saturating_sub(lookahead)];
 4855        let suffix = &old_text[lookbehind.min(old_text.len())..];
 4856
 4857        let selections = self.selections.all::<usize>(cx);
 4858        let mut ranges = Vec::new();
 4859        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4860
 4861        for selection in &selections {
 4862            let range = if selection.id == newest_anchor.id {
 4863                replace_range_multibuffer.clone()
 4864            } else {
 4865                let mut range = selection.range();
 4866
 4867                // if prefix is present, don't duplicate it
 4868                if snapshot.contains_str_at(range.start.saturating_sub(lookbehind), prefix) {
 4869                    range.start = range.start.saturating_sub(lookbehind);
 4870
 4871                    // if suffix is also present, mimic the newest cursor and replace it
 4872                    if selection.id != newest_anchor.id
 4873                        && snapshot.contains_str_at(range.end, suffix)
 4874                    {
 4875                        range.end += lookahead;
 4876                    }
 4877                }
 4878                range
 4879            };
 4880
 4881            ranges.push(range);
 4882
 4883            if !self.linked_edit_ranges.is_empty() {
 4884                let start_anchor = snapshot.anchor_before(selection.head());
 4885                let end_anchor = snapshot.anchor_after(selection.tail());
 4886                if let Some(ranges) = self
 4887                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4888                {
 4889                    for (buffer, edits) in ranges {
 4890                        linked_edits
 4891                            .entry(buffer.clone())
 4892                            .or_default()
 4893                            .extend(edits.into_iter().map(|range| (range, new_text.to_owned())));
 4894                    }
 4895                }
 4896            }
 4897        }
 4898
 4899        cx.emit(EditorEvent::InputHandled {
 4900            utf16_range_to_replace: None,
 4901            text: new_text.clone().into(),
 4902        });
 4903
 4904        self.transact(window, cx, |this, window, cx| {
 4905            if let Some(mut snippet) = snippet {
 4906                snippet.text = new_text.to_string();
 4907                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4908            } else {
 4909                this.buffer.update(cx, |buffer, cx| {
 4910                    let auto_indent = match completion.insert_text_mode {
 4911                        Some(InsertTextMode::AS_IS) => None,
 4912                        _ => this.autoindent_mode.clone(),
 4913                    };
 4914                    let edits = ranges.into_iter().map(|range| (range, new_text.as_str()));
 4915                    buffer.edit(edits, auto_indent, cx);
 4916                });
 4917            }
 4918            for (buffer, edits) in linked_edits {
 4919                buffer.update(cx, |buffer, cx| {
 4920                    let snapshot = buffer.snapshot();
 4921                    let edits = edits
 4922                        .into_iter()
 4923                        .map(|(range, text)| {
 4924                            use text::ToPoint as TP;
 4925                            let end_point = TP::to_point(&range.end, &snapshot);
 4926                            let start_point = TP::to_point(&range.start, &snapshot);
 4927                            (start_point..end_point, text)
 4928                        })
 4929                        .sorted_by_key(|(range, _)| range.start);
 4930                    buffer.edit(edits, None, cx);
 4931                })
 4932            }
 4933
 4934            this.refresh_inline_completion(true, false, window, cx);
 4935        });
 4936
 4937        let show_new_completions_on_confirm = completion
 4938            .confirm
 4939            .as_ref()
 4940            .map_or(false, |confirm| confirm(intent, window, cx));
 4941        if show_new_completions_on_confirm {
 4942            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4943        }
 4944
 4945        let provider = self.completion_provider.as_ref()?;
 4946        drop(completion);
 4947        let apply_edits = provider.apply_additional_edits_for_completion(
 4948            buffer_handle,
 4949            completions_menu.completions.clone(),
 4950            candidate_id,
 4951            true,
 4952            cx,
 4953        );
 4954
 4955        let editor_settings = EditorSettings::get_global(cx);
 4956        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4957            // After the code completion is finished, users often want to know what signatures are needed.
 4958            // so we should automatically call signature_help
 4959            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4960        }
 4961
 4962        Some(cx.foreground_executor().spawn(async move {
 4963            apply_edits.await?;
 4964            Ok(())
 4965        }))
 4966    }
 4967
 4968    pub fn toggle_code_actions(
 4969        &mut self,
 4970        action: &ToggleCodeActions,
 4971        window: &mut Window,
 4972        cx: &mut Context<Self>,
 4973    ) {
 4974        let mut context_menu = self.context_menu.borrow_mut();
 4975        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4976            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4977                // Toggle if we're selecting the same one
 4978                *context_menu = None;
 4979                cx.notify();
 4980                return;
 4981            } else {
 4982                // Otherwise, clear it and start a new one
 4983                *context_menu = None;
 4984                cx.notify();
 4985            }
 4986        }
 4987        drop(context_menu);
 4988        let snapshot = self.snapshot(window, cx);
 4989        let deployed_from_indicator = action.deployed_from_indicator;
 4990        let mut task = self.code_actions_task.take();
 4991        let action = action.clone();
 4992        cx.spawn_in(window, async move |editor, cx| {
 4993            while let Some(prev_task) = task {
 4994                prev_task.await.log_err();
 4995                task = editor.update(cx, |this, _| this.code_actions_task.take())?;
 4996            }
 4997
 4998            let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
 4999                if editor.focus_handle.is_focused(window) {
 5000                    let multibuffer_point = action
 5001                        .deployed_from_indicator
 5002                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 5003                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 5004                    let (buffer, buffer_row) = snapshot
 5005                        .buffer_snapshot
 5006                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 5007                        .and_then(|(buffer_snapshot, range)| {
 5008                            editor
 5009                                .buffer
 5010                                .read(cx)
 5011                                .buffer(buffer_snapshot.remote_id())
 5012                                .map(|buffer| (buffer, range.start.row))
 5013                        })?;
 5014                    let (_, code_actions) = editor
 5015                        .available_code_actions
 5016                        .clone()
 5017                        .and_then(|(location, code_actions)| {
 5018                            let snapshot = location.buffer.read(cx).snapshot();
 5019                            let point_range = location.range.to_point(&snapshot);
 5020                            let point_range = point_range.start.row..=point_range.end.row;
 5021                            if point_range.contains(&buffer_row) {
 5022                                Some((location, code_actions))
 5023                            } else {
 5024                                None
 5025                            }
 5026                        })
 5027                        .unzip();
 5028                    let buffer_id = buffer.read(cx).remote_id();
 5029                    let tasks = editor
 5030                        .tasks
 5031                        .get(&(buffer_id, buffer_row))
 5032                        .map(|t| Arc::new(t.to_owned()));
 5033                    if tasks.is_none() && code_actions.is_none() {
 5034                        return None;
 5035                    }
 5036
 5037                    editor.completion_tasks.clear();
 5038                    editor.discard_inline_completion(false, cx);
 5039                    let task_context =
 5040                        tasks
 5041                            .as_ref()
 5042                            .zip(editor.project.clone())
 5043                            .map(|(tasks, project)| {
 5044                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 5045                            });
 5046
 5047                    let debugger_flag = cx.has_flag::<Debugger>();
 5048
 5049                    Some(cx.spawn_in(window, async move |editor, cx| {
 5050                        let task_context = match task_context {
 5051                            Some(task_context) => task_context.await,
 5052                            None => None,
 5053                        };
 5054                        let resolved_tasks =
 5055                            tasks
 5056                                .zip(task_context)
 5057                                .map(|(tasks, task_context)| ResolvedTasks {
 5058                                    templates: tasks.resolve(&task_context).collect(),
 5059                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 5060                                        multibuffer_point.row,
 5061                                        tasks.column,
 5062                                    )),
 5063                                });
 5064                        let spawn_straight_away = resolved_tasks.as_ref().map_or(false, |tasks| {
 5065                            tasks
 5066                                .templates
 5067                                .iter()
 5068                                .filter(|task| {
 5069                                    if matches!(task.1.task_type(), task::TaskType::Debug(_)) {
 5070                                        debugger_flag
 5071                                    } else {
 5072                                        true
 5073                                    }
 5074                                })
 5075                                .count()
 5076                                == 1
 5077                        }) && code_actions
 5078                            .as_ref()
 5079                            .map_or(true, |actions| actions.is_empty());
 5080                        if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
 5081                            *editor.context_menu.borrow_mut() =
 5082                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 5083                                    buffer,
 5084                                    actions: CodeActionContents::new(
 5085                                        resolved_tasks,
 5086                                        code_actions,
 5087                                        cx,
 5088                                    ),
 5089                                    selected_item: Default::default(),
 5090                                    scroll_handle: UniformListScrollHandle::default(),
 5091                                    deployed_from_indicator,
 5092                                }));
 5093                            if spawn_straight_away {
 5094                                if let Some(task) = editor.confirm_code_action(
 5095                                    &ConfirmCodeAction { item_ix: Some(0) },
 5096                                    window,
 5097                                    cx,
 5098                                ) {
 5099                                    cx.notify();
 5100                                    return task;
 5101                                }
 5102                            }
 5103                            cx.notify();
 5104                            Task::ready(Ok(()))
 5105                        }) {
 5106                            task.await
 5107                        } else {
 5108                            Ok(())
 5109                        }
 5110                    }))
 5111                } else {
 5112                    Some(Task::ready(Ok(())))
 5113                }
 5114            })?;
 5115            if let Some(task) = spawned_test_task {
 5116                task.await?;
 5117            }
 5118
 5119            Ok::<_, anyhow::Error>(())
 5120        })
 5121        .detach_and_log_err(cx);
 5122    }
 5123
 5124    pub fn confirm_code_action(
 5125        &mut self,
 5126        action: &ConfirmCodeAction,
 5127        window: &mut Window,
 5128        cx: &mut Context<Self>,
 5129    ) -> Option<Task<Result<()>>> {
 5130        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 5131
 5132        let actions_menu =
 5133            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 5134                menu
 5135            } else {
 5136                return None;
 5137            };
 5138
 5139        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 5140        let action = actions_menu.actions.get(action_ix)?;
 5141        let title = action.label();
 5142        let buffer = actions_menu.buffer;
 5143        let workspace = self.workspace()?;
 5144
 5145        match action {
 5146            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 5147                match resolved_task.task_type() {
 5148                    task::TaskType::Script => workspace.update(cx, |workspace, cx| {
 5149                        workspace.schedule_resolved_task(
 5150                            task_source_kind,
 5151                            resolved_task,
 5152                            false,
 5153                            window,
 5154                            cx,
 5155                        );
 5156
 5157                        Some(Task::ready(Ok(())))
 5158                    }),
 5159                    task::TaskType::Debug(_) => {
 5160                        workspace.update(cx, |workspace, cx| {
 5161                            workspace.schedule_debug_task(resolved_task, window, cx);
 5162                        });
 5163                        Some(Task::ready(Ok(())))
 5164                    }
 5165                }
 5166            }
 5167            CodeActionsItem::CodeAction {
 5168                excerpt_id,
 5169                action,
 5170                provider,
 5171            } => {
 5172                let apply_code_action =
 5173                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 5174                let workspace = workspace.downgrade();
 5175                Some(cx.spawn_in(window, async move |editor, cx| {
 5176                    let project_transaction = apply_code_action.await?;
 5177                    Self::open_project_transaction(
 5178                        &editor,
 5179                        workspace,
 5180                        project_transaction,
 5181                        title,
 5182                        cx,
 5183                    )
 5184                    .await
 5185                }))
 5186            }
 5187        }
 5188    }
 5189
 5190    pub async fn open_project_transaction(
 5191        this: &WeakEntity<Editor>,
 5192        workspace: WeakEntity<Workspace>,
 5193        transaction: ProjectTransaction,
 5194        title: String,
 5195        cx: &mut AsyncWindowContext,
 5196    ) -> Result<()> {
 5197        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 5198        cx.update(|_, cx| {
 5199            entries.sort_unstable_by_key(|(buffer, _)| {
 5200                buffer.read(cx).file().map(|f| f.path().clone())
 5201            });
 5202        })?;
 5203
 5204        // If the project transaction's edits are all contained within this editor, then
 5205        // avoid opening a new editor to display them.
 5206
 5207        if let Some((buffer, transaction)) = entries.first() {
 5208            if entries.len() == 1 {
 5209                let excerpt = this.update(cx, |editor, cx| {
 5210                    editor
 5211                        .buffer()
 5212                        .read(cx)
 5213                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 5214                })?;
 5215                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 5216                    if excerpted_buffer == *buffer {
 5217                        let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
 5218                            let excerpt_range = excerpt_range.to_offset(buffer);
 5219                            buffer
 5220                                .edited_ranges_for_transaction::<usize>(transaction)
 5221                                .all(|range| {
 5222                                    excerpt_range.start <= range.start
 5223                                        && excerpt_range.end >= range.end
 5224                                })
 5225                        })?;
 5226
 5227                        if all_edits_within_excerpt {
 5228                            return Ok(());
 5229                        }
 5230                    }
 5231                }
 5232            }
 5233        } else {
 5234            return Ok(());
 5235        }
 5236
 5237        let mut ranges_to_highlight = Vec::new();
 5238        let excerpt_buffer = cx.new(|cx| {
 5239            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 5240            for (buffer_handle, transaction) in &entries {
 5241                let edited_ranges = buffer_handle
 5242                    .read(cx)
 5243                    .edited_ranges_for_transaction::<Point>(transaction)
 5244                    .collect::<Vec<_>>();
 5245                let (ranges, _) = multibuffer.set_excerpts_for_path(
 5246                    PathKey::for_buffer(buffer_handle, cx),
 5247                    buffer_handle.clone(),
 5248                    edited_ranges,
 5249                    DEFAULT_MULTIBUFFER_CONTEXT,
 5250                    cx,
 5251                );
 5252
 5253                ranges_to_highlight.extend(ranges);
 5254            }
 5255            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5256            multibuffer
 5257        })?;
 5258
 5259        workspace.update_in(cx, |workspace, window, cx| {
 5260            let project = workspace.project().clone();
 5261            let editor =
 5262                cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
 5263            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 5264            editor.update(cx, |editor, cx| {
 5265                editor.highlight_background::<Self>(
 5266                    &ranges_to_highlight,
 5267                    |theme| theme.editor_highlighted_line_background,
 5268                    cx,
 5269                );
 5270            });
 5271        })?;
 5272
 5273        Ok(())
 5274    }
 5275
 5276    pub fn clear_code_action_providers(&mut self) {
 5277        self.code_action_providers.clear();
 5278        self.available_code_actions.take();
 5279    }
 5280
 5281    pub fn add_code_action_provider(
 5282        &mut self,
 5283        provider: Rc<dyn CodeActionProvider>,
 5284        window: &mut Window,
 5285        cx: &mut Context<Self>,
 5286    ) {
 5287        if self
 5288            .code_action_providers
 5289            .iter()
 5290            .any(|existing_provider| existing_provider.id() == provider.id())
 5291        {
 5292            return;
 5293        }
 5294
 5295        self.code_action_providers.push(provider);
 5296        self.refresh_code_actions(window, cx);
 5297    }
 5298
 5299    pub fn remove_code_action_provider(
 5300        &mut self,
 5301        id: Arc<str>,
 5302        window: &mut Window,
 5303        cx: &mut Context<Self>,
 5304    ) {
 5305        self.code_action_providers
 5306            .retain(|provider| provider.id() != id);
 5307        self.refresh_code_actions(window, cx);
 5308    }
 5309
 5310    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 5311        let newest_selection = self.selections.newest_anchor().clone();
 5312        let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
 5313        let buffer = self.buffer.read(cx);
 5314        if newest_selection.head().diff_base_anchor.is_some() {
 5315            return None;
 5316        }
 5317        let (start_buffer, start) =
 5318            buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
 5319        let (end_buffer, end) =
 5320            buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
 5321        if start_buffer != end_buffer {
 5322            return None;
 5323        }
 5324
 5325        self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
 5326            cx.background_executor()
 5327                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5328                .await;
 5329
 5330            let (providers, tasks) = this.update_in(cx, |this, window, cx| {
 5331                let providers = this.code_action_providers.clone();
 5332                let tasks = this
 5333                    .code_action_providers
 5334                    .iter()
 5335                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 5336                    .collect::<Vec<_>>();
 5337                (providers, tasks)
 5338            })?;
 5339
 5340            let mut actions = Vec::new();
 5341            for (provider, provider_actions) in
 5342                providers.into_iter().zip(future::join_all(tasks).await)
 5343            {
 5344                if let Some(provider_actions) = provider_actions.log_err() {
 5345                    actions.extend(provider_actions.into_iter().map(|action| {
 5346                        AvailableCodeAction {
 5347                            excerpt_id: newest_selection.start.excerpt_id,
 5348                            action,
 5349                            provider: provider.clone(),
 5350                        }
 5351                    }));
 5352                }
 5353            }
 5354
 5355            this.update(cx, |this, cx| {
 5356                this.available_code_actions = if actions.is_empty() {
 5357                    None
 5358                } else {
 5359                    Some((
 5360                        Location {
 5361                            buffer: start_buffer,
 5362                            range: start..end,
 5363                        },
 5364                        actions.into(),
 5365                    ))
 5366                };
 5367                cx.notify();
 5368            })
 5369        }));
 5370        None
 5371    }
 5372
 5373    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5374        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5375            self.show_git_blame_inline = false;
 5376
 5377            self.show_git_blame_inline_delay_task =
 5378                Some(cx.spawn_in(window, async move |this, cx| {
 5379                    cx.background_executor().timer(delay).await;
 5380
 5381                    this.update(cx, |this, cx| {
 5382                        this.show_git_blame_inline = true;
 5383                        cx.notify();
 5384                    })
 5385                    .log_err();
 5386                }));
 5387        }
 5388    }
 5389
 5390    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 5391        if self.pending_rename.is_some() {
 5392            return None;
 5393        }
 5394
 5395        let provider = self.semantics_provider.clone()?;
 5396        let buffer = self.buffer.read(cx);
 5397        let newest_selection = self.selections.newest_anchor().clone();
 5398        let cursor_position = newest_selection.head();
 5399        let (cursor_buffer, cursor_buffer_position) =
 5400            buffer.text_anchor_for_position(cursor_position, cx)?;
 5401        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5402        if cursor_buffer != tail_buffer {
 5403            return None;
 5404        }
 5405        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 5406        self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
 5407            cx.background_executor()
 5408                .timer(Duration::from_millis(debounce))
 5409                .await;
 5410
 5411            let highlights = if let Some(highlights) = cx
 5412                .update(|cx| {
 5413                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5414                })
 5415                .ok()
 5416                .flatten()
 5417            {
 5418                highlights.await.log_err()
 5419            } else {
 5420                None
 5421            };
 5422
 5423            if let Some(highlights) = highlights {
 5424                this.update(cx, |this, cx| {
 5425                    if this.pending_rename.is_some() {
 5426                        return;
 5427                    }
 5428
 5429                    let buffer_id = cursor_position.buffer_id;
 5430                    let buffer = this.buffer.read(cx);
 5431                    if !buffer
 5432                        .text_anchor_for_position(cursor_position, cx)
 5433                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5434                    {
 5435                        return;
 5436                    }
 5437
 5438                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5439                    let mut write_ranges = Vec::new();
 5440                    let mut read_ranges = Vec::new();
 5441                    for highlight in highlights {
 5442                        for (excerpt_id, excerpt_range) in
 5443                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 5444                        {
 5445                            let start = highlight
 5446                                .range
 5447                                .start
 5448                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5449                            let end = highlight
 5450                                .range
 5451                                .end
 5452                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5453                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5454                                continue;
 5455                            }
 5456
 5457                            let range = Anchor {
 5458                                buffer_id,
 5459                                excerpt_id,
 5460                                text_anchor: start,
 5461                                diff_base_anchor: None,
 5462                            }..Anchor {
 5463                                buffer_id,
 5464                                excerpt_id,
 5465                                text_anchor: end,
 5466                                diff_base_anchor: None,
 5467                            };
 5468                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5469                                write_ranges.push(range);
 5470                            } else {
 5471                                read_ranges.push(range);
 5472                            }
 5473                        }
 5474                    }
 5475
 5476                    this.highlight_background::<DocumentHighlightRead>(
 5477                        &read_ranges,
 5478                        |theme| theme.editor_document_highlight_read_background,
 5479                        cx,
 5480                    );
 5481                    this.highlight_background::<DocumentHighlightWrite>(
 5482                        &write_ranges,
 5483                        |theme| theme.editor_document_highlight_write_background,
 5484                        cx,
 5485                    );
 5486                    cx.notify();
 5487                })
 5488                .log_err();
 5489            }
 5490        }));
 5491        None
 5492    }
 5493
 5494    fn prepare_highlight_query_from_selection(
 5495        &mut self,
 5496        cx: &mut Context<Editor>,
 5497    ) -> Option<(String, Range<Anchor>)> {
 5498        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 5499            return None;
 5500        }
 5501        if !EditorSettings::get_global(cx).selection_highlight {
 5502            return None;
 5503        }
 5504        if self.selections.count() != 1 || self.selections.line_mode {
 5505            return None;
 5506        }
 5507        let selection = self.selections.newest::<Point>(cx);
 5508        if selection.is_empty() || selection.start.row != selection.end.row {
 5509            return None;
 5510        }
 5511        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5512        let selection_anchor_range = selection.range().to_anchors(&multi_buffer_snapshot);
 5513        let query = multi_buffer_snapshot
 5514            .text_for_range(selection_anchor_range.clone())
 5515            .collect::<String>();
 5516        if query.trim().is_empty() {
 5517            return None;
 5518        }
 5519        Some((query, selection_anchor_range))
 5520    }
 5521
 5522    fn update_selection_occurrence_highlights(
 5523        &mut self,
 5524        query_text: String,
 5525        query_range: Range<Anchor>,
 5526        multi_buffer_range_to_query: Range<Point>,
 5527        use_debounce: bool,
 5528        window: &mut Window,
 5529        cx: &mut Context<Editor>,
 5530    ) -> Task<()> {
 5531        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5532        cx.spawn_in(window, async move |editor, cx| {
 5533            if use_debounce {
 5534                cx.background_executor()
 5535                    .timer(SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT)
 5536                    .await;
 5537            }
 5538            let match_task = cx.background_spawn(async move {
 5539                let buffer_ranges = multi_buffer_snapshot
 5540                    .range_to_buffer_ranges(multi_buffer_range_to_query)
 5541                    .into_iter()
 5542                    .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty());
 5543                let mut match_ranges = Vec::new();
 5544                for (buffer_snapshot, search_range, excerpt_id) in buffer_ranges {
 5545                    match_ranges.extend(
 5546                        project::search::SearchQuery::text(
 5547                            query_text.clone(),
 5548                            false,
 5549                            false,
 5550                            false,
 5551                            Default::default(),
 5552                            Default::default(),
 5553                            false,
 5554                            None,
 5555                        )
 5556                        .unwrap()
 5557                        .search(&buffer_snapshot, Some(search_range.clone()))
 5558                        .await
 5559                        .into_iter()
 5560                        .filter_map(|match_range| {
 5561                            let match_start = buffer_snapshot
 5562                                .anchor_after(search_range.start + match_range.start);
 5563                            let match_end =
 5564                                buffer_snapshot.anchor_before(search_range.start + match_range.end);
 5565                            let match_anchor_range = Anchor::range_in_buffer(
 5566                                excerpt_id,
 5567                                buffer_snapshot.remote_id(),
 5568                                match_start..match_end,
 5569                            );
 5570                            (match_anchor_range != query_range).then_some(match_anchor_range)
 5571                        }),
 5572                    );
 5573                }
 5574                match_ranges
 5575            });
 5576            let match_ranges = match_task.await;
 5577            editor
 5578                .update_in(cx, |editor, _, cx| {
 5579                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5580                    if !match_ranges.is_empty() {
 5581                        editor.highlight_background::<SelectedTextHighlight>(
 5582                            &match_ranges,
 5583                            |theme| theme.editor_document_highlight_bracket_background,
 5584                            cx,
 5585                        )
 5586                    }
 5587                })
 5588                .log_err();
 5589        })
 5590    }
 5591
 5592    fn refresh_selected_text_highlights(&mut self, window: &mut Window, cx: &mut Context<Editor>) {
 5593        let Some((query_text, query_range)) = self.prepare_highlight_query_from_selection(cx)
 5594        else {
 5595            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5596            self.quick_selection_highlight_task.take();
 5597            self.debounced_selection_highlight_task.take();
 5598            return;
 5599        };
 5600        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5601        if self
 5602            .quick_selection_highlight_task
 5603            .as_ref()
 5604            .map_or(true, |(prev_anchor_range, _)| {
 5605                prev_anchor_range != &query_range
 5606            })
 5607        {
 5608            let multi_buffer_visible_start = self
 5609                .scroll_manager
 5610                .anchor()
 5611                .anchor
 5612                .to_point(&multi_buffer_snapshot);
 5613            let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 5614                multi_buffer_visible_start
 5615                    + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 5616                Bias::Left,
 5617            );
 5618            let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 5619            self.quick_selection_highlight_task = Some((
 5620                query_range.clone(),
 5621                self.update_selection_occurrence_highlights(
 5622                    query_text.clone(),
 5623                    query_range.clone(),
 5624                    multi_buffer_visible_range,
 5625                    false,
 5626                    window,
 5627                    cx,
 5628                ),
 5629            ));
 5630        }
 5631        if self
 5632            .debounced_selection_highlight_task
 5633            .as_ref()
 5634            .map_or(true, |(prev_anchor_range, _)| {
 5635                prev_anchor_range != &query_range
 5636            })
 5637        {
 5638            let multi_buffer_start = multi_buffer_snapshot
 5639                .anchor_before(0)
 5640                .to_point(&multi_buffer_snapshot);
 5641            let multi_buffer_end = multi_buffer_snapshot
 5642                .anchor_after(multi_buffer_snapshot.len())
 5643                .to_point(&multi_buffer_snapshot);
 5644            let multi_buffer_full_range = multi_buffer_start..multi_buffer_end;
 5645            self.debounced_selection_highlight_task = Some((
 5646                query_range.clone(),
 5647                self.update_selection_occurrence_highlights(
 5648                    query_text,
 5649                    query_range,
 5650                    multi_buffer_full_range,
 5651                    true,
 5652                    window,
 5653                    cx,
 5654                ),
 5655            ));
 5656        }
 5657    }
 5658
 5659    pub fn refresh_inline_completion(
 5660        &mut self,
 5661        debounce: bool,
 5662        user_requested: bool,
 5663        window: &mut Window,
 5664        cx: &mut Context<Self>,
 5665    ) -> Option<()> {
 5666        let provider = self.edit_prediction_provider()?;
 5667        let cursor = self.selections.newest_anchor().head();
 5668        let (buffer, cursor_buffer_position) =
 5669            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5670
 5671        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 5672            self.discard_inline_completion(false, cx);
 5673            return None;
 5674        }
 5675
 5676        if !user_requested
 5677            && (!self.should_show_edit_predictions()
 5678                || !self.is_focused(window)
 5679                || buffer.read(cx).is_empty())
 5680        {
 5681            self.discard_inline_completion(false, cx);
 5682            return None;
 5683        }
 5684
 5685        self.update_visible_inline_completion(window, cx);
 5686        provider.refresh(
 5687            self.project.clone(),
 5688            buffer,
 5689            cursor_buffer_position,
 5690            debounce,
 5691            cx,
 5692        );
 5693        Some(())
 5694    }
 5695
 5696    fn show_edit_predictions_in_menu(&self) -> bool {
 5697        match self.edit_prediction_settings {
 5698            EditPredictionSettings::Disabled => false,
 5699            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 5700        }
 5701    }
 5702
 5703    pub fn edit_predictions_enabled(&self) -> bool {
 5704        match self.edit_prediction_settings {
 5705            EditPredictionSettings::Disabled => false,
 5706            EditPredictionSettings::Enabled { .. } => true,
 5707        }
 5708    }
 5709
 5710    fn edit_prediction_requires_modifier(&self) -> bool {
 5711        match self.edit_prediction_settings {
 5712            EditPredictionSettings::Disabled => false,
 5713            EditPredictionSettings::Enabled {
 5714                preview_requires_modifier,
 5715                ..
 5716            } => preview_requires_modifier,
 5717        }
 5718    }
 5719
 5720    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 5721        if self.edit_prediction_provider.is_none() {
 5722            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5723        } else {
 5724            let selection = self.selections.newest_anchor();
 5725            let cursor = selection.head();
 5726
 5727            if let Some((buffer, cursor_buffer_position)) =
 5728                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5729            {
 5730                self.edit_prediction_settings =
 5731                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5732            }
 5733        }
 5734    }
 5735
 5736    fn edit_prediction_settings_at_position(
 5737        &self,
 5738        buffer: &Entity<Buffer>,
 5739        buffer_position: language::Anchor,
 5740        cx: &App,
 5741    ) -> EditPredictionSettings {
 5742        if !self.mode.is_full()
 5743            || !self.show_inline_completions_override.unwrap_or(true)
 5744            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 5745        {
 5746            return EditPredictionSettings::Disabled;
 5747        }
 5748
 5749        let buffer = buffer.read(cx);
 5750
 5751        let file = buffer.file();
 5752
 5753        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 5754            return EditPredictionSettings::Disabled;
 5755        };
 5756
 5757        let by_provider = matches!(
 5758            self.menu_inline_completions_policy,
 5759            MenuInlineCompletionsPolicy::ByProvider
 5760        );
 5761
 5762        let show_in_menu = by_provider
 5763            && self
 5764                .edit_prediction_provider
 5765                .as_ref()
 5766                .map_or(false, |provider| {
 5767                    provider.provider.show_completions_in_menu()
 5768                });
 5769
 5770        let preview_requires_modifier =
 5771            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 5772
 5773        EditPredictionSettings::Enabled {
 5774            show_in_menu,
 5775            preview_requires_modifier,
 5776        }
 5777    }
 5778
 5779    fn should_show_edit_predictions(&self) -> bool {
 5780        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 5781    }
 5782
 5783    pub fn edit_prediction_preview_is_active(&self) -> bool {
 5784        matches!(
 5785            self.edit_prediction_preview,
 5786            EditPredictionPreview::Active { .. }
 5787        )
 5788    }
 5789
 5790    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 5791        let cursor = self.selections.newest_anchor().head();
 5792        if let Some((buffer, cursor_position)) =
 5793            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5794        {
 5795            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 5796        } else {
 5797            false
 5798        }
 5799    }
 5800
 5801    fn edit_predictions_enabled_in_buffer(
 5802        &self,
 5803        buffer: &Entity<Buffer>,
 5804        buffer_position: language::Anchor,
 5805        cx: &App,
 5806    ) -> bool {
 5807        maybe!({
 5808            if self.read_only(cx) {
 5809                return Some(false);
 5810            }
 5811            let provider = self.edit_prediction_provider()?;
 5812            if !provider.is_enabled(&buffer, buffer_position, cx) {
 5813                return Some(false);
 5814            }
 5815            let buffer = buffer.read(cx);
 5816            let Some(file) = buffer.file() else {
 5817                return Some(true);
 5818            };
 5819            let settings = all_language_settings(Some(file), cx);
 5820            Some(settings.edit_predictions_enabled_for_file(file, cx))
 5821        })
 5822        .unwrap_or(false)
 5823    }
 5824
 5825    fn cycle_inline_completion(
 5826        &mut self,
 5827        direction: Direction,
 5828        window: &mut Window,
 5829        cx: &mut Context<Self>,
 5830    ) -> Option<()> {
 5831        let provider = self.edit_prediction_provider()?;
 5832        let cursor = self.selections.newest_anchor().head();
 5833        let (buffer, cursor_buffer_position) =
 5834            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5835        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 5836            return None;
 5837        }
 5838
 5839        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5840        self.update_visible_inline_completion(window, cx);
 5841
 5842        Some(())
 5843    }
 5844
 5845    pub fn show_inline_completion(
 5846        &mut self,
 5847        _: &ShowEditPrediction,
 5848        window: &mut Window,
 5849        cx: &mut Context<Self>,
 5850    ) {
 5851        if !self.has_active_inline_completion() {
 5852            self.refresh_inline_completion(false, true, window, cx);
 5853            return;
 5854        }
 5855
 5856        self.update_visible_inline_completion(window, cx);
 5857    }
 5858
 5859    pub fn display_cursor_names(
 5860        &mut self,
 5861        _: &DisplayCursorNames,
 5862        window: &mut Window,
 5863        cx: &mut Context<Self>,
 5864    ) {
 5865        self.show_cursor_names(window, cx);
 5866    }
 5867
 5868    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5869        self.show_cursor_names = true;
 5870        cx.notify();
 5871        cx.spawn_in(window, async move |this, cx| {
 5872            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5873            this.update(cx, |this, cx| {
 5874                this.show_cursor_names = false;
 5875                cx.notify()
 5876            })
 5877            .ok()
 5878        })
 5879        .detach();
 5880    }
 5881
 5882    pub fn next_edit_prediction(
 5883        &mut self,
 5884        _: &NextEditPrediction,
 5885        window: &mut Window,
 5886        cx: &mut Context<Self>,
 5887    ) {
 5888        if self.has_active_inline_completion() {
 5889            self.cycle_inline_completion(Direction::Next, window, cx);
 5890        } else {
 5891            let is_copilot_disabled = self
 5892                .refresh_inline_completion(false, true, window, cx)
 5893                .is_none();
 5894            if is_copilot_disabled {
 5895                cx.propagate();
 5896            }
 5897        }
 5898    }
 5899
 5900    pub fn previous_edit_prediction(
 5901        &mut self,
 5902        _: &PreviousEditPrediction,
 5903        window: &mut Window,
 5904        cx: &mut Context<Self>,
 5905    ) {
 5906        if self.has_active_inline_completion() {
 5907            self.cycle_inline_completion(Direction::Prev, window, cx);
 5908        } else {
 5909            let is_copilot_disabled = self
 5910                .refresh_inline_completion(false, true, window, cx)
 5911                .is_none();
 5912            if is_copilot_disabled {
 5913                cx.propagate();
 5914            }
 5915        }
 5916    }
 5917
 5918    pub fn accept_edit_prediction(
 5919        &mut self,
 5920        _: &AcceptEditPrediction,
 5921        window: &mut Window,
 5922        cx: &mut Context<Self>,
 5923    ) {
 5924        if self.show_edit_predictions_in_menu() {
 5925            self.hide_context_menu(window, cx);
 5926        }
 5927
 5928        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5929            return;
 5930        };
 5931
 5932        self.report_inline_completion_event(
 5933            active_inline_completion.completion_id.clone(),
 5934            true,
 5935            cx,
 5936        );
 5937
 5938        match &active_inline_completion.completion {
 5939            InlineCompletion::Move { target, .. } => {
 5940                let target = *target;
 5941
 5942                if let Some(position_map) = &self.last_position_map {
 5943                    if position_map
 5944                        .visible_row_range
 5945                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5946                        || !self.edit_prediction_requires_modifier()
 5947                    {
 5948                        self.unfold_ranges(&[target..target], true, false, cx);
 5949                        // Note that this is also done in vim's handler of the Tab action.
 5950                        self.change_selections(
 5951                            Some(Autoscroll::newest()),
 5952                            window,
 5953                            cx,
 5954                            |selections| {
 5955                                selections.select_anchor_ranges([target..target]);
 5956                            },
 5957                        );
 5958                        self.clear_row_highlights::<EditPredictionPreview>();
 5959
 5960                        self.edit_prediction_preview
 5961                            .set_previous_scroll_position(None);
 5962                    } else {
 5963                        self.edit_prediction_preview
 5964                            .set_previous_scroll_position(Some(
 5965                                position_map.snapshot.scroll_anchor,
 5966                            ));
 5967
 5968                        self.highlight_rows::<EditPredictionPreview>(
 5969                            target..target,
 5970                            cx.theme().colors().editor_highlighted_line_background,
 5971                            RowHighlightOptions {
 5972                                autoscroll: true,
 5973                                ..Default::default()
 5974                            },
 5975                            cx,
 5976                        );
 5977                        self.request_autoscroll(Autoscroll::fit(), cx);
 5978                    }
 5979                }
 5980            }
 5981            InlineCompletion::Edit { edits, .. } => {
 5982                if let Some(provider) = self.edit_prediction_provider() {
 5983                    provider.accept(cx);
 5984                }
 5985
 5986                let snapshot = self.buffer.read(cx).snapshot(cx);
 5987                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5988
 5989                self.buffer.update(cx, |buffer, cx| {
 5990                    buffer.edit(edits.iter().cloned(), None, cx)
 5991                });
 5992
 5993                self.change_selections(None, window, cx, |s| {
 5994                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5995                });
 5996
 5997                self.update_visible_inline_completion(window, cx);
 5998                if self.active_inline_completion.is_none() {
 5999                    self.refresh_inline_completion(true, true, window, cx);
 6000                }
 6001
 6002                cx.notify();
 6003            }
 6004        }
 6005
 6006        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 6007    }
 6008
 6009    pub fn accept_partial_inline_completion(
 6010        &mut self,
 6011        _: &AcceptPartialEditPrediction,
 6012        window: &mut Window,
 6013        cx: &mut Context<Self>,
 6014    ) {
 6015        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 6016            return;
 6017        };
 6018        if self.selections.count() != 1 {
 6019            return;
 6020        }
 6021
 6022        self.report_inline_completion_event(
 6023            active_inline_completion.completion_id.clone(),
 6024            true,
 6025            cx,
 6026        );
 6027
 6028        match &active_inline_completion.completion {
 6029            InlineCompletion::Move { target, .. } => {
 6030                let target = *target;
 6031                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 6032                    selections.select_anchor_ranges([target..target]);
 6033                });
 6034            }
 6035            InlineCompletion::Edit { edits, .. } => {
 6036                // Find an insertion that starts at the cursor position.
 6037                let snapshot = self.buffer.read(cx).snapshot(cx);
 6038                let cursor_offset = self.selections.newest::<usize>(cx).head();
 6039                let insertion = edits.iter().find_map(|(range, text)| {
 6040                    let range = range.to_offset(&snapshot);
 6041                    if range.is_empty() && range.start == cursor_offset {
 6042                        Some(text)
 6043                    } else {
 6044                        None
 6045                    }
 6046                });
 6047
 6048                if let Some(text) = insertion {
 6049                    let mut partial_completion = text
 6050                        .chars()
 6051                        .by_ref()
 6052                        .take_while(|c| c.is_alphabetic())
 6053                        .collect::<String>();
 6054                    if partial_completion.is_empty() {
 6055                        partial_completion = text
 6056                            .chars()
 6057                            .by_ref()
 6058                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 6059                            .collect::<String>();
 6060                    }
 6061
 6062                    cx.emit(EditorEvent::InputHandled {
 6063                        utf16_range_to_replace: None,
 6064                        text: partial_completion.clone().into(),
 6065                    });
 6066
 6067                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 6068
 6069                    self.refresh_inline_completion(true, true, window, cx);
 6070                    cx.notify();
 6071                } else {
 6072                    self.accept_edit_prediction(&Default::default(), window, cx);
 6073                }
 6074            }
 6075        }
 6076    }
 6077
 6078    fn discard_inline_completion(
 6079        &mut self,
 6080        should_report_inline_completion_event: bool,
 6081        cx: &mut Context<Self>,
 6082    ) -> bool {
 6083        if should_report_inline_completion_event {
 6084            let completion_id = self
 6085                .active_inline_completion
 6086                .as_ref()
 6087                .and_then(|active_completion| active_completion.completion_id.clone());
 6088
 6089            self.report_inline_completion_event(completion_id, false, cx);
 6090        }
 6091
 6092        if let Some(provider) = self.edit_prediction_provider() {
 6093            provider.discard(cx);
 6094        }
 6095
 6096        self.take_active_inline_completion(cx)
 6097    }
 6098
 6099    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 6100        let Some(provider) = self.edit_prediction_provider() else {
 6101            return;
 6102        };
 6103
 6104        let Some((_, buffer, _)) = self
 6105            .buffer
 6106            .read(cx)
 6107            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 6108        else {
 6109            return;
 6110        };
 6111
 6112        let extension = buffer
 6113            .read(cx)
 6114            .file()
 6115            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 6116
 6117        let event_type = match accepted {
 6118            true => "Edit Prediction Accepted",
 6119            false => "Edit Prediction Discarded",
 6120        };
 6121        telemetry::event!(
 6122            event_type,
 6123            provider = provider.name(),
 6124            prediction_id = id,
 6125            suggestion_accepted = accepted,
 6126            file_extension = extension,
 6127        );
 6128    }
 6129
 6130    pub fn has_active_inline_completion(&self) -> bool {
 6131        self.active_inline_completion.is_some()
 6132    }
 6133
 6134    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 6135        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 6136            return false;
 6137        };
 6138
 6139        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 6140        self.clear_highlights::<InlineCompletionHighlight>(cx);
 6141        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 6142        true
 6143    }
 6144
 6145    /// Returns true when we're displaying the edit prediction popover below the cursor
 6146    /// like we are not previewing and the LSP autocomplete menu is visible
 6147    /// or we are in `when_holding_modifier` mode.
 6148    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 6149        if self.edit_prediction_preview_is_active()
 6150            || !self.show_edit_predictions_in_menu()
 6151            || !self.edit_predictions_enabled()
 6152        {
 6153            return false;
 6154        }
 6155
 6156        if self.has_visible_completions_menu() {
 6157            return true;
 6158        }
 6159
 6160        has_completion && self.edit_prediction_requires_modifier()
 6161    }
 6162
 6163    fn handle_modifiers_changed(
 6164        &mut self,
 6165        modifiers: Modifiers,
 6166        position_map: &PositionMap,
 6167        window: &mut Window,
 6168        cx: &mut Context<Self>,
 6169    ) {
 6170        if self.show_edit_predictions_in_menu() {
 6171            self.update_edit_prediction_preview(&modifiers, window, cx);
 6172        }
 6173
 6174        self.update_selection_mode(&modifiers, position_map, window, cx);
 6175
 6176        let mouse_position = window.mouse_position();
 6177        if !position_map.text_hitbox.is_hovered(window) {
 6178            return;
 6179        }
 6180
 6181        self.update_hovered_link(
 6182            position_map.point_for_position(mouse_position),
 6183            &position_map.snapshot,
 6184            modifiers,
 6185            window,
 6186            cx,
 6187        )
 6188    }
 6189
 6190    fn update_selection_mode(
 6191        &mut self,
 6192        modifiers: &Modifiers,
 6193        position_map: &PositionMap,
 6194        window: &mut Window,
 6195        cx: &mut Context<Self>,
 6196    ) {
 6197        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 6198            return;
 6199        }
 6200
 6201        let mouse_position = window.mouse_position();
 6202        let point_for_position = position_map.point_for_position(mouse_position);
 6203        let position = point_for_position.previous_valid;
 6204
 6205        self.select(
 6206            SelectPhase::BeginColumnar {
 6207                position,
 6208                reset: false,
 6209                goal_column: point_for_position.exact_unclipped.column(),
 6210            },
 6211            window,
 6212            cx,
 6213        );
 6214    }
 6215
 6216    fn update_edit_prediction_preview(
 6217        &mut self,
 6218        modifiers: &Modifiers,
 6219        window: &mut Window,
 6220        cx: &mut Context<Self>,
 6221    ) {
 6222        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 6223        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 6224            return;
 6225        };
 6226
 6227        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 6228            if matches!(
 6229                self.edit_prediction_preview,
 6230                EditPredictionPreview::Inactive { .. }
 6231            ) {
 6232                self.edit_prediction_preview = EditPredictionPreview::Active {
 6233                    previous_scroll_position: None,
 6234                    since: Instant::now(),
 6235                };
 6236
 6237                self.update_visible_inline_completion(window, cx);
 6238                cx.notify();
 6239            }
 6240        } else if let EditPredictionPreview::Active {
 6241            previous_scroll_position,
 6242            since,
 6243        } = self.edit_prediction_preview
 6244        {
 6245            if let (Some(previous_scroll_position), Some(position_map)) =
 6246                (previous_scroll_position, self.last_position_map.as_ref())
 6247            {
 6248                self.set_scroll_position(
 6249                    previous_scroll_position
 6250                        .scroll_position(&position_map.snapshot.display_snapshot),
 6251                    window,
 6252                    cx,
 6253                );
 6254            }
 6255
 6256            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 6257                released_too_fast: since.elapsed() < Duration::from_millis(200),
 6258            };
 6259            self.clear_row_highlights::<EditPredictionPreview>();
 6260            self.update_visible_inline_completion(window, cx);
 6261            cx.notify();
 6262        }
 6263    }
 6264
 6265    fn update_visible_inline_completion(
 6266        &mut self,
 6267        _window: &mut Window,
 6268        cx: &mut Context<Self>,
 6269    ) -> Option<()> {
 6270        let selection = self.selections.newest_anchor();
 6271        let cursor = selection.head();
 6272        let multibuffer = self.buffer.read(cx).snapshot(cx);
 6273        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 6274        let excerpt_id = cursor.excerpt_id;
 6275
 6276        let show_in_menu = self.show_edit_predictions_in_menu();
 6277        let completions_menu_has_precedence = !show_in_menu
 6278            && (self.context_menu.borrow().is_some()
 6279                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 6280
 6281        if completions_menu_has_precedence
 6282            || !offset_selection.is_empty()
 6283            || self
 6284                .active_inline_completion
 6285                .as_ref()
 6286                .map_or(false, |completion| {
 6287                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 6288                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 6289                    !invalidation_range.contains(&offset_selection.head())
 6290                })
 6291        {
 6292            self.discard_inline_completion(false, cx);
 6293            return None;
 6294        }
 6295
 6296        self.take_active_inline_completion(cx);
 6297        let Some(provider) = self.edit_prediction_provider() else {
 6298            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 6299            return None;
 6300        };
 6301
 6302        let (buffer, cursor_buffer_position) =
 6303            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 6304
 6305        self.edit_prediction_settings =
 6306            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 6307
 6308        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 6309
 6310        if self.edit_prediction_indent_conflict {
 6311            let cursor_point = cursor.to_point(&multibuffer);
 6312
 6313            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 6314
 6315            if let Some((_, indent)) = indents.iter().next() {
 6316                if indent.len == cursor_point.column {
 6317                    self.edit_prediction_indent_conflict = false;
 6318                }
 6319            }
 6320        }
 6321
 6322        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 6323        let edits = inline_completion
 6324            .edits
 6325            .into_iter()
 6326            .flat_map(|(range, new_text)| {
 6327                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 6328                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 6329                Some((start..end, new_text))
 6330            })
 6331            .collect::<Vec<_>>();
 6332        if edits.is_empty() {
 6333            return None;
 6334        }
 6335
 6336        let first_edit_start = edits.first().unwrap().0.start;
 6337        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 6338        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 6339
 6340        let last_edit_end = edits.last().unwrap().0.end;
 6341        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 6342        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 6343
 6344        let cursor_row = cursor.to_point(&multibuffer).row;
 6345
 6346        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 6347
 6348        let mut inlay_ids = Vec::new();
 6349        let invalidation_row_range;
 6350        let move_invalidation_row_range = if cursor_row < edit_start_row {
 6351            Some(cursor_row..edit_end_row)
 6352        } else if cursor_row > edit_end_row {
 6353            Some(edit_start_row..cursor_row)
 6354        } else {
 6355            None
 6356        };
 6357        let is_move =
 6358            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 6359        let completion = if is_move {
 6360            invalidation_row_range =
 6361                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 6362            let target = first_edit_start;
 6363            InlineCompletion::Move { target, snapshot }
 6364        } else {
 6365            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 6366                && !self.inline_completions_hidden_for_vim_mode;
 6367
 6368            if show_completions_in_buffer {
 6369                if edits
 6370                    .iter()
 6371                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 6372                {
 6373                    let mut inlays = Vec::new();
 6374                    for (range, new_text) in &edits {
 6375                        let inlay = Inlay::inline_completion(
 6376                            post_inc(&mut self.next_inlay_id),
 6377                            range.start,
 6378                            new_text.as_str(),
 6379                        );
 6380                        inlay_ids.push(inlay.id);
 6381                        inlays.push(inlay);
 6382                    }
 6383
 6384                    self.splice_inlays(&[], inlays, cx);
 6385                } else {
 6386                    let background_color = cx.theme().status().deleted_background;
 6387                    self.highlight_text::<InlineCompletionHighlight>(
 6388                        edits.iter().map(|(range, _)| range.clone()).collect(),
 6389                        HighlightStyle {
 6390                            background_color: Some(background_color),
 6391                            ..Default::default()
 6392                        },
 6393                        cx,
 6394                    );
 6395                }
 6396            }
 6397
 6398            invalidation_row_range = edit_start_row..edit_end_row;
 6399
 6400            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 6401                if provider.show_tab_accept_marker() {
 6402                    EditDisplayMode::TabAccept
 6403                } else {
 6404                    EditDisplayMode::Inline
 6405                }
 6406            } else {
 6407                EditDisplayMode::DiffPopover
 6408            };
 6409
 6410            InlineCompletion::Edit {
 6411                edits,
 6412                edit_preview: inline_completion.edit_preview,
 6413                display_mode,
 6414                snapshot,
 6415            }
 6416        };
 6417
 6418        let invalidation_range = multibuffer
 6419            .anchor_before(Point::new(invalidation_row_range.start, 0))
 6420            ..multibuffer.anchor_after(Point::new(
 6421                invalidation_row_range.end,
 6422                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 6423            ));
 6424
 6425        self.stale_inline_completion_in_menu = None;
 6426        self.active_inline_completion = Some(InlineCompletionState {
 6427            inlay_ids,
 6428            completion,
 6429            completion_id: inline_completion.id,
 6430            invalidation_range,
 6431        });
 6432
 6433        cx.notify();
 6434
 6435        Some(())
 6436    }
 6437
 6438    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 6439        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 6440    }
 6441
 6442    fn render_code_actions_indicator(
 6443        &self,
 6444        _style: &EditorStyle,
 6445        row: DisplayRow,
 6446        is_active: bool,
 6447        breakpoint: Option<&(Anchor, Breakpoint)>,
 6448        cx: &mut Context<Self>,
 6449    ) -> Option<IconButton> {
 6450        let color = Color::Muted;
 6451        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6452        let show_tooltip = !self.context_menu_visible();
 6453
 6454        if self.available_code_actions.is_some() {
 6455            Some(
 6456                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 6457                    .shape(ui::IconButtonShape::Square)
 6458                    .icon_size(IconSize::XSmall)
 6459                    .icon_color(color)
 6460                    .toggle_state(is_active)
 6461                    .when(show_tooltip, |this| {
 6462                        this.tooltip({
 6463                            let focus_handle = self.focus_handle.clone();
 6464                            move |window, cx| {
 6465                                Tooltip::for_action_in(
 6466                                    "Toggle Code Actions",
 6467                                    &ToggleCodeActions {
 6468                                        deployed_from_indicator: None,
 6469                                    },
 6470                                    &focus_handle,
 6471                                    window,
 6472                                    cx,
 6473                                )
 6474                            }
 6475                        })
 6476                    })
 6477                    .on_click(cx.listener(move |editor, _e, window, cx| {
 6478                        window.focus(&editor.focus_handle(cx));
 6479                        editor.toggle_code_actions(
 6480                            &ToggleCodeActions {
 6481                                deployed_from_indicator: Some(row),
 6482                            },
 6483                            window,
 6484                            cx,
 6485                        );
 6486                    }))
 6487                    .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6488                        editor.set_breakpoint_context_menu(
 6489                            row,
 6490                            position,
 6491                            event.down.position,
 6492                            window,
 6493                            cx,
 6494                        );
 6495                    })),
 6496            )
 6497        } else {
 6498            None
 6499        }
 6500    }
 6501
 6502    fn clear_tasks(&mut self) {
 6503        self.tasks.clear()
 6504    }
 6505
 6506    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 6507        if self.tasks.insert(key, value).is_some() {
 6508            // This case should hopefully be rare, but just in case...
 6509            log::error!(
 6510                "multiple different run targets found on a single line, only the last target will be rendered"
 6511            )
 6512        }
 6513    }
 6514
 6515    /// Get all display points of breakpoints that will be rendered within editor
 6516    ///
 6517    /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
 6518    /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
 6519    /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
 6520    fn active_breakpoints(
 6521        &self,
 6522        range: Range<DisplayRow>,
 6523        window: &mut Window,
 6524        cx: &mut Context<Self>,
 6525    ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
 6526        let mut breakpoint_display_points = HashMap::default();
 6527
 6528        let Some(breakpoint_store) = self.breakpoint_store.clone() else {
 6529            return breakpoint_display_points;
 6530        };
 6531
 6532        let snapshot = self.snapshot(window, cx);
 6533
 6534        let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
 6535        let Some(project) = self.project.as_ref() else {
 6536            return breakpoint_display_points;
 6537        };
 6538
 6539        let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
 6540            ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
 6541
 6542        for (buffer_snapshot, range, excerpt_id) in
 6543            multi_buffer_snapshot.range_to_buffer_ranges(range)
 6544        {
 6545            let Some(buffer) = project.read_with(cx, |this, cx| {
 6546                this.buffer_for_id(buffer_snapshot.remote_id(), cx)
 6547            }) else {
 6548                continue;
 6549            };
 6550            let breakpoints = breakpoint_store.read(cx).breakpoints(
 6551                &buffer,
 6552                Some(
 6553                    buffer_snapshot.anchor_before(range.start)
 6554                        ..buffer_snapshot.anchor_after(range.end),
 6555                ),
 6556                buffer_snapshot,
 6557                cx,
 6558            );
 6559            for (anchor, breakpoint) in breakpoints {
 6560                let multi_buffer_anchor =
 6561                    Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
 6562                let position = multi_buffer_anchor
 6563                    .to_point(&multi_buffer_snapshot)
 6564                    .to_display_point(&snapshot);
 6565
 6566                breakpoint_display_points
 6567                    .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
 6568            }
 6569        }
 6570
 6571        breakpoint_display_points
 6572    }
 6573
 6574    fn breakpoint_context_menu(
 6575        &self,
 6576        anchor: Anchor,
 6577        window: &mut Window,
 6578        cx: &mut Context<Self>,
 6579    ) -> Entity<ui::ContextMenu> {
 6580        let weak_editor = cx.weak_entity();
 6581        let focus_handle = self.focus_handle(cx);
 6582
 6583        let row = self
 6584            .buffer
 6585            .read(cx)
 6586            .snapshot(cx)
 6587            .summary_for_anchor::<Point>(&anchor)
 6588            .row;
 6589
 6590        let breakpoint = self
 6591            .breakpoint_at_row(row, window, cx)
 6592            .map(|(anchor, bp)| (anchor, Arc::from(bp)));
 6593
 6594        let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
 6595            "Edit Log Breakpoint"
 6596        } else {
 6597            "Set Log Breakpoint"
 6598        };
 6599
 6600        let condition_breakpoint_msg = if breakpoint
 6601            .as_ref()
 6602            .is_some_and(|bp| bp.1.condition.is_some())
 6603        {
 6604            "Edit Condition Breakpoint"
 6605        } else {
 6606            "Set Condition Breakpoint"
 6607        };
 6608
 6609        let hit_condition_breakpoint_msg = if breakpoint
 6610            .as_ref()
 6611            .is_some_and(|bp| bp.1.hit_condition.is_some())
 6612        {
 6613            "Edit Hit Condition Breakpoint"
 6614        } else {
 6615            "Set Hit Condition Breakpoint"
 6616        };
 6617
 6618        let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
 6619            "Unset Breakpoint"
 6620        } else {
 6621            "Set Breakpoint"
 6622        };
 6623
 6624        let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
 6625            .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
 6626
 6627        let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
 6628            BreakpointState::Enabled => Some("Disable"),
 6629            BreakpointState::Disabled => Some("Enable"),
 6630        });
 6631
 6632        let (anchor, breakpoint) =
 6633            breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
 6634
 6635        ui::ContextMenu::build(window, cx, |menu, _, _cx| {
 6636            menu.on_blur_subscription(Subscription::new(|| {}))
 6637                .context(focus_handle)
 6638                .when(run_to_cursor, |this| {
 6639                    let weak_editor = weak_editor.clone();
 6640                    this.entry("Run to cursor", None, move |window, cx| {
 6641                        weak_editor
 6642                            .update(cx, |editor, cx| {
 6643                                editor.change_selections(None, window, cx, |s| {
 6644                                    s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
 6645                                });
 6646                            })
 6647                            .ok();
 6648
 6649                        window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
 6650                    })
 6651                    .separator()
 6652                })
 6653                .when_some(toggle_state_msg, |this, msg| {
 6654                    this.entry(msg, None, {
 6655                        let weak_editor = weak_editor.clone();
 6656                        let breakpoint = breakpoint.clone();
 6657                        move |_window, cx| {
 6658                            weak_editor
 6659                                .update(cx, |this, cx| {
 6660                                    this.edit_breakpoint_at_anchor(
 6661                                        anchor,
 6662                                        breakpoint.as_ref().clone(),
 6663                                        BreakpointEditAction::InvertState,
 6664                                        cx,
 6665                                    );
 6666                                })
 6667                                .log_err();
 6668                        }
 6669                    })
 6670                })
 6671                .entry(set_breakpoint_msg, None, {
 6672                    let weak_editor = weak_editor.clone();
 6673                    let breakpoint = breakpoint.clone();
 6674                    move |_window, cx| {
 6675                        weak_editor
 6676                            .update(cx, |this, cx| {
 6677                                this.edit_breakpoint_at_anchor(
 6678                                    anchor,
 6679                                    breakpoint.as_ref().clone(),
 6680                                    BreakpointEditAction::Toggle,
 6681                                    cx,
 6682                                );
 6683                            })
 6684                            .log_err();
 6685                    }
 6686                })
 6687                .entry(log_breakpoint_msg, None, {
 6688                    let breakpoint = breakpoint.clone();
 6689                    let weak_editor = weak_editor.clone();
 6690                    move |window, cx| {
 6691                        weak_editor
 6692                            .update(cx, |this, cx| {
 6693                                this.add_edit_breakpoint_block(
 6694                                    anchor,
 6695                                    breakpoint.as_ref(),
 6696                                    BreakpointPromptEditAction::Log,
 6697                                    window,
 6698                                    cx,
 6699                                );
 6700                            })
 6701                            .log_err();
 6702                    }
 6703                })
 6704                .entry(condition_breakpoint_msg, None, {
 6705                    let breakpoint = breakpoint.clone();
 6706                    let weak_editor = weak_editor.clone();
 6707                    move |window, cx| {
 6708                        weak_editor
 6709                            .update(cx, |this, cx| {
 6710                                this.add_edit_breakpoint_block(
 6711                                    anchor,
 6712                                    breakpoint.as_ref(),
 6713                                    BreakpointPromptEditAction::Condition,
 6714                                    window,
 6715                                    cx,
 6716                                );
 6717                            })
 6718                            .log_err();
 6719                    }
 6720                })
 6721                .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
 6722                    weak_editor
 6723                        .update(cx, |this, cx| {
 6724                            this.add_edit_breakpoint_block(
 6725                                anchor,
 6726                                breakpoint.as_ref(),
 6727                                BreakpointPromptEditAction::HitCondition,
 6728                                window,
 6729                                cx,
 6730                            );
 6731                        })
 6732                        .log_err();
 6733                })
 6734        })
 6735    }
 6736
 6737    fn render_breakpoint(
 6738        &self,
 6739        position: Anchor,
 6740        row: DisplayRow,
 6741        breakpoint: &Breakpoint,
 6742        cx: &mut Context<Self>,
 6743    ) -> IconButton {
 6744        let (color, icon) = {
 6745            let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
 6746                (false, false) => ui::IconName::DebugBreakpoint,
 6747                (true, false) => ui::IconName::DebugLogBreakpoint,
 6748                (false, true) => ui::IconName::DebugDisabledBreakpoint,
 6749                (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
 6750            };
 6751
 6752            let color = if self
 6753                .gutter_breakpoint_indicator
 6754                .0
 6755                .is_some_and(|(point, is_visible)| is_visible && point.row() == row)
 6756            {
 6757                Color::Hint
 6758            } else {
 6759                Color::Debugger
 6760            };
 6761
 6762            (color, icon)
 6763        };
 6764
 6765        let breakpoint = Arc::from(breakpoint.clone());
 6766
 6767        IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
 6768            .icon_size(IconSize::XSmall)
 6769            .size(ui::ButtonSize::None)
 6770            .icon_color(color)
 6771            .style(ButtonStyle::Transparent)
 6772            .on_click(cx.listener({
 6773                let breakpoint = breakpoint.clone();
 6774
 6775                move |editor, event: &ClickEvent, window, cx| {
 6776                    let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
 6777                        BreakpointEditAction::InvertState
 6778                    } else {
 6779                        BreakpointEditAction::Toggle
 6780                    };
 6781
 6782                    window.focus(&editor.focus_handle(cx));
 6783                    editor.edit_breakpoint_at_anchor(
 6784                        position,
 6785                        breakpoint.as_ref().clone(),
 6786                        edit_action,
 6787                        cx,
 6788                    );
 6789                }
 6790            }))
 6791            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6792                editor.set_breakpoint_context_menu(
 6793                    row,
 6794                    Some(position),
 6795                    event.down.position,
 6796                    window,
 6797                    cx,
 6798                );
 6799            }))
 6800    }
 6801
 6802    fn build_tasks_context(
 6803        project: &Entity<Project>,
 6804        buffer: &Entity<Buffer>,
 6805        buffer_row: u32,
 6806        tasks: &Arc<RunnableTasks>,
 6807        cx: &mut Context<Self>,
 6808    ) -> Task<Option<task::TaskContext>> {
 6809        let position = Point::new(buffer_row, tasks.column);
 6810        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 6811        let location = Location {
 6812            buffer: buffer.clone(),
 6813            range: range_start..range_start,
 6814        };
 6815        // Fill in the environmental variables from the tree-sitter captures
 6816        let mut captured_task_variables = TaskVariables::default();
 6817        for (capture_name, value) in tasks.extra_variables.clone() {
 6818            captured_task_variables.insert(
 6819                task::VariableName::Custom(capture_name.into()),
 6820                value.clone(),
 6821            );
 6822        }
 6823        project.update(cx, |project, cx| {
 6824            project.task_store().update(cx, |task_store, cx| {
 6825                task_store.task_context_for_location(captured_task_variables, location, cx)
 6826            })
 6827        })
 6828    }
 6829
 6830    pub fn spawn_nearest_task(
 6831        &mut self,
 6832        action: &SpawnNearestTask,
 6833        window: &mut Window,
 6834        cx: &mut Context<Self>,
 6835    ) {
 6836        let Some((workspace, _)) = self.workspace.clone() else {
 6837            return;
 6838        };
 6839        let Some(project) = self.project.clone() else {
 6840            return;
 6841        };
 6842
 6843        // Try to find a closest, enclosing node using tree-sitter that has a
 6844        // task
 6845        let Some((buffer, buffer_row, tasks)) = self
 6846            .find_enclosing_node_task(cx)
 6847            // Or find the task that's closest in row-distance.
 6848            .or_else(|| self.find_closest_task(cx))
 6849        else {
 6850            return;
 6851        };
 6852
 6853        let reveal_strategy = action.reveal;
 6854        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 6855        cx.spawn_in(window, async move |_, cx| {
 6856            let context = task_context.await?;
 6857            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 6858
 6859            let resolved = resolved_task.resolved.as_mut()?;
 6860            resolved.reveal = reveal_strategy;
 6861
 6862            workspace
 6863                .update_in(cx, |workspace, window, cx| {
 6864                    workspace.schedule_resolved_task(
 6865                        task_source_kind,
 6866                        resolved_task,
 6867                        false,
 6868                        window,
 6869                        cx,
 6870                    );
 6871                })
 6872                .ok()
 6873        })
 6874        .detach();
 6875    }
 6876
 6877    fn find_closest_task(
 6878        &mut self,
 6879        cx: &mut Context<Self>,
 6880    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6881        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 6882
 6883        let ((buffer_id, row), tasks) = self
 6884            .tasks
 6885            .iter()
 6886            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 6887
 6888        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 6889        let tasks = Arc::new(tasks.to_owned());
 6890        Some((buffer, *row, tasks))
 6891    }
 6892
 6893    fn find_enclosing_node_task(
 6894        &mut self,
 6895        cx: &mut Context<Self>,
 6896    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6897        let snapshot = self.buffer.read(cx).snapshot(cx);
 6898        let offset = self.selections.newest::<usize>(cx).head();
 6899        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 6900        let buffer_id = excerpt.buffer().remote_id();
 6901
 6902        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 6903        let mut cursor = layer.node().walk();
 6904
 6905        while cursor.goto_first_child_for_byte(offset).is_some() {
 6906            if cursor.node().end_byte() == offset {
 6907                cursor.goto_next_sibling();
 6908            }
 6909        }
 6910
 6911        // Ascend to the smallest ancestor that contains the range and has a task.
 6912        loop {
 6913            let node = cursor.node();
 6914            let node_range = node.byte_range();
 6915            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 6916
 6917            // Check if this node contains our offset
 6918            if node_range.start <= offset && node_range.end >= offset {
 6919                // If it contains offset, check for task
 6920                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 6921                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 6922                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 6923                }
 6924            }
 6925
 6926            if !cursor.goto_parent() {
 6927                break;
 6928            }
 6929        }
 6930        None
 6931    }
 6932
 6933    fn render_run_indicator(
 6934        &self,
 6935        _style: &EditorStyle,
 6936        is_active: bool,
 6937        row: DisplayRow,
 6938        breakpoint: Option<(Anchor, Breakpoint)>,
 6939        cx: &mut Context<Self>,
 6940    ) -> IconButton {
 6941        let color = Color::Muted;
 6942        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6943
 6944        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 6945            .shape(ui::IconButtonShape::Square)
 6946            .icon_size(IconSize::XSmall)
 6947            .icon_color(color)
 6948            .toggle_state(is_active)
 6949            .on_click(cx.listener(move |editor, _e, window, cx| {
 6950                window.focus(&editor.focus_handle(cx));
 6951                editor.toggle_code_actions(
 6952                    &ToggleCodeActions {
 6953                        deployed_from_indicator: Some(row),
 6954                    },
 6955                    window,
 6956                    cx,
 6957                );
 6958            }))
 6959            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6960                editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
 6961            }))
 6962    }
 6963
 6964    pub fn context_menu_visible(&self) -> bool {
 6965        !self.edit_prediction_preview_is_active()
 6966            && self
 6967                .context_menu
 6968                .borrow()
 6969                .as_ref()
 6970                .map_or(false, |menu| menu.visible())
 6971    }
 6972
 6973    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 6974        self.context_menu
 6975            .borrow()
 6976            .as_ref()
 6977            .map(|menu| menu.origin())
 6978    }
 6979
 6980    pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
 6981        self.context_menu_options = Some(options);
 6982    }
 6983
 6984    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 6985    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 6986
 6987    fn render_edit_prediction_popover(
 6988        &mut self,
 6989        text_bounds: &Bounds<Pixels>,
 6990        content_origin: gpui::Point<Pixels>,
 6991        editor_snapshot: &EditorSnapshot,
 6992        visible_row_range: Range<DisplayRow>,
 6993        scroll_top: f32,
 6994        scroll_bottom: f32,
 6995        line_layouts: &[LineWithInvisibles],
 6996        line_height: Pixels,
 6997        scroll_pixel_position: gpui::Point<Pixels>,
 6998        newest_selection_head: Option<DisplayPoint>,
 6999        editor_width: Pixels,
 7000        style: &EditorStyle,
 7001        window: &mut Window,
 7002        cx: &mut App,
 7003    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7004        let active_inline_completion = self.active_inline_completion.as_ref()?;
 7005
 7006        if self.edit_prediction_visible_in_cursor_popover(true) {
 7007            return None;
 7008        }
 7009
 7010        match &active_inline_completion.completion {
 7011            InlineCompletion::Move { target, .. } => {
 7012                let target_display_point = target.to_display_point(editor_snapshot);
 7013
 7014                if self.edit_prediction_requires_modifier() {
 7015                    if !self.edit_prediction_preview_is_active() {
 7016                        return None;
 7017                    }
 7018
 7019                    self.render_edit_prediction_modifier_jump_popover(
 7020                        text_bounds,
 7021                        content_origin,
 7022                        visible_row_range,
 7023                        line_layouts,
 7024                        line_height,
 7025                        scroll_pixel_position,
 7026                        newest_selection_head,
 7027                        target_display_point,
 7028                        window,
 7029                        cx,
 7030                    )
 7031                } else {
 7032                    self.render_edit_prediction_eager_jump_popover(
 7033                        text_bounds,
 7034                        content_origin,
 7035                        editor_snapshot,
 7036                        visible_row_range,
 7037                        scroll_top,
 7038                        scroll_bottom,
 7039                        line_height,
 7040                        scroll_pixel_position,
 7041                        target_display_point,
 7042                        editor_width,
 7043                        window,
 7044                        cx,
 7045                    )
 7046                }
 7047            }
 7048            InlineCompletion::Edit {
 7049                display_mode: EditDisplayMode::Inline,
 7050                ..
 7051            } => None,
 7052            InlineCompletion::Edit {
 7053                display_mode: EditDisplayMode::TabAccept,
 7054                edits,
 7055                ..
 7056            } => {
 7057                let range = &edits.first()?.0;
 7058                let target_display_point = range.end.to_display_point(editor_snapshot);
 7059
 7060                self.render_edit_prediction_end_of_line_popover(
 7061                    "Accept",
 7062                    editor_snapshot,
 7063                    visible_row_range,
 7064                    target_display_point,
 7065                    line_height,
 7066                    scroll_pixel_position,
 7067                    content_origin,
 7068                    editor_width,
 7069                    window,
 7070                    cx,
 7071                )
 7072            }
 7073            InlineCompletion::Edit {
 7074                edits,
 7075                edit_preview,
 7076                display_mode: EditDisplayMode::DiffPopover,
 7077                snapshot,
 7078            } => self.render_edit_prediction_diff_popover(
 7079                text_bounds,
 7080                content_origin,
 7081                editor_snapshot,
 7082                visible_row_range,
 7083                line_layouts,
 7084                line_height,
 7085                scroll_pixel_position,
 7086                newest_selection_head,
 7087                editor_width,
 7088                style,
 7089                edits,
 7090                edit_preview,
 7091                snapshot,
 7092                window,
 7093                cx,
 7094            ),
 7095        }
 7096    }
 7097
 7098    fn render_edit_prediction_modifier_jump_popover(
 7099        &mut self,
 7100        text_bounds: &Bounds<Pixels>,
 7101        content_origin: gpui::Point<Pixels>,
 7102        visible_row_range: Range<DisplayRow>,
 7103        line_layouts: &[LineWithInvisibles],
 7104        line_height: Pixels,
 7105        scroll_pixel_position: gpui::Point<Pixels>,
 7106        newest_selection_head: Option<DisplayPoint>,
 7107        target_display_point: DisplayPoint,
 7108        window: &mut Window,
 7109        cx: &mut App,
 7110    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7111        let scrolled_content_origin =
 7112            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 7113
 7114        const SCROLL_PADDING_Y: Pixels = px(12.);
 7115
 7116        if target_display_point.row() < visible_row_range.start {
 7117            return self.render_edit_prediction_scroll_popover(
 7118                |_| SCROLL_PADDING_Y,
 7119                IconName::ArrowUp,
 7120                visible_row_range,
 7121                line_layouts,
 7122                newest_selection_head,
 7123                scrolled_content_origin,
 7124                window,
 7125                cx,
 7126            );
 7127        } else if target_display_point.row() >= visible_row_range.end {
 7128            return self.render_edit_prediction_scroll_popover(
 7129                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 7130                IconName::ArrowDown,
 7131                visible_row_range,
 7132                line_layouts,
 7133                newest_selection_head,
 7134                scrolled_content_origin,
 7135                window,
 7136                cx,
 7137            );
 7138        }
 7139
 7140        const POLE_WIDTH: Pixels = px(2.);
 7141
 7142        let line_layout =
 7143            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 7144        let target_column = target_display_point.column() as usize;
 7145
 7146        let target_x = line_layout.x_for_index(target_column);
 7147        let target_y =
 7148            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 7149
 7150        let flag_on_right = target_x < text_bounds.size.width / 2.;
 7151
 7152        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 7153        border_color.l += 0.001;
 7154
 7155        let mut element = v_flex()
 7156            .items_end()
 7157            .when(flag_on_right, |el| el.items_start())
 7158            .child(if flag_on_right {
 7159                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7160                    .rounded_bl(px(0.))
 7161                    .rounded_tl(px(0.))
 7162                    .border_l_2()
 7163                    .border_color(border_color)
 7164            } else {
 7165                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7166                    .rounded_br(px(0.))
 7167                    .rounded_tr(px(0.))
 7168                    .border_r_2()
 7169                    .border_color(border_color)
 7170            })
 7171            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 7172            .into_any();
 7173
 7174        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7175
 7176        let mut origin = scrolled_content_origin + point(target_x, target_y)
 7177            - point(
 7178                if flag_on_right {
 7179                    POLE_WIDTH
 7180                } else {
 7181                    size.width - POLE_WIDTH
 7182                },
 7183                size.height - line_height,
 7184            );
 7185
 7186        origin.x = origin.x.max(content_origin.x);
 7187
 7188        element.prepaint_at(origin, window, cx);
 7189
 7190        Some((element, origin))
 7191    }
 7192
 7193    fn render_edit_prediction_scroll_popover(
 7194        &mut self,
 7195        to_y: impl Fn(Size<Pixels>) -> Pixels,
 7196        scroll_icon: IconName,
 7197        visible_row_range: Range<DisplayRow>,
 7198        line_layouts: &[LineWithInvisibles],
 7199        newest_selection_head: Option<DisplayPoint>,
 7200        scrolled_content_origin: gpui::Point<Pixels>,
 7201        window: &mut Window,
 7202        cx: &mut App,
 7203    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7204        let mut element = self
 7205            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 7206            .into_any();
 7207
 7208        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7209
 7210        let cursor = newest_selection_head?;
 7211        let cursor_row_layout =
 7212            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 7213        let cursor_column = cursor.column() as usize;
 7214
 7215        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 7216
 7217        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 7218
 7219        element.prepaint_at(origin, window, cx);
 7220        Some((element, origin))
 7221    }
 7222
 7223    fn render_edit_prediction_eager_jump_popover(
 7224        &mut self,
 7225        text_bounds: &Bounds<Pixels>,
 7226        content_origin: gpui::Point<Pixels>,
 7227        editor_snapshot: &EditorSnapshot,
 7228        visible_row_range: Range<DisplayRow>,
 7229        scroll_top: f32,
 7230        scroll_bottom: f32,
 7231        line_height: Pixels,
 7232        scroll_pixel_position: gpui::Point<Pixels>,
 7233        target_display_point: DisplayPoint,
 7234        editor_width: Pixels,
 7235        window: &mut Window,
 7236        cx: &mut App,
 7237    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7238        if target_display_point.row().as_f32() < scroll_top {
 7239            let mut element = self
 7240                .render_edit_prediction_line_popover(
 7241                    "Jump to Edit",
 7242                    Some(IconName::ArrowUp),
 7243                    window,
 7244                    cx,
 7245                )?
 7246                .into_any();
 7247
 7248            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7249            let offset = point(
 7250                (text_bounds.size.width - size.width) / 2.,
 7251                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7252            );
 7253
 7254            let origin = text_bounds.origin + offset;
 7255            element.prepaint_at(origin, window, cx);
 7256            Some((element, origin))
 7257        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 7258            let mut element = self
 7259                .render_edit_prediction_line_popover(
 7260                    "Jump to Edit",
 7261                    Some(IconName::ArrowDown),
 7262                    window,
 7263                    cx,
 7264                )?
 7265                .into_any();
 7266
 7267            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7268            let offset = point(
 7269                (text_bounds.size.width - size.width) / 2.,
 7270                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7271            );
 7272
 7273            let origin = text_bounds.origin + offset;
 7274            element.prepaint_at(origin, window, cx);
 7275            Some((element, origin))
 7276        } else {
 7277            self.render_edit_prediction_end_of_line_popover(
 7278                "Jump to Edit",
 7279                editor_snapshot,
 7280                visible_row_range,
 7281                target_display_point,
 7282                line_height,
 7283                scroll_pixel_position,
 7284                content_origin,
 7285                editor_width,
 7286                window,
 7287                cx,
 7288            )
 7289        }
 7290    }
 7291
 7292    fn render_edit_prediction_end_of_line_popover(
 7293        self: &mut Editor,
 7294        label: &'static str,
 7295        editor_snapshot: &EditorSnapshot,
 7296        visible_row_range: Range<DisplayRow>,
 7297        target_display_point: DisplayPoint,
 7298        line_height: Pixels,
 7299        scroll_pixel_position: gpui::Point<Pixels>,
 7300        content_origin: gpui::Point<Pixels>,
 7301        editor_width: Pixels,
 7302        window: &mut Window,
 7303        cx: &mut App,
 7304    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7305        let target_line_end = DisplayPoint::new(
 7306            target_display_point.row(),
 7307            editor_snapshot.line_len(target_display_point.row()),
 7308        );
 7309
 7310        let mut element = self
 7311            .render_edit_prediction_line_popover(label, None, window, cx)?
 7312            .into_any();
 7313
 7314        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7315
 7316        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 7317
 7318        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 7319        let mut origin = start_point
 7320            + line_origin
 7321            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 7322        origin.x = origin.x.max(content_origin.x);
 7323
 7324        let max_x = content_origin.x + editor_width - size.width;
 7325
 7326        if origin.x > max_x {
 7327            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 7328
 7329            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 7330                origin.y += offset;
 7331                IconName::ArrowUp
 7332            } else {
 7333                origin.y -= offset;
 7334                IconName::ArrowDown
 7335            };
 7336
 7337            element = self
 7338                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 7339                .into_any();
 7340
 7341            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7342
 7343            origin.x = content_origin.x + editor_width - size.width - px(2.);
 7344        }
 7345
 7346        element.prepaint_at(origin, window, cx);
 7347        Some((element, origin))
 7348    }
 7349
 7350    fn render_edit_prediction_diff_popover(
 7351        self: &Editor,
 7352        text_bounds: &Bounds<Pixels>,
 7353        content_origin: gpui::Point<Pixels>,
 7354        editor_snapshot: &EditorSnapshot,
 7355        visible_row_range: Range<DisplayRow>,
 7356        line_layouts: &[LineWithInvisibles],
 7357        line_height: Pixels,
 7358        scroll_pixel_position: gpui::Point<Pixels>,
 7359        newest_selection_head: Option<DisplayPoint>,
 7360        editor_width: Pixels,
 7361        style: &EditorStyle,
 7362        edits: &Vec<(Range<Anchor>, String)>,
 7363        edit_preview: &Option<language::EditPreview>,
 7364        snapshot: &language::BufferSnapshot,
 7365        window: &mut Window,
 7366        cx: &mut App,
 7367    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7368        let edit_start = edits
 7369            .first()
 7370            .unwrap()
 7371            .0
 7372            .start
 7373            .to_display_point(editor_snapshot);
 7374        let edit_end = edits
 7375            .last()
 7376            .unwrap()
 7377            .0
 7378            .end
 7379            .to_display_point(editor_snapshot);
 7380
 7381        let is_visible = visible_row_range.contains(&edit_start.row())
 7382            || visible_row_range.contains(&edit_end.row());
 7383        if !is_visible {
 7384            return None;
 7385        }
 7386
 7387        let highlighted_edits =
 7388            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 7389
 7390        let styled_text = highlighted_edits.to_styled_text(&style.text);
 7391        let line_count = highlighted_edits.text.lines().count();
 7392
 7393        const BORDER_WIDTH: Pixels = px(1.);
 7394
 7395        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7396        let has_keybind = keybind.is_some();
 7397
 7398        let mut element = h_flex()
 7399            .items_start()
 7400            .child(
 7401                h_flex()
 7402                    .bg(cx.theme().colors().editor_background)
 7403                    .border(BORDER_WIDTH)
 7404                    .shadow_sm()
 7405                    .border_color(cx.theme().colors().border)
 7406                    .rounded_l_lg()
 7407                    .when(line_count > 1, |el| el.rounded_br_lg())
 7408                    .pr_1()
 7409                    .child(styled_text),
 7410            )
 7411            .child(
 7412                h_flex()
 7413                    .h(line_height + BORDER_WIDTH * 2.)
 7414                    .px_1p5()
 7415                    .gap_1()
 7416                    // Workaround: For some reason, there's a gap if we don't do this
 7417                    .ml(-BORDER_WIDTH)
 7418                    .shadow(smallvec![gpui::BoxShadow {
 7419                        color: gpui::black().opacity(0.05),
 7420                        offset: point(px(1.), px(1.)),
 7421                        blur_radius: px(2.),
 7422                        spread_radius: px(0.),
 7423                    }])
 7424                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 7425                    .border(BORDER_WIDTH)
 7426                    .border_color(cx.theme().colors().border)
 7427                    .rounded_r_lg()
 7428                    .id("edit_prediction_diff_popover_keybind")
 7429                    .when(!has_keybind, |el| {
 7430                        let status_colors = cx.theme().status();
 7431
 7432                        el.bg(status_colors.error_background)
 7433                            .border_color(status_colors.error.opacity(0.6))
 7434                            .child(Icon::new(IconName::Info).color(Color::Error))
 7435                            .cursor_default()
 7436                            .hoverable_tooltip(move |_window, cx| {
 7437                                cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7438                            })
 7439                    })
 7440                    .children(keybind),
 7441            )
 7442            .into_any();
 7443
 7444        let longest_row =
 7445            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 7446        let longest_line_width = if visible_row_range.contains(&longest_row) {
 7447            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 7448        } else {
 7449            layout_line(
 7450                longest_row,
 7451                editor_snapshot,
 7452                style,
 7453                editor_width,
 7454                |_| false,
 7455                window,
 7456                cx,
 7457            )
 7458            .width
 7459        };
 7460
 7461        let viewport_bounds =
 7462            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 7463                right: -EditorElement::SCROLLBAR_WIDTH,
 7464                ..Default::default()
 7465            });
 7466
 7467        let x_after_longest =
 7468            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 7469                - scroll_pixel_position.x;
 7470
 7471        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7472
 7473        // Fully visible if it can be displayed within the window (allow overlapping other
 7474        // panes). However, this is only allowed if the popover starts within text_bounds.
 7475        let can_position_to_the_right = x_after_longest < text_bounds.right()
 7476            && x_after_longest + element_bounds.width < viewport_bounds.right();
 7477
 7478        let mut origin = if can_position_to_the_right {
 7479            point(
 7480                x_after_longest,
 7481                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 7482                    - scroll_pixel_position.y,
 7483            )
 7484        } else {
 7485            let cursor_row = newest_selection_head.map(|head| head.row());
 7486            let above_edit = edit_start
 7487                .row()
 7488                .0
 7489                .checked_sub(line_count as u32)
 7490                .map(DisplayRow);
 7491            let below_edit = Some(edit_end.row() + 1);
 7492            let above_cursor =
 7493                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 7494            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 7495
 7496            // Place the edit popover adjacent to the edit if there is a location
 7497            // available that is onscreen and does not obscure the cursor. Otherwise,
 7498            // place it adjacent to the cursor.
 7499            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 7500                .into_iter()
 7501                .flatten()
 7502                .find(|&start_row| {
 7503                    let end_row = start_row + line_count as u32;
 7504                    visible_row_range.contains(&start_row)
 7505                        && visible_row_range.contains(&end_row)
 7506                        && cursor_row.map_or(true, |cursor_row| {
 7507                            !((start_row..end_row).contains(&cursor_row))
 7508                        })
 7509                })?;
 7510
 7511            content_origin
 7512                + point(
 7513                    -scroll_pixel_position.x,
 7514                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 7515                )
 7516        };
 7517
 7518        origin.x -= BORDER_WIDTH;
 7519
 7520        window.defer_draw(element, origin, 1);
 7521
 7522        // Do not return an element, since it will already be drawn due to defer_draw.
 7523        None
 7524    }
 7525
 7526    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 7527        px(30.)
 7528    }
 7529
 7530    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 7531        if self.read_only(cx) {
 7532            cx.theme().players().read_only()
 7533        } else {
 7534            self.style.as_ref().unwrap().local_player
 7535        }
 7536    }
 7537
 7538    fn render_edit_prediction_accept_keybind(
 7539        &self,
 7540        window: &mut Window,
 7541        cx: &App,
 7542    ) -> Option<AnyElement> {
 7543        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 7544        let accept_keystroke = accept_binding.keystroke()?;
 7545
 7546        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7547
 7548        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 7549            Color::Accent
 7550        } else {
 7551            Color::Muted
 7552        };
 7553
 7554        h_flex()
 7555            .px_0p5()
 7556            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 7557            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7558            .text_size(TextSize::XSmall.rems(cx))
 7559            .child(h_flex().children(ui::render_modifiers(
 7560                &accept_keystroke.modifiers,
 7561                PlatformStyle::platform(),
 7562                Some(modifiers_color),
 7563                Some(IconSize::XSmall.rems().into()),
 7564                true,
 7565            )))
 7566            .when(is_platform_style_mac, |parent| {
 7567                parent.child(accept_keystroke.key.clone())
 7568            })
 7569            .when(!is_platform_style_mac, |parent| {
 7570                parent.child(
 7571                    Key::new(
 7572                        util::capitalize(&accept_keystroke.key),
 7573                        Some(Color::Default),
 7574                    )
 7575                    .size(Some(IconSize::XSmall.rems().into())),
 7576                )
 7577            })
 7578            .into_any()
 7579            .into()
 7580    }
 7581
 7582    fn render_edit_prediction_line_popover(
 7583        &self,
 7584        label: impl Into<SharedString>,
 7585        icon: Option<IconName>,
 7586        window: &mut Window,
 7587        cx: &App,
 7588    ) -> Option<Stateful<Div>> {
 7589        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 7590
 7591        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7592        let has_keybind = keybind.is_some();
 7593
 7594        let result = h_flex()
 7595            .id("ep-line-popover")
 7596            .py_0p5()
 7597            .pl_1()
 7598            .pr(padding_right)
 7599            .gap_1()
 7600            .rounded_md()
 7601            .border_1()
 7602            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7603            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 7604            .shadow_sm()
 7605            .when(!has_keybind, |el| {
 7606                let status_colors = cx.theme().status();
 7607
 7608                el.bg(status_colors.error_background)
 7609                    .border_color(status_colors.error.opacity(0.6))
 7610                    .pl_2()
 7611                    .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
 7612                    .cursor_default()
 7613                    .hoverable_tooltip(move |_window, cx| {
 7614                        cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7615                    })
 7616            })
 7617            .children(keybind)
 7618            .child(
 7619                Label::new(label)
 7620                    .size(LabelSize::Small)
 7621                    .when(!has_keybind, |el| {
 7622                        el.color(cx.theme().status().error.into()).strikethrough()
 7623                    }),
 7624            )
 7625            .when(!has_keybind, |el| {
 7626                el.child(
 7627                    h_flex().ml_1().child(
 7628                        Icon::new(IconName::Info)
 7629                            .size(IconSize::Small)
 7630                            .color(cx.theme().status().error.into()),
 7631                    ),
 7632                )
 7633            })
 7634            .when_some(icon, |element, icon| {
 7635                element.child(
 7636                    div()
 7637                        .mt(px(1.5))
 7638                        .child(Icon::new(icon).size(IconSize::Small)),
 7639                )
 7640            });
 7641
 7642        Some(result)
 7643    }
 7644
 7645    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 7646        let accent_color = cx.theme().colors().text_accent;
 7647        let editor_bg_color = cx.theme().colors().editor_background;
 7648        editor_bg_color.blend(accent_color.opacity(0.1))
 7649    }
 7650
 7651    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 7652        let accent_color = cx.theme().colors().text_accent;
 7653        let editor_bg_color = cx.theme().colors().editor_background;
 7654        editor_bg_color.blend(accent_color.opacity(0.6))
 7655    }
 7656
 7657    fn render_edit_prediction_cursor_popover(
 7658        &self,
 7659        min_width: Pixels,
 7660        max_width: Pixels,
 7661        cursor_point: Point,
 7662        style: &EditorStyle,
 7663        accept_keystroke: Option<&gpui::Keystroke>,
 7664        _window: &Window,
 7665        cx: &mut Context<Editor>,
 7666    ) -> Option<AnyElement> {
 7667        let provider = self.edit_prediction_provider.as_ref()?;
 7668
 7669        if provider.provider.needs_terms_acceptance(cx) {
 7670            return Some(
 7671                h_flex()
 7672                    .min_w(min_width)
 7673                    .flex_1()
 7674                    .px_2()
 7675                    .py_1()
 7676                    .gap_3()
 7677                    .elevation_2(cx)
 7678                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 7679                    .id("accept-terms")
 7680                    .cursor_pointer()
 7681                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 7682                    .on_click(cx.listener(|this, _event, window, cx| {
 7683                        cx.stop_propagation();
 7684                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 7685                        window.dispatch_action(
 7686                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 7687                            cx,
 7688                        );
 7689                    }))
 7690                    .child(
 7691                        h_flex()
 7692                            .flex_1()
 7693                            .gap_2()
 7694                            .child(Icon::new(IconName::ZedPredict))
 7695                            .child(Label::new("Accept Terms of Service"))
 7696                            .child(div().w_full())
 7697                            .child(
 7698                                Icon::new(IconName::ArrowUpRight)
 7699                                    .color(Color::Muted)
 7700                                    .size(IconSize::Small),
 7701                            )
 7702                            .into_any_element(),
 7703                    )
 7704                    .into_any(),
 7705            );
 7706        }
 7707
 7708        let is_refreshing = provider.provider.is_refreshing(cx);
 7709
 7710        fn pending_completion_container() -> Div {
 7711            h_flex()
 7712                .h_full()
 7713                .flex_1()
 7714                .gap_2()
 7715                .child(Icon::new(IconName::ZedPredict))
 7716        }
 7717
 7718        let completion = match &self.active_inline_completion {
 7719            Some(prediction) => {
 7720                if !self.has_visible_completions_menu() {
 7721                    const RADIUS: Pixels = px(6.);
 7722                    const BORDER_WIDTH: Pixels = px(1.);
 7723
 7724                    return Some(
 7725                        h_flex()
 7726                            .elevation_2(cx)
 7727                            .border(BORDER_WIDTH)
 7728                            .border_color(cx.theme().colors().border)
 7729                            .when(accept_keystroke.is_none(), |el| {
 7730                                el.border_color(cx.theme().status().error)
 7731                            })
 7732                            .rounded(RADIUS)
 7733                            .rounded_tl(px(0.))
 7734                            .overflow_hidden()
 7735                            .child(div().px_1p5().child(match &prediction.completion {
 7736                                InlineCompletion::Move { target, snapshot } => {
 7737                                    use text::ToPoint as _;
 7738                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 7739                                    {
 7740                                        Icon::new(IconName::ZedPredictDown)
 7741                                    } else {
 7742                                        Icon::new(IconName::ZedPredictUp)
 7743                                    }
 7744                                }
 7745                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 7746                            }))
 7747                            .child(
 7748                                h_flex()
 7749                                    .gap_1()
 7750                                    .py_1()
 7751                                    .px_2()
 7752                                    .rounded_r(RADIUS - BORDER_WIDTH)
 7753                                    .border_l_1()
 7754                                    .border_color(cx.theme().colors().border)
 7755                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7756                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 7757                                        el.child(
 7758                                            Label::new("Hold")
 7759                                                .size(LabelSize::Small)
 7760                                                .when(accept_keystroke.is_none(), |el| {
 7761                                                    el.strikethrough()
 7762                                                })
 7763                                                .line_height_style(LineHeightStyle::UiLabel),
 7764                                        )
 7765                                    })
 7766                                    .id("edit_prediction_cursor_popover_keybind")
 7767                                    .when(accept_keystroke.is_none(), |el| {
 7768                                        let status_colors = cx.theme().status();
 7769
 7770                                        el.bg(status_colors.error_background)
 7771                                            .border_color(status_colors.error.opacity(0.6))
 7772                                            .child(Icon::new(IconName::Info).color(Color::Error))
 7773                                            .cursor_default()
 7774                                            .hoverable_tooltip(move |_window, cx| {
 7775                                                cx.new(|_| MissingEditPredictionKeybindingTooltip)
 7776                                                    .into()
 7777                                            })
 7778                                    })
 7779                                    .when_some(
 7780                                        accept_keystroke.as_ref(),
 7781                                        |el, accept_keystroke| {
 7782                                            el.child(h_flex().children(ui::render_modifiers(
 7783                                                &accept_keystroke.modifiers,
 7784                                                PlatformStyle::platform(),
 7785                                                Some(Color::Default),
 7786                                                Some(IconSize::XSmall.rems().into()),
 7787                                                false,
 7788                                            )))
 7789                                        },
 7790                                    ),
 7791                            )
 7792                            .into_any(),
 7793                    );
 7794                }
 7795
 7796                self.render_edit_prediction_cursor_popover_preview(
 7797                    prediction,
 7798                    cursor_point,
 7799                    style,
 7800                    cx,
 7801                )?
 7802            }
 7803
 7804            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 7805                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 7806                    stale_completion,
 7807                    cursor_point,
 7808                    style,
 7809                    cx,
 7810                )?,
 7811
 7812                None => {
 7813                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 7814                }
 7815            },
 7816
 7817            None => pending_completion_container().child(Label::new("No Prediction")),
 7818        };
 7819
 7820        let completion = if is_refreshing {
 7821            completion
 7822                .with_animation(
 7823                    "loading-completion",
 7824                    Animation::new(Duration::from_secs(2))
 7825                        .repeat()
 7826                        .with_easing(pulsating_between(0.4, 0.8)),
 7827                    |label, delta| label.opacity(delta),
 7828                )
 7829                .into_any_element()
 7830        } else {
 7831            completion.into_any_element()
 7832        };
 7833
 7834        let has_completion = self.active_inline_completion.is_some();
 7835
 7836        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7837        Some(
 7838            h_flex()
 7839                .min_w(min_width)
 7840                .max_w(max_width)
 7841                .flex_1()
 7842                .elevation_2(cx)
 7843                .border_color(cx.theme().colors().border)
 7844                .child(
 7845                    div()
 7846                        .flex_1()
 7847                        .py_1()
 7848                        .px_2()
 7849                        .overflow_hidden()
 7850                        .child(completion),
 7851                )
 7852                .when_some(accept_keystroke, |el, accept_keystroke| {
 7853                    if !accept_keystroke.modifiers.modified() {
 7854                        return el;
 7855                    }
 7856
 7857                    el.child(
 7858                        h_flex()
 7859                            .h_full()
 7860                            .border_l_1()
 7861                            .rounded_r_lg()
 7862                            .border_color(cx.theme().colors().border)
 7863                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7864                            .gap_1()
 7865                            .py_1()
 7866                            .px_2()
 7867                            .child(
 7868                                h_flex()
 7869                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7870                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 7871                                    .child(h_flex().children(ui::render_modifiers(
 7872                                        &accept_keystroke.modifiers,
 7873                                        PlatformStyle::platform(),
 7874                                        Some(if !has_completion {
 7875                                            Color::Muted
 7876                                        } else {
 7877                                            Color::Default
 7878                                        }),
 7879                                        None,
 7880                                        false,
 7881                                    ))),
 7882                            )
 7883                            .child(Label::new("Preview").into_any_element())
 7884                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 7885                    )
 7886                })
 7887                .into_any(),
 7888        )
 7889    }
 7890
 7891    fn render_edit_prediction_cursor_popover_preview(
 7892        &self,
 7893        completion: &InlineCompletionState,
 7894        cursor_point: Point,
 7895        style: &EditorStyle,
 7896        cx: &mut Context<Editor>,
 7897    ) -> Option<Div> {
 7898        use text::ToPoint as _;
 7899
 7900        fn render_relative_row_jump(
 7901            prefix: impl Into<String>,
 7902            current_row: u32,
 7903            target_row: u32,
 7904        ) -> Div {
 7905            let (row_diff, arrow) = if target_row < current_row {
 7906                (current_row - target_row, IconName::ArrowUp)
 7907            } else {
 7908                (target_row - current_row, IconName::ArrowDown)
 7909            };
 7910
 7911            h_flex()
 7912                .child(
 7913                    Label::new(format!("{}{}", prefix.into(), row_diff))
 7914                        .color(Color::Muted)
 7915                        .size(LabelSize::Small),
 7916                )
 7917                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 7918        }
 7919
 7920        match &completion.completion {
 7921            InlineCompletion::Move {
 7922                target, snapshot, ..
 7923            } => Some(
 7924                h_flex()
 7925                    .px_2()
 7926                    .gap_2()
 7927                    .flex_1()
 7928                    .child(
 7929                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 7930                            Icon::new(IconName::ZedPredictDown)
 7931                        } else {
 7932                            Icon::new(IconName::ZedPredictUp)
 7933                        },
 7934                    )
 7935                    .child(Label::new("Jump to Edit")),
 7936            ),
 7937
 7938            InlineCompletion::Edit {
 7939                edits,
 7940                edit_preview,
 7941                snapshot,
 7942                display_mode: _,
 7943            } => {
 7944                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 7945
 7946                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 7947                    &snapshot,
 7948                    &edits,
 7949                    edit_preview.as_ref()?,
 7950                    true,
 7951                    cx,
 7952                )
 7953                .first_line_preview();
 7954
 7955                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 7956                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 7957
 7958                let preview = h_flex()
 7959                    .gap_1()
 7960                    .min_w_16()
 7961                    .child(styled_text)
 7962                    .when(has_more_lines, |parent| parent.child(""));
 7963
 7964                let left = if first_edit_row != cursor_point.row {
 7965                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 7966                        .into_any_element()
 7967                } else {
 7968                    Icon::new(IconName::ZedPredict).into_any_element()
 7969                };
 7970
 7971                Some(
 7972                    h_flex()
 7973                        .h_full()
 7974                        .flex_1()
 7975                        .gap_2()
 7976                        .pr_1()
 7977                        .overflow_x_hidden()
 7978                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7979                        .child(left)
 7980                        .child(preview),
 7981                )
 7982            }
 7983        }
 7984    }
 7985
 7986    fn render_context_menu(
 7987        &self,
 7988        style: &EditorStyle,
 7989        max_height_in_lines: u32,
 7990        window: &mut Window,
 7991        cx: &mut Context<Editor>,
 7992    ) -> Option<AnyElement> {
 7993        let menu = self.context_menu.borrow();
 7994        let menu = menu.as_ref()?;
 7995        if !menu.visible() {
 7996            return None;
 7997        };
 7998        Some(menu.render(style, max_height_in_lines, window, cx))
 7999    }
 8000
 8001    fn render_context_menu_aside(
 8002        &mut self,
 8003        max_size: Size<Pixels>,
 8004        window: &mut Window,
 8005        cx: &mut Context<Editor>,
 8006    ) -> Option<AnyElement> {
 8007        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 8008            if menu.visible() {
 8009                menu.render_aside(self, max_size, window, cx)
 8010            } else {
 8011                None
 8012            }
 8013        })
 8014    }
 8015
 8016    fn hide_context_menu(
 8017        &mut self,
 8018        window: &mut Window,
 8019        cx: &mut Context<Self>,
 8020    ) -> Option<CodeContextMenu> {
 8021        cx.notify();
 8022        self.completion_tasks.clear();
 8023        let context_menu = self.context_menu.borrow_mut().take();
 8024        self.stale_inline_completion_in_menu.take();
 8025        self.update_visible_inline_completion(window, cx);
 8026        context_menu
 8027    }
 8028
 8029    fn show_snippet_choices(
 8030        &mut self,
 8031        choices: &Vec<String>,
 8032        selection: Range<Anchor>,
 8033        cx: &mut Context<Self>,
 8034    ) {
 8035        if selection.start.buffer_id.is_none() {
 8036            return;
 8037        }
 8038        let buffer_id = selection.start.buffer_id.unwrap();
 8039        let buffer = self.buffer().read(cx).buffer(buffer_id);
 8040        let id = post_inc(&mut self.next_completion_id);
 8041
 8042        if let Some(buffer) = buffer {
 8043            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 8044                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 8045            ));
 8046        }
 8047    }
 8048
 8049    pub fn insert_snippet(
 8050        &mut self,
 8051        insertion_ranges: &[Range<usize>],
 8052        snippet: Snippet,
 8053        window: &mut Window,
 8054        cx: &mut Context<Self>,
 8055    ) -> Result<()> {
 8056        struct Tabstop<T> {
 8057            is_end_tabstop: bool,
 8058            ranges: Vec<Range<T>>,
 8059            choices: Option<Vec<String>>,
 8060        }
 8061
 8062        let tabstops = self.buffer.update(cx, |buffer, cx| {
 8063            let snippet_text: Arc<str> = snippet.text.clone().into();
 8064            let edits = insertion_ranges
 8065                .iter()
 8066                .cloned()
 8067                .map(|range| (range, snippet_text.clone()));
 8068            buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
 8069
 8070            let snapshot = &*buffer.read(cx);
 8071            let snippet = &snippet;
 8072            snippet
 8073                .tabstops
 8074                .iter()
 8075                .map(|tabstop| {
 8076                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 8077                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 8078                    });
 8079                    let mut tabstop_ranges = tabstop
 8080                        .ranges
 8081                        .iter()
 8082                        .flat_map(|tabstop_range| {
 8083                            let mut delta = 0_isize;
 8084                            insertion_ranges.iter().map(move |insertion_range| {
 8085                                let insertion_start = insertion_range.start as isize + delta;
 8086                                delta +=
 8087                                    snippet.text.len() as isize - insertion_range.len() as isize;
 8088
 8089                                let start = ((insertion_start + tabstop_range.start) as usize)
 8090                                    .min(snapshot.len());
 8091                                let end = ((insertion_start + tabstop_range.end) as usize)
 8092                                    .min(snapshot.len());
 8093                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 8094                            })
 8095                        })
 8096                        .collect::<Vec<_>>();
 8097                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 8098
 8099                    Tabstop {
 8100                        is_end_tabstop,
 8101                        ranges: tabstop_ranges,
 8102                        choices: tabstop.choices.clone(),
 8103                    }
 8104                })
 8105                .collect::<Vec<_>>()
 8106        });
 8107        if let Some(tabstop) = tabstops.first() {
 8108            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8109                s.select_ranges(tabstop.ranges.iter().cloned());
 8110            });
 8111
 8112            if let Some(choices) = &tabstop.choices {
 8113                if let Some(selection) = tabstop.ranges.first() {
 8114                    self.show_snippet_choices(choices, selection.clone(), cx)
 8115                }
 8116            }
 8117
 8118            // If we're already at the last tabstop and it's at the end of the snippet,
 8119            // we're done, we don't need to keep the state around.
 8120            if !tabstop.is_end_tabstop {
 8121                let choices = tabstops
 8122                    .iter()
 8123                    .map(|tabstop| tabstop.choices.clone())
 8124                    .collect();
 8125
 8126                let ranges = tabstops
 8127                    .into_iter()
 8128                    .map(|tabstop| tabstop.ranges)
 8129                    .collect::<Vec<_>>();
 8130
 8131                self.snippet_stack.push(SnippetState {
 8132                    active_index: 0,
 8133                    ranges,
 8134                    choices,
 8135                });
 8136            }
 8137
 8138            // Check whether the just-entered snippet ends with an auto-closable bracket.
 8139            if self.autoclose_regions.is_empty() {
 8140                let snapshot = self.buffer.read(cx).snapshot(cx);
 8141                for selection in &mut self.selections.all::<Point>(cx) {
 8142                    let selection_head = selection.head();
 8143                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 8144                        continue;
 8145                    };
 8146
 8147                    let mut bracket_pair = None;
 8148                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 8149                    let prev_chars = snapshot
 8150                        .reversed_chars_at(selection_head)
 8151                        .collect::<String>();
 8152                    for (pair, enabled) in scope.brackets() {
 8153                        if enabled
 8154                            && pair.close
 8155                            && prev_chars.starts_with(pair.start.as_str())
 8156                            && next_chars.starts_with(pair.end.as_str())
 8157                        {
 8158                            bracket_pair = Some(pair.clone());
 8159                            break;
 8160                        }
 8161                    }
 8162                    if let Some(pair) = bracket_pair {
 8163                        let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
 8164                        let autoclose_enabled =
 8165                            self.use_autoclose && snapshot_settings.use_autoclose;
 8166                        if autoclose_enabled {
 8167                            let start = snapshot.anchor_after(selection_head);
 8168                            let end = snapshot.anchor_after(selection_head);
 8169                            self.autoclose_regions.push(AutocloseRegion {
 8170                                selection_id: selection.id,
 8171                                range: start..end,
 8172                                pair,
 8173                            });
 8174                        }
 8175                    }
 8176                }
 8177            }
 8178        }
 8179        Ok(())
 8180    }
 8181
 8182    pub fn move_to_next_snippet_tabstop(
 8183        &mut self,
 8184        window: &mut Window,
 8185        cx: &mut Context<Self>,
 8186    ) -> bool {
 8187        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 8188    }
 8189
 8190    pub fn move_to_prev_snippet_tabstop(
 8191        &mut self,
 8192        window: &mut Window,
 8193        cx: &mut Context<Self>,
 8194    ) -> bool {
 8195        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 8196    }
 8197
 8198    pub fn move_to_snippet_tabstop(
 8199        &mut self,
 8200        bias: Bias,
 8201        window: &mut Window,
 8202        cx: &mut Context<Self>,
 8203    ) -> bool {
 8204        if let Some(mut snippet) = self.snippet_stack.pop() {
 8205            match bias {
 8206                Bias::Left => {
 8207                    if snippet.active_index > 0 {
 8208                        snippet.active_index -= 1;
 8209                    } else {
 8210                        self.snippet_stack.push(snippet);
 8211                        return false;
 8212                    }
 8213                }
 8214                Bias::Right => {
 8215                    if snippet.active_index + 1 < snippet.ranges.len() {
 8216                        snippet.active_index += 1;
 8217                    } else {
 8218                        self.snippet_stack.push(snippet);
 8219                        return false;
 8220                    }
 8221                }
 8222            }
 8223            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 8224                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8225                    s.select_anchor_ranges(current_ranges.iter().cloned())
 8226                });
 8227
 8228                if let Some(choices) = &snippet.choices[snippet.active_index] {
 8229                    if let Some(selection) = current_ranges.first() {
 8230                        self.show_snippet_choices(&choices, selection.clone(), cx);
 8231                    }
 8232                }
 8233
 8234                // If snippet state is not at the last tabstop, push it back on the stack
 8235                if snippet.active_index + 1 < snippet.ranges.len() {
 8236                    self.snippet_stack.push(snippet);
 8237                }
 8238                return true;
 8239            }
 8240        }
 8241
 8242        false
 8243    }
 8244
 8245    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 8246        self.transact(window, cx, |this, window, cx| {
 8247            this.select_all(&SelectAll, window, cx);
 8248            this.insert("", window, cx);
 8249        });
 8250    }
 8251
 8252    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 8253        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8254        self.transact(window, cx, |this, window, cx| {
 8255            this.select_autoclose_pair(window, cx);
 8256            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 8257            if !this.linked_edit_ranges.is_empty() {
 8258                let selections = this.selections.all::<MultiBufferPoint>(cx);
 8259                let snapshot = this.buffer.read(cx).snapshot(cx);
 8260
 8261                for selection in selections.iter() {
 8262                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 8263                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 8264                    if selection_start.buffer_id != selection_end.buffer_id {
 8265                        continue;
 8266                    }
 8267                    if let Some(ranges) =
 8268                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 8269                    {
 8270                        for (buffer, entries) in ranges {
 8271                            linked_ranges.entry(buffer).or_default().extend(entries);
 8272                        }
 8273                    }
 8274                }
 8275            }
 8276
 8277            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8278            let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 8279            for selection in &mut selections {
 8280                if selection.is_empty() {
 8281                    let old_head = selection.head();
 8282                    let mut new_head =
 8283                        movement::left(&display_map, old_head.to_display_point(&display_map))
 8284                            .to_point(&display_map);
 8285                    if let Some((buffer, line_buffer_range)) = display_map
 8286                        .buffer_snapshot
 8287                        .buffer_line_for_row(MultiBufferRow(old_head.row))
 8288                    {
 8289                        let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
 8290                        let indent_len = match indent_size.kind {
 8291                            IndentKind::Space => {
 8292                                buffer.settings_at(line_buffer_range.start, cx).tab_size
 8293                            }
 8294                            IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 8295                        };
 8296                        if old_head.column <= indent_size.len && old_head.column > 0 {
 8297                            let indent_len = indent_len.get();
 8298                            new_head = cmp::min(
 8299                                new_head,
 8300                                MultiBufferPoint::new(
 8301                                    old_head.row,
 8302                                    ((old_head.column - 1) / indent_len) * indent_len,
 8303                                ),
 8304                            );
 8305                        }
 8306                    }
 8307
 8308                    selection.set_head(new_head, SelectionGoal::None);
 8309                }
 8310            }
 8311
 8312            this.signature_help_state.set_backspace_pressed(true);
 8313            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8314                s.select(selections)
 8315            });
 8316            this.insert("", window, cx);
 8317            let empty_str: Arc<str> = Arc::from("");
 8318            for (buffer, edits) in linked_ranges {
 8319                let snapshot = buffer.read(cx).snapshot();
 8320                use text::ToPoint as TP;
 8321
 8322                let edits = edits
 8323                    .into_iter()
 8324                    .map(|range| {
 8325                        let end_point = TP::to_point(&range.end, &snapshot);
 8326                        let mut start_point = TP::to_point(&range.start, &snapshot);
 8327
 8328                        if end_point == start_point {
 8329                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 8330                                .saturating_sub(1);
 8331                            start_point =
 8332                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 8333                        };
 8334
 8335                        (start_point..end_point, empty_str.clone())
 8336                    })
 8337                    .sorted_by_key(|(range, _)| range.start)
 8338                    .collect::<Vec<_>>();
 8339                buffer.update(cx, |this, cx| {
 8340                    this.edit(edits, None, cx);
 8341                })
 8342            }
 8343            this.refresh_inline_completion(true, false, window, cx);
 8344            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 8345        });
 8346    }
 8347
 8348    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 8349        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8350        self.transact(window, cx, |this, window, cx| {
 8351            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8352                s.move_with(|map, selection| {
 8353                    if selection.is_empty() {
 8354                        let cursor = movement::right(map, selection.head());
 8355                        selection.end = cursor;
 8356                        selection.reversed = true;
 8357                        selection.goal = SelectionGoal::None;
 8358                    }
 8359                })
 8360            });
 8361            this.insert("", window, cx);
 8362            this.refresh_inline_completion(true, false, window, cx);
 8363        });
 8364    }
 8365
 8366    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 8367        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8368        if self.move_to_prev_snippet_tabstop(window, cx) {
 8369            return;
 8370        }
 8371        self.outdent(&Outdent, window, cx);
 8372    }
 8373
 8374    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 8375        if self.move_to_next_snippet_tabstop(window, cx) {
 8376            self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8377            return;
 8378        }
 8379        if self.read_only(cx) {
 8380            return;
 8381        }
 8382        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8383        let mut selections = self.selections.all_adjusted(cx);
 8384        let buffer = self.buffer.read(cx);
 8385        let snapshot = buffer.snapshot(cx);
 8386        let rows_iter = selections.iter().map(|s| s.head().row);
 8387        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 8388
 8389        let mut edits = Vec::new();
 8390        let mut prev_edited_row = 0;
 8391        let mut row_delta = 0;
 8392        for selection in &mut selections {
 8393            if selection.start.row != prev_edited_row {
 8394                row_delta = 0;
 8395            }
 8396            prev_edited_row = selection.end.row;
 8397
 8398            // If the selection is non-empty, then increase the indentation of the selected lines.
 8399            if !selection.is_empty() {
 8400                row_delta =
 8401                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8402                continue;
 8403            }
 8404
 8405            // If the selection is empty and the cursor is in the leading whitespace before the
 8406            // suggested indentation, then auto-indent the line.
 8407            let cursor = selection.head();
 8408            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 8409            if let Some(suggested_indent) =
 8410                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 8411            {
 8412                if cursor.column < suggested_indent.len
 8413                    && cursor.column <= current_indent.len
 8414                    && current_indent.len <= suggested_indent.len
 8415                {
 8416                    selection.start = Point::new(cursor.row, suggested_indent.len);
 8417                    selection.end = selection.start;
 8418                    if row_delta == 0 {
 8419                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 8420                            cursor.row,
 8421                            current_indent,
 8422                            suggested_indent,
 8423                        ));
 8424                        row_delta = suggested_indent.len - current_indent.len;
 8425                    }
 8426                    continue;
 8427                }
 8428            }
 8429
 8430            // Otherwise, insert a hard or soft tab.
 8431            let settings = buffer.language_settings_at(cursor, cx);
 8432            let tab_size = if settings.hard_tabs {
 8433                IndentSize::tab()
 8434            } else {
 8435                let tab_size = settings.tab_size.get();
 8436                let indent_remainder = snapshot
 8437                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 8438                    .flat_map(str::chars)
 8439                    .fold(row_delta % tab_size, |counter: u32, c| {
 8440                        if c == '\t' {
 8441                            0
 8442                        } else {
 8443                            (counter + 1) % tab_size
 8444                        }
 8445                    });
 8446
 8447                let chars_to_next_tab_stop = tab_size - indent_remainder;
 8448                IndentSize::spaces(chars_to_next_tab_stop)
 8449            };
 8450            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 8451            selection.end = selection.start;
 8452            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 8453            row_delta += tab_size.len;
 8454        }
 8455
 8456        self.transact(window, cx, |this, window, cx| {
 8457            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8458            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8459                s.select(selections)
 8460            });
 8461            this.refresh_inline_completion(true, false, window, cx);
 8462        });
 8463    }
 8464
 8465    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 8466        if self.read_only(cx) {
 8467            return;
 8468        }
 8469        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8470        let mut selections = self.selections.all::<Point>(cx);
 8471        let mut prev_edited_row = 0;
 8472        let mut row_delta = 0;
 8473        let mut edits = Vec::new();
 8474        let buffer = self.buffer.read(cx);
 8475        let snapshot = buffer.snapshot(cx);
 8476        for selection in &mut selections {
 8477            if selection.start.row != prev_edited_row {
 8478                row_delta = 0;
 8479            }
 8480            prev_edited_row = selection.end.row;
 8481
 8482            row_delta =
 8483                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8484        }
 8485
 8486        self.transact(window, cx, |this, window, cx| {
 8487            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8488            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8489                s.select(selections)
 8490            });
 8491        });
 8492    }
 8493
 8494    fn indent_selection(
 8495        buffer: &MultiBuffer,
 8496        snapshot: &MultiBufferSnapshot,
 8497        selection: &mut Selection<Point>,
 8498        edits: &mut Vec<(Range<Point>, String)>,
 8499        delta_for_start_row: u32,
 8500        cx: &App,
 8501    ) -> u32 {
 8502        let settings = buffer.language_settings_at(selection.start, cx);
 8503        let tab_size = settings.tab_size.get();
 8504        let indent_kind = if settings.hard_tabs {
 8505            IndentKind::Tab
 8506        } else {
 8507            IndentKind::Space
 8508        };
 8509        let mut start_row = selection.start.row;
 8510        let mut end_row = selection.end.row + 1;
 8511
 8512        // If a selection ends at the beginning of a line, don't indent
 8513        // that last line.
 8514        if selection.end.column == 0 && selection.end.row > selection.start.row {
 8515            end_row -= 1;
 8516        }
 8517
 8518        // Avoid re-indenting a row that has already been indented by a
 8519        // previous selection, but still update this selection's column
 8520        // to reflect that indentation.
 8521        if delta_for_start_row > 0 {
 8522            start_row += 1;
 8523            selection.start.column += delta_for_start_row;
 8524            if selection.end.row == selection.start.row {
 8525                selection.end.column += delta_for_start_row;
 8526            }
 8527        }
 8528
 8529        let mut delta_for_end_row = 0;
 8530        let has_multiple_rows = start_row + 1 != end_row;
 8531        for row in start_row..end_row {
 8532            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 8533            let indent_delta = match (current_indent.kind, indent_kind) {
 8534                (IndentKind::Space, IndentKind::Space) => {
 8535                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 8536                    IndentSize::spaces(columns_to_next_tab_stop)
 8537                }
 8538                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 8539                (_, IndentKind::Tab) => IndentSize::tab(),
 8540            };
 8541
 8542            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 8543                0
 8544            } else {
 8545                selection.start.column
 8546            };
 8547            let row_start = Point::new(row, start);
 8548            edits.push((
 8549                row_start..row_start,
 8550                indent_delta.chars().collect::<String>(),
 8551            ));
 8552
 8553            // Update this selection's endpoints to reflect the indentation.
 8554            if row == selection.start.row {
 8555                selection.start.column += indent_delta.len;
 8556            }
 8557            if row == selection.end.row {
 8558                selection.end.column += indent_delta.len;
 8559                delta_for_end_row = indent_delta.len;
 8560            }
 8561        }
 8562
 8563        if selection.start.row == selection.end.row {
 8564            delta_for_start_row + delta_for_end_row
 8565        } else {
 8566            delta_for_end_row
 8567        }
 8568    }
 8569
 8570    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 8571        if self.read_only(cx) {
 8572            return;
 8573        }
 8574        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8575        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8576        let selections = self.selections.all::<Point>(cx);
 8577        let mut deletion_ranges = Vec::new();
 8578        let mut last_outdent = None;
 8579        {
 8580            let buffer = self.buffer.read(cx);
 8581            let snapshot = buffer.snapshot(cx);
 8582            for selection in &selections {
 8583                let settings = buffer.language_settings_at(selection.start, cx);
 8584                let tab_size = settings.tab_size.get();
 8585                let mut rows = selection.spanned_rows(false, &display_map);
 8586
 8587                // Avoid re-outdenting a row that has already been outdented by a
 8588                // previous selection.
 8589                if let Some(last_row) = last_outdent {
 8590                    if last_row == rows.start {
 8591                        rows.start = rows.start.next_row();
 8592                    }
 8593                }
 8594                let has_multiple_rows = rows.len() > 1;
 8595                for row in rows.iter_rows() {
 8596                    let indent_size = snapshot.indent_size_for_line(row);
 8597                    if indent_size.len > 0 {
 8598                        let deletion_len = match indent_size.kind {
 8599                            IndentKind::Space => {
 8600                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 8601                                if columns_to_prev_tab_stop == 0 {
 8602                                    tab_size
 8603                                } else {
 8604                                    columns_to_prev_tab_stop
 8605                                }
 8606                            }
 8607                            IndentKind::Tab => 1,
 8608                        };
 8609                        let start = if has_multiple_rows
 8610                            || deletion_len > selection.start.column
 8611                            || indent_size.len < selection.start.column
 8612                        {
 8613                            0
 8614                        } else {
 8615                            selection.start.column - deletion_len
 8616                        };
 8617                        deletion_ranges.push(
 8618                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 8619                        );
 8620                        last_outdent = Some(row);
 8621                    }
 8622                }
 8623            }
 8624        }
 8625
 8626        self.transact(window, cx, |this, window, cx| {
 8627            this.buffer.update(cx, |buffer, cx| {
 8628                let empty_str: Arc<str> = Arc::default();
 8629                buffer.edit(
 8630                    deletion_ranges
 8631                        .into_iter()
 8632                        .map(|range| (range, empty_str.clone())),
 8633                    None,
 8634                    cx,
 8635                );
 8636            });
 8637            let selections = this.selections.all::<usize>(cx);
 8638            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8639                s.select(selections)
 8640            });
 8641        });
 8642    }
 8643
 8644    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 8645        if self.read_only(cx) {
 8646            return;
 8647        }
 8648        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8649        let selections = self
 8650            .selections
 8651            .all::<usize>(cx)
 8652            .into_iter()
 8653            .map(|s| s.range());
 8654
 8655        self.transact(window, cx, |this, window, cx| {
 8656            this.buffer.update(cx, |buffer, cx| {
 8657                buffer.autoindent_ranges(selections, cx);
 8658            });
 8659            let selections = this.selections.all::<usize>(cx);
 8660            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8661                s.select(selections)
 8662            });
 8663        });
 8664    }
 8665
 8666    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 8667        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8668        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8669        let selections = self.selections.all::<Point>(cx);
 8670
 8671        let mut new_cursors = Vec::new();
 8672        let mut edit_ranges = Vec::new();
 8673        let mut selections = selections.iter().peekable();
 8674        while let Some(selection) = selections.next() {
 8675            let mut rows = selection.spanned_rows(false, &display_map);
 8676            let goal_display_column = selection.head().to_display_point(&display_map).column();
 8677
 8678            // Accumulate contiguous regions of rows that we want to delete.
 8679            while let Some(next_selection) = selections.peek() {
 8680                let next_rows = next_selection.spanned_rows(false, &display_map);
 8681                if next_rows.start <= rows.end {
 8682                    rows.end = next_rows.end;
 8683                    selections.next().unwrap();
 8684                } else {
 8685                    break;
 8686                }
 8687            }
 8688
 8689            let buffer = &display_map.buffer_snapshot;
 8690            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 8691            let edit_end;
 8692            let cursor_buffer_row;
 8693            if buffer.max_point().row >= rows.end.0 {
 8694                // If there's a line after the range, delete the \n from the end of the row range
 8695                // and position the cursor on the next line.
 8696                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 8697                cursor_buffer_row = rows.end;
 8698            } else {
 8699                // If there isn't a line after the range, delete the \n from the line before the
 8700                // start of the row range and position the cursor there.
 8701                edit_start = edit_start.saturating_sub(1);
 8702                edit_end = buffer.len();
 8703                cursor_buffer_row = rows.start.previous_row();
 8704            }
 8705
 8706            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 8707            *cursor.column_mut() =
 8708                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 8709
 8710            new_cursors.push((
 8711                selection.id,
 8712                buffer.anchor_after(cursor.to_point(&display_map)),
 8713            ));
 8714            edit_ranges.push(edit_start..edit_end);
 8715        }
 8716
 8717        self.transact(window, cx, |this, window, cx| {
 8718            let buffer = this.buffer.update(cx, |buffer, cx| {
 8719                let empty_str: Arc<str> = Arc::default();
 8720                buffer.edit(
 8721                    edit_ranges
 8722                        .into_iter()
 8723                        .map(|range| (range, empty_str.clone())),
 8724                    None,
 8725                    cx,
 8726                );
 8727                buffer.snapshot(cx)
 8728            });
 8729            let new_selections = new_cursors
 8730                .into_iter()
 8731                .map(|(id, cursor)| {
 8732                    let cursor = cursor.to_point(&buffer);
 8733                    Selection {
 8734                        id,
 8735                        start: cursor,
 8736                        end: cursor,
 8737                        reversed: false,
 8738                        goal: SelectionGoal::None,
 8739                    }
 8740                })
 8741                .collect();
 8742
 8743            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8744                s.select(new_selections);
 8745            });
 8746        });
 8747    }
 8748
 8749    pub fn join_lines_impl(
 8750        &mut self,
 8751        insert_whitespace: bool,
 8752        window: &mut Window,
 8753        cx: &mut Context<Self>,
 8754    ) {
 8755        if self.read_only(cx) {
 8756            return;
 8757        }
 8758        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 8759        for selection in self.selections.all::<Point>(cx) {
 8760            let start = MultiBufferRow(selection.start.row);
 8761            // Treat single line selections as if they include the next line. Otherwise this action
 8762            // would do nothing for single line selections individual cursors.
 8763            let end = if selection.start.row == selection.end.row {
 8764                MultiBufferRow(selection.start.row + 1)
 8765            } else {
 8766                MultiBufferRow(selection.end.row)
 8767            };
 8768
 8769            if let Some(last_row_range) = row_ranges.last_mut() {
 8770                if start <= last_row_range.end {
 8771                    last_row_range.end = end;
 8772                    continue;
 8773                }
 8774            }
 8775            row_ranges.push(start..end);
 8776        }
 8777
 8778        let snapshot = self.buffer.read(cx).snapshot(cx);
 8779        let mut cursor_positions = Vec::new();
 8780        for row_range in &row_ranges {
 8781            let anchor = snapshot.anchor_before(Point::new(
 8782                row_range.end.previous_row().0,
 8783                snapshot.line_len(row_range.end.previous_row()),
 8784            ));
 8785            cursor_positions.push(anchor..anchor);
 8786        }
 8787
 8788        self.transact(window, cx, |this, window, cx| {
 8789            for row_range in row_ranges.into_iter().rev() {
 8790                for row in row_range.iter_rows().rev() {
 8791                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 8792                    let next_line_row = row.next_row();
 8793                    let indent = snapshot.indent_size_for_line(next_line_row);
 8794                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 8795
 8796                    let replace =
 8797                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 8798                            " "
 8799                        } else {
 8800                            ""
 8801                        };
 8802
 8803                    this.buffer.update(cx, |buffer, cx| {
 8804                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 8805                    });
 8806                }
 8807            }
 8808
 8809            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8810                s.select_anchor_ranges(cursor_positions)
 8811            });
 8812        });
 8813    }
 8814
 8815    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 8816        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8817        self.join_lines_impl(true, window, cx);
 8818    }
 8819
 8820    pub fn sort_lines_case_sensitive(
 8821        &mut self,
 8822        _: &SortLinesCaseSensitive,
 8823        window: &mut Window,
 8824        cx: &mut Context<Self>,
 8825    ) {
 8826        self.manipulate_lines(window, cx, |lines| lines.sort())
 8827    }
 8828
 8829    pub fn sort_lines_case_insensitive(
 8830        &mut self,
 8831        _: &SortLinesCaseInsensitive,
 8832        window: &mut Window,
 8833        cx: &mut Context<Self>,
 8834    ) {
 8835        self.manipulate_lines(window, cx, |lines| {
 8836            lines.sort_by_key(|line| line.to_lowercase())
 8837        })
 8838    }
 8839
 8840    pub fn unique_lines_case_insensitive(
 8841        &mut self,
 8842        _: &UniqueLinesCaseInsensitive,
 8843        window: &mut Window,
 8844        cx: &mut Context<Self>,
 8845    ) {
 8846        self.manipulate_lines(window, cx, |lines| {
 8847            let mut seen = HashSet::default();
 8848            lines.retain(|line| seen.insert(line.to_lowercase()));
 8849        })
 8850    }
 8851
 8852    pub fn unique_lines_case_sensitive(
 8853        &mut self,
 8854        _: &UniqueLinesCaseSensitive,
 8855        window: &mut Window,
 8856        cx: &mut Context<Self>,
 8857    ) {
 8858        self.manipulate_lines(window, cx, |lines| {
 8859            let mut seen = HashSet::default();
 8860            lines.retain(|line| seen.insert(*line));
 8861        })
 8862    }
 8863
 8864    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 8865        let Some(project) = self.project.clone() else {
 8866            return;
 8867        };
 8868        self.reload(project, window, cx)
 8869            .detach_and_notify_err(window, cx);
 8870    }
 8871
 8872    pub fn restore_file(
 8873        &mut self,
 8874        _: &::git::RestoreFile,
 8875        window: &mut Window,
 8876        cx: &mut Context<Self>,
 8877    ) {
 8878        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8879        let mut buffer_ids = HashSet::default();
 8880        let snapshot = self.buffer().read(cx).snapshot(cx);
 8881        for selection in self.selections.all::<usize>(cx) {
 8882            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 8883        }
 8884
 8885        let buffer = self.buffer().read(cx);
 8886        let ranges = buffer_ids
 8887            .into_iter()
 8888            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 8889            .collect::<Vec<_>>();
 8890
 8891        self.restore_hunks_in_ranges(ranges, window, cx);
 8892    }
 8893
 8894    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 8895        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8896        let selections = self
 8897            .selections
 8898            .all(cx)
 8899            .into_iter()
 8900            .map(|s| s.range())
 8901            .collect();
 8902        self.restore_hunks_in_ranges(selections, window, cx);
 8903    }
 8904
 8905    pub fn restore_hunks_in_ranges(
 8906        &mut self,
 8907        ranges: Vec<Range<Point>>,
 8908        window: &mut Window,
 8909        cx: &mut Context<Editor>,
 8910    ) {
 8911        let mut revert_changes = HashMap::default();
 8912        let chunk_by = self
 8913            .snapshot(window, cx)
 8914            .hunks_for_ranges(ranges)
 8915            .into_iter()
 8916            .chunk_by(|hunk| hunk.buffer_id);
 8917        for (buffer_id, hunks) in &chunk_by {
 8918            let hunks = hunks.collect::<Vec<_>>();
 8919            for hunk in &hunks {
 8920                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 8921            }
 8922            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
 8923        }
 8924        drop(chunk_by);
 8925        if !revert_changes.is_empty() {
 8926            self.transact(window, cx, |editor, window, cx| {
 8927                editor.restore(revert_changes, window, cx);
 8928            });
 8929        }
 8930    }
 8931
 8932    pub fn open_active_item_in_terminal(
 8933        &mut self,
 8934        _: &OpenInTerminal,
 8935        window: &mut Window,
 8936        cx: &mut Context<Self>,
 8937    ) {
 8938        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 8939            let project_path = buffer.read(cx).project_path(cx)?;
 8940            let project = self.project.as_ref()?.read(cx);
 8941            let entry = project.entry_for_path(&project_path, cx)?;
 8942            let parent = match &entry.canonical_path {
 8943                Some(canonical_path) => canonical_path.to_path_buf(),
 8944                None => project.absolute_path(&project_path, cx)?,
 8945            }
 8946            .parent()?
 8947            .to_path_buf();
 8948            Some(parent)
 8949        }) {
 8950            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 8951        }
 8952    }
 8953
 8954    fn set_breakpoint_context_menu(
 8955        &mut self,
 8956        display_row: DisplayRow,
 8957        position: Option<Anchor>,
 8958        clicked_point: gpui::Point<Pixels>,
 8959        window: &mut Window,
 8960        cx: &mut Context<Self>,
 8961    ) {
 8962        if !cx.has_flag::<Debugger>() {
 8963            return;
 8964        }
 8965        let source = self
 8966            .buffer
 8967            .read(cx)
 8968            .snapshot(cx)
 8969            .anchor_before(Point::new(display_row.0, 0u32));
 8970
 8971        let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
 8972
 8973        self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
 8974            self,
 8975            source,
 8976            clicked_point,
 8977            context_menu,
 8978            window,
 8979            cx,
 8980        );
 8981    }
 8982
 8983    fn add_edit_breakpoint_block(
 8984        &mut self,
 8985        anchor: Anchor,
 8986        breakpoint: &Breakpoint,
 8987        edit_action: BreakpointPromptEditAction,
 8988        window: &mut Window,
 8989        cx: &mut Context<Self>,
 8990    ) {
 8991        let weak_editor = cx.weak_entity();
 8992        let bp_prompt = cx.new(|cx| {
 8993            BreakpointPromptEditor::new(
 8994                weak_editor,
 8995                anchor,
 8996                breakpoint.clone(),
 8997                edit_action,
 8998                window,
 8999                cx,
 9000            )
 9001        });
 9002
 9003        let height = bp_prompt.update(cx, |this, cx| {
 9004            this.prompt
 9005                .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
 9006        });
 9007        let cloned_prompt = bp_prompt.clone();
 9008        let blocks = vec![BlockProperties {
 9009            style: BlockStyle::Sticky,
 9010            placement: BlockPlacement::Above(anchor),
 9011            height: Some(height),
 9012            render: Arc::new(move |cx| {
 9013                *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
 9014                cloned_prompt.clone().into_any_element()
 9015            }),
 9016            priority: 0,
 9017        }];
 9018
 9019        let focus_handle = bp_prompt.focus_handle(cx);
 9020        window.focus(&focus_handle);
 9021
 9022        let block_ids = self.insert_blocks(blocks, None, cx);
 9023        bp_prompt.update(cx, |prompt, _| {
 9024            prompt.add_block_ids(block_ids);
 9025        });
 9026    }
 9027
 9028    pub(crate) fn breakpoint_at_row(
 9029        &self,
 9030        row: u32,
 9031        window: &mut Window,
 9032        cx: &mut Context<Self>,
 9033    ) -> Option<(Anchor, Breakpoint)> {
 9034        let snapshot = self.snapshot(window, cx);
 9035        let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
 9036
 9037        self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 9038    }
 9039
 9040    pub(crate) fn breakpoint_at_anchor(
 9041        &self,
 9042        breakpoint_position: Anchor,
 9043        snapshot: &EditorSnapshot,
 9044        cx: &mut Context<Self>,
 9045    ) -> Option<(Anchor, Breakpoint)> {
 9046        let project = self.project.clone()?;
 9047
 9048        let buffer_id = breakpoint_position.buffer_id.or_else(|| {
 9049            snapshot
 9050                .buffer_snapshot
 9051                .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
 9052        })?;
 9053
 9054        let enclosing_excerpt = breakpoint_position.excerpt_id;
 9055        let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
 9056        let buffer_snapshot = buffer.read(cx).snapshot();
 9057
 9058        let row = buffer_snapshot
 9059            .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
 9060            .row;
 9061
 9062        let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
 9063        let anchor_end = snapshot
 9064            .buffer_snapshot
 9065            .anchor_after(Point::new(row, line_len));
 9066
 9067        let bp = self
 9068            .breakpoint_store
 9069            .as_ref()?
 9070            .read_with(cx, |breakpoint_store, cx| {
 9071                breakpoint_store
 9072                    .breakpoints(
 9073                        &buffer,
 9074                        Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
 9075                        &buffer_snapshot,
 9076                        cx,
 9077                    )
 9078                    .next()
 9079                    .and_then(|(anchor, bp)| {
 9080                        let breakpoint_row = buffer_snapshot
 9081                            .summary_for_anchor::<text::PointUtf16>(anchor)
 9082                            .row;
 9083
 9084                        if breakpoint_row == row {
 9085                            snapshot
 9086                                .buffer_snapshot
 9087                                .anchor_in_excerpt(enclosing_excerpt, *anchor)
 9088                                .map(|anchor| (anchor, bp.clone()))
 9089                        } else {
 9090                            None
 9091                        }
 9092                    })
 9093            });
 9094        bp
 9095    }
 9096
 9097    pub fn edit_log_breakpoint(
 9098        &mut self,
 9099        _: &EditLogBreakpoint,
 9100        window: &mut Window,
 9101        cx: &mut Context<Self>,
 9102    ) {
 9103        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9104            let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
 9105                message: None,
 9106                state: BreakpointState::Enabled,
 9107                condition: None,
 9108                hit_condition: None,
 9109            });
 9110
 9111            self.add_edit_breakpoint_block(
 9112                anchor,
 9113                &breakpoint,
 9114                BreakpointPromptEditAction::Log,
 9115                window,
 9116                cx,
 9117            );
 9118        }
 9119    }
 9120
 9121    fn breakpoints_at_cursors(
 9122        &self,
 9123        window: &mut Window,
 9124        cx: &mut Context<Self>,
 9125    ) -> Vec<(Anchor, Option<Breakpoint>)> {
 9126        let snapshot = self.snapshot(window, cx);
 9127        let cursors = self
 9128            .selections
 9129            .disjoint_anchors()
 9130            .into_iter()
 9131            .map(|selection| {
 9132                let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
 9133
 9134                let breakpoint_position = self
 9135                    .breakpoint_at_row(cursor_position.row, window, cx)
 9136                    .map(|bp| bp.0)
 9137                    .unwrap_or_else(|| {
 9138                        snapshot
 9139                            .display_snapshot
 9140                            .buffer_snapshot
 9141                            .anchor_after(Point::new(cursor_position.row, 0))
 9142                    });
 9143
 9144                let breakpoint = self
 9145                    .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 9146                    .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
 9147
 9148                breakpoint.unwrap_or_else(|| (breakpoint_position, None))
 9149            })
 9150            // There might be multiple cursors on the same line; all of them should have the same anchors though as their breakpoints positions, which makes it possible to sort and dedup the list.
 9151            .collect::<HashMap<Anchor, _>>();
 9152
 9153        cursors.into_iter().collect()
 9154    }
 9155
 9156    pub fn enable_breakpoint(
 9157        &mut self,
 9158        _: &crate::actions::EnableBreakpoint,
 9159        window: &mut Window,
 9160        cx: &mut Context<Self>,
 9161    ) {
 9162        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9163            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
 9164                continue;
 9165            };
 9166            self.edit_breakpoint_at_anchor(
 9167                anchor,
 9168                breakpoint,
 9169                BreakpointEditAction::InvertState,
 9170                cx,
 9171            );
 9172        }
 9173    }
 9174
 9175    pub fn disable_breakpoint(
 9176        &mut self,
 9177        _: &crate::actions::DisableBreakpoint,
 9178        window: &mut Window,
 9179        cx: &mut Context<Self>,
 9180    ) {
 9181        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9182            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
 9183                continue;
 9184            };
 9185            self.edit_breakpoint_at_anchor(
 9186                anchor,
 9187                breakpoint,
 9188                BreakpointEditAction::InvertState,
 9189                cx,
 9190            );
 9191        }
 9192    }
 9193
 9194    pub fn toggle_breakpoint(
 9195        &mut self,
 9196        _: &crate::actions::ToggleBreakpoint,
 9197        window: &mut Window,
 9198        cx: &mut Context<Self>,
 9199    ) {
 9200        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9201            if let Some(breakpoint) = breakpoint {
 9202                self.edit_breakpoint_at_anchor(
 9203                    anchor,
 9204                    breakpoint,
 9205                    BreakpointEditAction::Toggle,
 9206                    cx,
 9207                );
 9208            } else {
 9209                self.edit_breakpoint_at_anchor(
 9210                    anchor,
 9211                    Breakpoint::new_standard(),
 9212                    BreakpointEditAction::Toggle,
 9213                    cx,
 9214                );
 9215            }
 9216        }
 9217    }
 9218
 9219    pub fn edit_breakpoint_at_anchor(
 9220        &mut self,
 9221        breakpoint_position: Anchor,
 9222        breakpoint: Breakpoint,
 9223        edit_action: BreakpointEditAction,
 9224        cx: &mut Context<Self>,
 9225    ) {
 9226        let Some(breakpoint_store) = &self.breakpoint_store else {
 9227            return;
 9228        };
 9229
 9230        let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
 9231            if breakpoint_position == Anchor::min() {
 9232                self.buffer()
 9233                    .read(cx)
 9234                    .excerpt_buffer_ids()
 9235                    .into_iter()
 9236                    .next()
 9237            } else {
 9238                None
 9239            }
 9240        }) else {
 9241            return;
 9242        };
 9243
 9244        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
 9245            return;
 9246        };
 9247
 9248        breakpoint_store.update(cx, |breakpoint_store, cx| {
 9249            breakpoint_store.toggle_breakpoint(
 9250                buffer,
 9251                (breakpoint_position.text_anchor, breakpoint),
 9252                edit_action,
 9253                cx,
 9254            );
 9255        });
 9256
 9257        cx.notify();
 9258    }
 9259
 9260    #[cfg(any(test, feature = "test-support"))]
 9261    pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
 9262        self.breakpoint_store.clone()
 9263    }
 9264
 9265    pub fn prepare_restore_change(
 9266        &self,
 9267        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 9268        hunk: &MultiBufferDiffHunk,
 9269        cx: &mut App,
 9270    ) -> Option<()> {
 9271        if hunk.is_created_file() {
 9272            return None;
 9273        }
 9274        let buffer = self.buffer.read(cx);
 9275        let diff = buffer.diff_for(hunk.buffer_id)?;
 9276        let buffer = buffer.buffer(hunk.buffer_id)?;
 9277        let buffer = buffer.read(cx);
 9278        let original_text = diff
 9279            .read(cx)
 9280            .base_text()
 9281            .as_rope()
 9282            .slice(hunk.diff_base_byte_range.clone());
 9283        let buffer_snapshot = buffer.snapshot();
 9284        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 9285        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 9286            probe
 9287                .0
 9288                .start
 9289                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 9290                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 9291        }) {
 9292            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 9293            Some(())
 9294        } else {
 9295            None
 9296        }
 9297    }
 9298
 9299    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 9300        self.manipulate_lines(window, cx, |lines| lines.reverse())
 9301    }
 9302
 9303    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 9304        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 9305    }
 9306
 9307    fn manipulate_lines<Fn>(
 9308        &mut self,
 9309        window: &mut Window,
 9310        cx: &mut Context<Self>,
 9311        mut callback: Fn,
 9312    ) where
 9313        Fn: FnMut(&mut Vec<&str>),
 9314    {
 9315        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9316
 9317        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9318        let buffer = self.buffer.read(cx).snapshot(cx);
 9319
 9320        let mut edits = Vec::new();
 9321
 9322        let selections = self.selections.all::<Point>(cx);
 9323        let mut selections = selections.iter().peekable();
 9324        let mut contiguous_row_selections = Vec::new();
 9325        let mut new_selections = Vec::new();
 9326        let mut added_lines = 0;
 9327        let mut removed_lines = 0;
 9328
 9329        while let Some(selection) = selections.next() {
 9330            let (start_row, end_row) = consume_contiguous_rows(
 9331                &mut contiguous_row_selections,
 9332                selection,
 9333                &display_map,
 9334                &mut selections,
 9335            );
 9336
 9337            let start_point = Point::new(start_row.0, 0);
 9338            let end_point = Point::new(
 9339                end_row.previous_row().0,
 9340                buffer.line_len(end_row.previous_row()),
 9341            );
 9342            let text = buffer
 9343                .text_for_range(start_point..end_point)
 9344                .collect::<String>();
 9345
 9346            let mut lines = text.split('\n').collect_vec();
 9347
 9348            let lines_before = lines.len();
 9349            callback(&mut lines);
 9350            let lines_after = lines.len();
 9351
 9352            edits.push((start_point..end_point, lines.join("\n")));
 9353
 9354            // Selections must change based on added and removed line count
 9355            let start_row =
 9356                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 9357            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 9358            new_selections.push(Selection {
 9359                id: selection.id,
 9360                start: start_row,
 9361                end: end_row,
 9362                goal: SelectionGoal::None,
 9363                reversed: selection.reversed,
 9364            });
 9365
 9366            if lines_after > lines_before {
 9367                added_lines += lines_after - lines_before;
 9368            } else if lines_before > lines_after {
 9369                removed_lines += lines_before - lines_after;
 9370            }
 9371        }
 9372
 9373        self.transact(window, cx, |this, window, cx| {
 9374            let buffer = this.buffer.update(cx, |buffer, cx| {
 9375                buffer.edit(edits, None, cx);
 9376                buffer.snapshot(cx)
 9377            });
 9378
 9379            // Recalculate offsets on newly edited buffer
 9380            let new_selections = new_selections
 9381                .iter()
 9382                .map(|s| {
 9383                    let start_point = Point::new(s.start.0, 0);
 9384                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 9385                    Selection {
 9386                        id: s.id,
 9387                        start: buffer.point_to_offset(start_point),
 9388                        end: buffer.point_to_offset(end_point),
 9389                        goal: s.goal,
 9390                        reversed: s.reversed,
 9391                    }
 9392                })
 9393                .collect();
 9394
 9395            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9396                s.select(new_selections);
 9397            });
 9398
 9399            this.request_autoscroll(Autoscroll::fit(), cx);
 9400        });
 9401    }
 9402
 9403    pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
 9404        self.manipulate_text(window, cx, |text| {
 9405            let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
 9406            if has_upper_case_characters {
 9407                text.to_lowercase()
 9408            } else {
 9409                text.to_uppercase()
 9410            }
 9411        })
 9412    }
 9413
 9414    pub fn convert_to_upper_case(
 9415        &mut self,
 9416        _: &ConvertToUpperCase,
 9417        window: &mut Window,
 9418        cx: &mut Context<Self>,
 9419    ) {
 9420        self.manipulate_text(window, cx, |text| text.to_uppercase())
 9421    }
 9422
 9423    pub fn convert_to_lower_case(
 9424        &mut self,
 9425        _: &ConvertToLowerCase,
 9426        window: &mut Window,
 9427        cx: &mut Context<Self>,
 9428    ) {
 9429        self.manipulate_text(window, cx, |text| text.to_lowercase())
 9430    }
 9431
 9432    pub fn convert_to_title_case(
 9433        &mut self,
 9434        _: &ConvertToTitleCase,
 9435        window: &mut Window,
 9436        cx: &mut Context<Self>,
 9437    ) {
 9438        self.manipulate_text(window, cx, |text| {
 9439            text.split('\n')
 9440                .map(|line| line.to_case(Case::Title))
 9441                .join("\n")
 9442        })
 9443    }
 9444
 9445    pub fn convert_to_snake_case(
 9446        &mut self,
 9447        _: &ConvertToSnakeCase,
 9448        window: &mut Window,
 9449        cx: &mut Context<Self>,
 9450    ) {
 9451        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 9452    }
 9453
 9454    pub fn convert_to_kebab_case(
 9455        &mut self,
 9456        _: &ConvertToKebabCase,
 9457        window: &mut Window,
 9458        cx: &mut Context<Self>,
 9459    ) {
 9460        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 9461    }
 9462
 9463    pub fn convert_to_upper_camel_case(
 9464        &mut self,
 9465        _: &ConvertToUpperCamelCase,
 9466        window: &mut Window,
 9467        cx: &mut Context<Self>,
 9468    ) {
 9469        self.manipulate_text(window, cx, |text| {
 9470            text.split('\n')
 9471                .map(|line| line.to_case(Case::UpperCamel))
 9472                .join("\n")
 9473        })
 9474    }
 9475
 9476    pub fn convert_to_lower_camel_case(
 9477        &mut self,
 9478        _: &ConvertToLowerCamelCase,
 9479        window: &mut Window,
 9480        cx: &mut Context<Self>,
 9481    ) {
 9482        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 9483    }
 9484
 9485    pub fn convert_to_opposite_case(
 9486        &mut self,
 9487        _: &ConvertToOppositeCase,
 9488        window: &mut Window,
 9489        cx: &mut Context<Self>,
 9490    ) {
 9491        self.manipulate_text(window, cx, |text| {
 9492            text.chars()
 9493                .fold(String::with_capacity(text.len()), |mut t, c| {
 9494                    if c.is_uppercase() {
 9495                        t.extend(c.to_lowercase());
 9496                    } else {
 9497                        t.extend(c.to_uppercase());
 9498                    }
 9499                    t
 9500                })
 9501        })
 9502    }
 9503
 9504    pub fn convert_to_rot13(
 9505        &mut self,
 9506        _: &ConvertToRot13,
 9507        window: &mut Window,
 9508        cx: &mut Context<Self>,
 9509    ) {
 9510        self.manipulate_text(window, cx, |text| {
 9511            text.chars()
 9512                .map(|c| match c {
 9513                    'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
 9514                    'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
 9515                    _ => c,
 9516                })
 9517                .collect()
 9518        })
 9519    }
 9520
 9521    pub fn convert_to_rot47(
 9522        &mut self,
 9523        _: &ConvertToRot47,
 9524        window: &mut Window,
 9525        cx: &mut Context<Self>,
 9526    ) {
 9527        self.manipulate_text(window, cx, |text| {
 9528            text.chars()
 9529                .map(|c| {
 9530                    let code_point = c as u32;
 9531                    if code_point >= 33 && code_point <= 126 {
 9532                        return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
 9533                    }
 9534                    c
 9535                })
 9536                .collect()
 9537        })
 9538    }
 9539
 9540    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 9541    where
 9542        Fn: FnMut(&str) -> String,
 9543    {
 9544        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9545        let buffer = self.buffer.read(cx).snapshot(cx);
 9546
 9547        let mut new_selections = Vec::new();
 9548        let mut edits = Vec::new();
 9549        let mut selection_adjustment = 0i32;
 9550
 9551        for selection in self.selections.all::<usize>(cx) {
 9552            let selection_is_empty = selection.is_empty();
 9553
 9554            let (start, end) = if selection_is_empty {
 9555                let word_range = movement::surrounding_word(
 9556                    &display_map,
 9557                    selection.start.to_display_point(&display_map),
 9558                );
 9559                let start = word_range.start.to_offset(&display_map, Bias::Left);
 9560                let end = word_range.end.to_offset(&display_map, Bias::Left);
 9561                (start, end)
 9562            } else {
 9563                (selection.start, selection.end)
 9564            };
 9565
 9566            let text = buffer.text_for_range(start..end).collect::<String>();
 9567            let old_length = text.len() as i32;
 9568            let text = callback(&text);
 9569
 9570            new_selections.push(Selection {
 9571                start: (start as i32 - selection_adjustment) as usize,
 9572                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 9573                goal: SelectionGoal::None,
 9574                ..selection
 9575            });
 9576
 9577            selection_adjustment += old_length - text.len() as i32;
 9578
 9579            edits.push((start..end, text));
 9580        }
 9581
 9582        self.transact(window, cx, |this, window, cx| {
 9583            this.buffer.update(cx, |buffer, cx| {
 9584                buffer.edit(edits, None, cx);
 9585            });
 9586
 9587            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9588                s.select(new_selections);
 9589            });
 9590
 9591            this.request_autoscroll(Autoscroll::fit(), cx);
 9592        });
 9593    }
 9594
 9595    pub fn duplicate(
 9596        &mut self,
 9597        upwards: bool,
 9598        whole_lines: bool,
 9599        window: &mut Window,
 9600        cx: &mut Context<Self>,
 9601    ) {
 9602        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9603
 9604        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9605        let buffer = &display_map.buffer_snapshot;
 9606        let selections = self.selections.all::<Point>(cx);
 9607
 9608        let mut edits = Vec::new();
 9609        let mut selections_iter = selections.iter().peekable();
 9610        while let Some(selection) = selections_iter.next() {
 9611            let mut rows = selection.spanned_rows(false, &display_map);
 9612            // duplicate line-wise
 9613            if whole_lines || selection.start == selection.end {
 9614                // Avoid duplicating the same lines twice.
 9615                while let Some(next_selection) = selections_iter.peek() {
 9616                    let next_rows = next_selection.spanned_rows(false, &display_map);
 9617                    if next_rows.start < rows.end {
 9618                        rows.end = next_rows.end;
 9619                        selections_iter.next().unwrap();
 9620                    } else {
 9621                        break;
 9622                    }
 9623                }
 9624
 9625                // Copy the text from the selected row region and splice it either at the start
 9626                // or end of the region.
 9627                let start = Point::new(rows.start.0, 0);
 9628                let end = Point::new(
 9629                    rows.end.previous_row().0,
 9630                    buffer.line_len(rows.end.previous_row()),
 9631                );
 9632                let text = buffer
 9633                    .text_for_range(start..end)
 9634                    .chain(Some("\n"))
 9635                    .collect::<String>();
 9636                let insert_location = if upwards {
 9637                    Point::new(rows.end.0, 0)
 9638                } else {
 9639                    start
 9640                };
 9641                edits.push((insert_location..insert_location, text));
 9642            } else {
 9643                // duplicate character-wise
 9644                let start = selection.start;
 9645                let end = selection.end;
 9646                let text = buffer.text_for_range(start..end).collect::<String>();
 9647                edits.push((selection.end..selection.end, text));
 9648            }
 9649        }
 9650
 9651        self.transact(window, cx, |this, _, cx| {
 9652            this.buffer.update(cx, |buffer, cx| {
 9653                buffer.edit(edits, None, cx);
 9654            });
 9655
 9656            this.request_autoscroll(Autoscroll::fit(), cx);
 9657        });
 9658    }
 9659
 9660    pub fn duplicate_line_up(
 9661        &mut self,
 9662        _: &DuplicateLineUp,
 9663        window: &mut Window,
 9664        cx: &mut Context<Self>,
 9665    ) {
 9666        self.duplicate(true, true, window, cx);
 9667    }
 9668
 9669    pub fn duplicate_line_down(
 9670        &mut self,
 9671        _: &DuplicateLineDown,
 9672        window: &mut Window,
 9673        cx: &mut Context<Self>,
 9674    ) {
 9675        self.duplicate(false, true, window, cx);
 9676    }
 9677
 9678    pub fn duplicate_selection(
 9679        &mut self,
 9680        _: &DuplicateSelection,
 9681        window: &mut Window,
 9682        cx: &mut Context<Self>,
 9683    ) {
 9684        self.duplicate(false, false, window, cx);
 9685    }
 9686
 9687    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 9688        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9689
 9690        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9691        let buffer = self.buffer.read(cx).snapshot(cx);
 9692
 9693        let mut edits = Vec::new();
 9694        let mut unfold_ranges = Vec::new();
 9695        let mut refold_creases = Vec::new();
 9696
 9697        let selections = self.selections.all::<Point>(cx);
 9698        let mut selections = selections.iter().peekable();
 9699        let mut contiguous_row_selections = Vec::new();
 9700        let mut new_selections = Vec::new();
 9701
 9702        while let Some(selection) = selections.next() {
 9703            // Find all the selections that span a contiguous row range
 9704            let (start_row, end_row) = consume_contiguous_rows(
 9705                &mut contiguous_row_selections,
 9706                selection,
 9707                &display_map,
 9708                &mut selections,
 9709            );
 9710
 9711            // Move the text spanned by the row range to be before the line preceding the row range
 9712            if start_row.0 > 0 {
 9713                let range_to_move = Point::new(
 9714                    start_row.previous_row().0,
 9715                    buffer.line_len(start_row.previous_row()),
 9716                )
 9717                    ..Point::new(
 9718                        end_row.previous_row().0,
 9719                        buffer.line_len(end_row.previous_row()),
 9720                    );
 9721                let insertion_point = display_map
 9722                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 9723                    .0;
 9724
 9725                // Don't move lines across excerpts
 9726                if buffer
 9727                    .excerpt_containing(insertion_point..range_to_move.end)
 9728                    .is_some()
 9729                {
 9730                    let text = buffer
 9731                        .text_for_range(range_to_move.clone())
 9732                        .flat_map(|s| s.chars())
 9733                        .skip(1)
 9734                        .chain(['\n'])
 9735                        .collect::<String>();
 9736
 9737                    edits.push((
 9738                        buffer.anchor_after(range_to_move.start)
 9739                            ..buffer.anchor_before(range_to_move.end),
 9740                        String::new(),
 9741                    ));
 9742                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9743                    edits.push((insertion_anchor..insertion_anchor, text));
 9744
 9745                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 9746
 9747                    // Move selections up
 9748                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9749                        |mut selection| {
 9750                            selection.start.row -= row_delta;
 9751                            selection.end.row -= row_delta;
 9752                            selection
 9753                        },
 9754                    ));
 9755
 9756                    // Move folds up
 9757                    unfold_ranges.push(range_to_move.clone());
 9758                    for fold in display_map.folds_in_range(
 9759                        buffer.anchor_before(range_to_move.start)
 9760                            ..buffer.anchor_after(range_to_move.end),
 9761                    ) {
 9762                        let mut start = fold.range.start.to_point(&buffer);
 9763                        let mut end = fold.range.end.to_point(&buffer);
 9764                        start.row -= row_delta;
 9765                        end.row -= row_delta;
 9766                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9767                    }
 9768                }
 9769            }
 9770
 9771            // If we didn't move line(s), preserve the existing selections
 9772            new_selections.append(&mut contiguous_row_selections);
 9773        }
 9774
 9775        self.transact(window, cx, |this, window, cx| {
 9776            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9777            this.buffer.update(cx, |buffer, cx| {
 9778                for (range, text) in edits {
 9779                    buffer.edit([(range, text)], None, cx);
 9780                }
 9781            });
 9782            this.fold_creases(refold_creases, true, window, cx);
 9783            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9784                s.select(new_selections);
 9785            })
 9786        });
 9787    }
 9788
 9789    pub fn move_line_down(
 9790        &mut self,
 9791        _: &MoveLineDown,
 9792        window: &mut Window,
 9793        cx: &mut Context<Self>,
 9794    ) {
 9795        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9796
 9797        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9798        let buffer = self.buffer.read(cx).snapshot(cx);
 9799
 9800        let mut edits = Vec::new();
 9801        let mut unfold_ranges = Vec::new();
 9802        let mut refold_creases = Vec::new();
 9803
 9804        let selections = self.selections.all::<Point>(cx);
 9805        let mut selections = selections.iter().peekable();
 9806        let mut contiguous_row_selections = Vec::new();
 9807        let mut new_selections = Vec::new();
 9808
 9809        while let Some(selection) = selections.next() {
 9810            // Find all the selections that span a contiguous row range
 9811            let (start_row, end_row) = consume_contiguous_rows(
 9812                &mut contiguous_row_selections,
 9813                selection,
 9814                &display_map,
 9815                &mut selections,
 9816            );
 9817
 9818            // Move the text spanned by the row range to be after the last line of the row range
 9819            if end_row.0 <= buffer.max_point().row {
 9820                let range_to_move =
 9821                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 9822                let insertion_point = display_map
 9823                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 9824                    .0;
 9825
 9826                // Don't move lines across excerpt boundaries
 9827                if buffer
 9828                    .excerpt_containing(range_to_move.start..insertion_point)
 9829                    .is_some()
 9830                {
 9831                    let mut text = String::from("\n");
 9832                    text.extend(buffer.text_for_range(range_to_move.clone()));
 9833                    text.pop(); // Drop trailing newline
 9834                    edits.push((
 9835                        buffer.anchor_after(range_to_move.start)
 9836                            ..buffer.anchor_before(range_to_move.end),
 9837                        String::new(),
 9838                    ));
 9839                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9840                    edits.push((insertion_anchor..insertion_anchor, text));
 9841
 9842                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 9843
 9844                    // Move selections down
 9845                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9846                        |mut selection| {
 9847                            selection.start.row += row_delta;
 9848                            selection.end.row += row_delta;
 9849                            selection
 9850                        },
 9851                    ));
 9852
 9853                    // Move folds down
 9854                    unfold_ranges.push(range_to_move.clone());
 9855                    for fold in display_map.folds_in_range(
 9856                        buffer.anchor_before(range_to_move.start)
 9857                            ..buffer.anchor_after(range_to_move.end),
 9858                    ) {
 9859                        let mut start = fold.range.start.to_point(&buffer);
 9860                        let mut end = fold.range.end.to_point(&buffer);
 9861                        start.row += row_delta;
 9862                        end.row += row_delta;
 9863                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9864                    }
 9865                }
 9866            }
 9867
 9868            // If we didn't move line(s), preserve the existing selections
 9869            new_selections.append(&mut contiguous_row_selections);
 9870        }
 9871
 9872        self.transact(window, cx, |this, window, cx| {
 9873            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9874            this.buffer.update(cx, |buffer, cx| {
 9875                for (range, text) in edits {
 9876                    buffer.edit([(range, text)], None, cx);
 9877                }
 9878            });
 9879            this.fold_creases(refold_creases, true, window, cx);
 9880            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9881                s.select(new_selections)
 9882            });
 9883        });
 9884    }
 9885
 9886    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 9887        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9888        let text_layout_details = &self.text_layout_details(window);
 9889        self.transact(window, cx, |this, window, cx| {
 9890            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9891                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 9892                s.move_with(|display_map, selection| {
 9893                    if !selection.is_empty() {
 9894                        return;
 9895                    }
 9896
 9897                    let mut head = selection.head();
 9898                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 9899                    if head.column() == display_map.line_len(head.row()) {
 9900                        transpose_offset = display_map
 9901                            .buffer_snapshot
 9902                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9903                    }
 9904
 9905                    if transpose_offset == 0 {
 9906                        return;
 9907                    }
 9908
 9909                    *head.column_mut() += 1;
 9910                    head = display_map.clip_point(head, Bias::Right);
 9911                    let goal = SelectionGoal::HorizontalPosition(
 9912                        display_map
 9913                            .x_for_display_point(head, text_layout_details)
 9914                            .into(),
 9915                    );
 9916                    selection.collapse_to(head, goal);
 9917
 9918                    let transpose_start = display_map
 9919                        .buffer_snapshot
 9920                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9921                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 9922                        let transpose_end = display_map
 9923                            .buffer_snapshot
 9924                            .clip_offset(transpose_offset + 1, Bias::Right);
 9925                        if let Some(ch) =
 9926                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 9927                        {
 9928                            edits.push((transpose_start..transpose_offset, String::new()));
 9929                            edits.push((transpose_end..transpose_end, ch.to_string()));
 9930                        }
 9931                    }
 9932                });
 9933                edits
 9934            });
 9935            this.buffer
 9936                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 9937            let selections = this.selections.all::<usize>(cx);
 9938            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9939                s.select(selections);
 9940            });
 9941        });
 9942    }
 9943
 9944    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 9945        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9946        self.rewrap_impl(RewrapOptions::default(), cx)
 9947    }
 9948
 9949    pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
 9950        let buffer = self.buffer.read(cx).snapshot(cx);
 9951        let selections = self.selections.all::<Point>(cx);
 9952        let mut selections = selections.iter().peekable();
 9953
 9954        let mut edits = Vec::new();
 9955        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 9956
 9957        while let Some(selection) = selections.next() {
 9958            let mut start_row = selection.start.row;
 9959            let mut end_row = selection.end.row;
 9960
 9961            // Skip selections that overlap with a range that has already been rewrapped.
 9962            let selection_range = start_row..end_row;
 9963            if rewrapped_row_ranges
 9964                .iter()
 9965                .any(|range| range.overlaps(&selection_range))
 9966            {
 9967                continue;
 9968            }
 9969
 9970            let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
 9971
 9972            // Since not all lines in the selection may be at the same indent
 9973            // level, choose the indent size that is the most common between all
 9974            // of the lines.
 9975            //
 9976            // If there is a tie, we use the deepest indent.
 9977            let (indent_size, indent_end) = {
 9978                let mut indent_size_occurrences = HashMap::default();
 9979                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 9980
 9981                for row in start_row..=end_row {
 9982                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 9983                    rows_by_indent_size.entry(indent).or_default().push(row);
 9984                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 9985                }
 9986
 9987                let indent_size = indent_size_occurrences
 9988                    .into_iter()
 9989                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 9990                    .map(|(indent, _)| indent)
 9991                    .unwrap_or_default();
 9992                let row = rows_by_indent_size[&indent_size][0];
 9993                let indent_end = Point::new(row, indent_size.len);
 9994
 9995                (indent_size, indent_end)
 9996            };
 9997
 9998            let mut line_prefix = indent_size.chars().collect::<String>();
 9999
10000            let mut inside_comment = false;
10001            if let Some(comment_prefix) =
10002                buffer
10003                    .language_scope_at(selection.head())
10004                    .and_then(|language| {
10005                        language
10006                            .line_comment_prefixes()
10007                            .iter()
10008                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
10009                            .cloned()
10010                    })
10011            {
10012                line_prefix.push_str(&comment_prefix);
10013                inside_comment = true;
10014            }
10015
10016            let language_settings = buffer.language_settings_at(selection.head(), cx);
10017            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
10018                RewrapBehavior::InComments => inside_comment,
10019                RewrapBehavior::InSelections => !selection.is_empty(),
10020                RewrapBehavior::Anywhere => true,
10021            };
10022
10023            let should_rewrap = options.override_language_settings
10024                || allow_rewrap_based_on_language
10025                || self.hard_wrap.is_some();
10026            if !should_rewrap {
10027                continue;
10028            }
10029
10030            if selection.is_empty() {
10031                'expand_upwards: while start_row > 0 {
10032                    let prev_row = start_row - 1;
10033                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
10034                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
10035                    {
10036                        start_row = prev_row;
10037                    } else {
10038                        break 'expand_upwards;
10039                    }
10040                }
10041
10042                'expand_downwards: while end_row < buffer.max_point().row {
10043                    let next_row = end_row + 1;
10044                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
10045                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
10046                    {
10047                        end_row = next_row;
10048                    } else {
10049                        break 'expand_downwards;
10050                    }
10051                }
10052            }
10053
10054            let start = Point::new(start_row, 0);
10055            let start_offset = start.to_offset(&buffer);
10056            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
10057            let selection_text = buffer.text_for_range(start..end).collect::<String>();
10058            let Some(lines_without_prefixes) = selection_text
10059                .lines()
10060                .map(|line| {
10061                    line.strip_prefix(&line_prefix)
10062                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
10063                        .ok_or_else(|| {
10064                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
10065                        })
10066                })
10067                .collect::<Result<Vec<_>, _>>()
10068                .log_err()
10069            else {
10070                continue;
10071            };
10072
10073            let wrap_column = self.hard_wrap.unwrap_or_else(|| {
10074                buffer
10075                    .language_settings_at(Point::new(start_row, 0), cx)
10076                    .preferred_line_length as usize
10077            });
10078            let wrapped_text = wrap_with_prefix(
10079                line_prefix,
10080                lines_without_prefixes.join("\n"),
10081                wrap_column,
10082                tab_size,
10083                options.preserve_existing_whitespace,
10084            );
10085
10086            // TODO: should always use char-based diff while still supporting cursor behavior that
10087            // matches vim.
10088            let mut diff_options = DiffOptions::default();
10089            if options.override_language_settings {
10090                diff_options.max_word_diff_len = 0;
10091                diff_options.max_word_diff_line_count = 0;
10092            } else {
10093                diff_options.max_word_diff_len = usize::MAX;
10094                diff_options.max_word_diff_line_count = usize::MAX;
10095            }
10096
10097            for (old_range, new_text) in
10098                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
10099            {
10100                let edit_start = buffer.anchor_after(start_offset + old_range.start);
10101                let edit_end = buffer.anchor_after(start_offset + old_range.end);
10102                edits.push((edit_start..edit_end, new_text));
10103            }
10104
10105            rewrapped_row_ranges.push(start_row..=end_row);
10106        }
10107
10108        self.buffer
10109            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10110    }
10111
10112    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
10113        let mut text = String::new();
10114        let buffer = self.buffer.read(cx).snapshot(cx);
10115        let mut selections = self.selections.all::<Point>(cx);
10116        let mut clipboard_selections = Vec::with_capacity(selections.len());
10117        {
10118            let max_point = buffer.max_point();
10119            let mut is_first = true;
10120            for selection in &mut selections {
10121                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10122                if is_entire_line {
10123                    selection.start = Point::new(selection.start.row, 0);
10124                    if !selection.is_empty() && selection.end.column == 0 {
10125                        selection.end = cmp::min(max_point, selection.end);
10126                    } else {
10127                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
10128                    }
10129                    selection.goal = SelectionGoal::None;
10130                }
10131                if is_first {
10132                    is_first = false;
10133                } else {
10134                    text += "\n";
10135                }
10136                let mut len = 0;
10137                for chunk in buffer.text_for_range(selection.start..selection.end) {
10138                    text.push_str(chunk);
10139                    len += chunk.len();
10140                }
10141                clipboard_selections.push(ClipboardSelection {
10142                    len,
10143                    is_entire_line,
10144                    first_line_indent: buffer
10145                        .indent_size_for_line(MultiBufferRow(selection.start.row))
10146                        .len,
10147                });
10148            }
10149        }
10150
10151        self.transact(window, cx, |this, window, cx| {
10152            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10153                s.select(selections);
10154            });
10155            this.insert("", window, cx);
10156        });
10157        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
10158    }
10159
10160    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
10161        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10162        let item = self.cut_common(window, cx);
10163        cx.write_to_clipboard(item);
10164    }
10165
10166    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
10167        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10168        self.change_selections(None, window, cx, |s| {
10169            s.move_with(|snapshot, sel| {
10170                if sel.is_empty() {
10171                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
10172                }
10173            });
10174        });
10175        let item = self.cut_common(window, cx);
10176        cx.set_global(KillRing(item))
10177    }
10178
10179    pub fn kill_ring_yank(
10180        &mut self,
10181        _: &KillRingYank,
10182        window: &mut Window,
10183        cx: &mut Context<Self>,
10184    ) {
10185        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10186        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10187            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10188                (kill_ring.text().to_string(), kill_ring.metadata_json())
10189            } else {
10190                return;
10191            }
10192        } else {
10193            return;
10194        };
10195        self.do_paste(&text, metadata, false, window, cx);
10196    }
10197
10198    pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10199        self.do_copy(true, cx);
10200    }
10201
10202    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10203        self.do_copy(false, cx);
10204    }
10205
10206    fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10207        let selections = self.selections.all::<Point>(cx);
10208        let buffer = self.buffer.read(cx).read(cx);
10209        let mut text = String::new();
10210
10211        let mut clipboard_selections = Vec::with_capacity(selections.len());
10212        {
10213            let max_point = buffer.max_point();
10214            let mut is_first = true;
10215            for selection in &selections {
10216                let mut start = selection.start;
10217                let mut end = selection.end;
10218                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10219                if is_entire_line {
10220                    start = Point::new(start.row, 0);
10221                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
10222                }
10223
10224                let mut trimmed_selections = Vec::new();
10225                if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10226                    let row = MultiBufferRow(start.row);
10227                    let first_indent = buffer.indent_size_for_line(row);
10228                    if first_indent.len == 0 || start.column > first_indent.len {
10229                        trimmed_selections.push(start..end);
10230                    } else {
10231                        trimmed_selections.push(
10232                            Point::new(row.0, first_indent.len)
10233                                ..Point::new(row.0, buffer.line_len(row)),
10234                        );
10235                        for row in start.row + 1..=end.row {
10236                            let mut line_len = buffer.line_len(MultiBufferRow(row));
10237                            if row == end.row {
10238                                line_len = end.column;
10239                            }
10240                            if line_len == 0 {
10241                                trimmed_selections
10242                                    .push(Point::new(row, 0)..Point::new(row, line_len));
10243                                continue;
10244                            }
10245                            let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10246                            if row_indent_size.len >= first_indent.len {
10247                                trimmed_selections.push(
10248                                    Point::new(row, first_indent.len)..Point::new(row, line_len),
10249                                );
10250                            } else {
10251                                trimmed_selections.clear();
10252                                trimmed_selections.push(start..end);
10253                                break;
10254                            }
10255                        }
10256                    }
10257                } else {
10258                    trimmed_selections.push(start..end);
10259                }
10260
10261                for trimmed_range in trimmed_selections {
10262                    if is_first {
10263                        is_first = false;
10264                    } else {
10265                        text += "\n";
10266                    }
10267                    let mut len = 0;
10268                    for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10269                        text.push_str(chunk);
10270                        len += chunk.len();
10271                    }
10272                    clipboard_selections.push(ClipboardSelection {
10273                        len,
10274                        is_entire_line,
10275                        first_line_indent: buffer
10276                            .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10277                            .len,
10278                    });
10279                }
10280            }
10281        }
10282
10283        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10284            text,
10285            clipboard_selections,
10286        ));
10287    }
10288
10289    pub fn do_paste(
10290        &mut self,
10291        text: &String,
10292        clipboard_selections: Option<Vec<ClipboardSelection>>,
10293        handle_entire_lines: bool,
10294        window: &mut Window,
10295        cx: &mut Context<Self>,
10296    ) {
10297        if self.read_only(cx) {
10298            return;
10299        }
10300
10301        let clipboard_text = Cow::Borrowed(text);
10302
10303        self.transact(window, cx, |this, window, cx| {
10304            if let Some(mut clipboard_selections) = clipboard_selections {
10305                let old_selections = this.selections.all::<usize>(cx);
10306                let all_selections_were_entire_line =
10307                    clipboard_selections.iter().all(|s| s.is_entire_line);
10308                let first_selection_indent_column =
10309                    clipboard_selections.first().map(|s| s.first_line_indent);
10310                if clipboard_selections.len() != old_selections.len() {
10311                    clipboard_selections.drain(..);
10312                }
10313                let cursor_offset = this.selections.last::<usize>(cx).head();
10314                let mut auto_indent_on_paste = true;
10315
10316                this.buffer.update(cx, |buffer, cx| {
10317                    let snapshot = buffer.read(cx);
10318                    auto_indent_on_paste = snapshot
10319                        .language_settings_at(cursor_offset, cx)
10320                        .auto_indent_on_paste;
10321
10322                    let mut start_offset = 0;
10323                    let mut edits = Vec::new();
10324                    let mut original_indent_columns = Vec::new();
10325                    for (ix, selection) in old_selections.iter().enumerate() {
10326                        let to_insert;
10327                        let entire_line;
10328                        let original_indent_column;
10329                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10330                            let end_offset = start_offset + clipboard_selection.len;
10331                            to_insert = &clipboard_text[start_offset..end_offset];
10332                            entire_line = clipboard_selection.is_entire_line;
10333                            start_offset = end_offset + 1;
10334                            original_indent_column = Some(clipboard_selection.first_line_indent);
10335                        } else {
10336                            to_insert = clipboard_text.as_str();
10337                            entire_line = all_selections_were_entire_line;
10338                            original_indent_column = first_selection_indent_column
10339                        }
10340
10341                        // If the corresponding selection was empty when this slice of the
10342                        // clipboard text was written, then the entire line containing the
10343                        // selection was copied. If this selection is also currently empty,
10344                        // then paste the line before the current line of the buffer.
10345                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
10346                            let column = selection.start.to_point(&snapshot).column as usize;
10347                            let line_start = selection.start - column;
10348                            line_start..line_start
10349                        } else {
10350                            selection.range()
10351                        };
10352
10353                        edits.push((range, to_insert));
10354                        original_indent_columns.push(original_indent_column);
10355                    }
10356                    drop(snapshot);
10357
10358                    buffer.edit(
10359                        edits,
10360                        if auto_indent_on_paste {
10361                            Some(AutoindentMode::Block {
10362                                original_indent_columns,
10363                            })
10364                        } else {
10365                            None
10366                        },
10367                        cx,
10368                    );
10369                });
10370
10371                let selections = this.selections.all::<usize>(cx);
10372                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10373                    s.select(selections)
10374                });
10375            } else {
10376                this.insert(&clipboard_text, window, cx);
10377            }
10378        });
10379    }
10380
10381    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10382        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10383        if let Some(item) = cx.read_from_clipboard() {
10384            let entries = item.entries();
10385
10386            match entries.first() {
10387                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10388                // of all the pasted entries.
10389                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10390                    .do_paste(
10391                        clipboard_string.text(),
10392                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10393                        true,
10394                        window,
10395                        cx,
10396                    ),
10397                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10398            }
10399        }
10400    }
10401
10402    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10403        if self.read_only(cx) {
10404            return;
10405        }
10406
10407        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10408
10409        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10410            if let Some((selections, _)) =
10411                self.selection_history.transaction(transaction_id).cloned()
10412            {
10413                self.change_selections(None, window, cx, |s| {
10414                    s.select_anchors(selections.to_vec());
10415                });
10416            } else {
10417                log::error!(
10418                    "No entry in selection_history found for undo. \
10419                     This may correspond to a bug where undo does not update the selection. \
10420                     If this is occurring, please add details to \
10421                     https://github.com/zed-industries/zed/issues/22692"
10422                );
10423            }
10424            self.request_autoscroll(Autoscroll::fit(), cx);
10425            self.unmark_text(window, cx);
10426            self.refresh_inline_completion(true, false, window, cx);
10427            cx.emit(EditorEvent::Edited { transaction_id });
10428            cx.emit(EditorEvent::TransactionUndone { transaction_id });
10429        }
10430    }
10431
10432    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10433        if self.read_only(cx) {
10434            return;
10435        }
10436
10437        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10438
10439        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10440            if let Some((_, Some(selections))) =
10441                self.selection_history.transaction(transaction_id).cloned()
10442            {
10443                self.change_selections(None, window, cx, |s| {
10444                    s.select_anchors(selections.to_vec());
10445                });
10446            } else {
10447                log::error!(
10448                    "No entry in selection_history found for redo. \
10449                     This may correspond to a bug where undo does not update the selection. \
10450                     If this is occurring, please add details to \
10451                     https://github.com/zed-industries/zed/issues/22692"
10452                );
10453            }
10454            self.request_autoscroll(Autoscroll::fit(), cx);
10455            self.unmark_text(window, cx);
10456            self.refresh_inline_completion(true, false, window, cx);
10457            cx.emit(EditorEvent::Edited { transaction_id });
10458        }
10459    }
10460
10461    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10462        self.buffer
10463            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10464    }
10465
10466    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10467        self.buffer
10468            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10469    }
10470
10471    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10472        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10473        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10474            s.move_with(|map, selection| {
10475                let cursor = if selection.is_empty() {
10476                    movement::left(map, selection.start)
10477                } else {
10478                    selection.start
10479                };
10480                selection.collapse_to(cursor, SelectionGoal::None);
10481            });
10482        })
10483    }
10484
10485    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10486        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10487        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10488            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10489        })
10490    }
10491
10492    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10493        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10494        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10495            s.move_with(|map, selection| {
10496                let cursor = if selection.is_empty() {
10497                    movement::right(map, selection.end)
10498                } else {
10499                    selection.end
10500                };
10501                selection.collapse_to(cursor, SelectionGoal::None)
10502            });
10503        })
10504    }
10505
10506    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10507        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10508        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10509            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10510        })
10511    }
10512
10513    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10514        if self.take_rename(true, window, cx).is_some() {
10515            return;
10516        }
10517
10518        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10519            cx.propagate();
10520            return;
10521        }
10522
10523        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10524
10525        let text_layout_details = &self.text_layout_details(window);
10526        let selection_count = self.selections.count();
10527        let first_selection = self.selections.first_anchor();
10528
10529        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10530            s.move_with(|map, selection| {
10531                if !selection.is_empty() {
10532                    selection.goal = SelectionGoal::None;
10533                }
10534                let (cursor, goal) = movement::up(
10535                    map,
10536                    selection.start,
10537                    selection.goal,
10538                    false,
10539                    text_layout_details,
10540                );
10541                selection.collapse_to(cursor, goal);
10542            });
10543        });
10544
10545        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10546        {
10547            cx.propagate();
10548        }
10549    }
10550
10551    pub fn move_up_by_lines(
10552        &mut self,
10553        action: &MoveUpByLines,
10554        window: &mut Window,
10555        cx: &mut Context<Self>,
10556    ) {
10557        if self.take_rename(true, window, cx).is_some() {
10558            return;
10559        }
10560
10561        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10562            cx.propagate();
10563            return;
10564        }
10565
10566        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10567
10568        let text_layout_details = &self.text_layout_details(window);
10569
10570        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10571            s.move_with(|map, selection| {
10572                if !selection.is_empty() {
10573                    selection.goal = SelectionGoal::None;
10574                }
10575                let (cursor, goal) = movement::up_by_rows(
10576                    map,
10577                    selection.start,
10578                    action.lines,
10579                    selection.goal,
10580                    false,
10581                    text_layout_details,
10582                );
10583                selection.collapse_to(cursor, goal);
10584            });
10585        })
10586    }
10587
10588    pub fn move_down_by_lines(
10589        &mut self,
10590        action: &MoveDownByLines,
10591        window: &mut Window,
10592        cx: &mut Context<Self>,
10593    ) {
10594        if self.take_rename(true, window, cx).is_some() {
10595            return;
10596        }
10597
10598        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10599            cx.propagate();
10600            return;
10601        }
10602
10603        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10604
10605        let text_layout_details = &self.text_layout_details(window);
10606
10607        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10608            s.move_with(|map, selection| {
10609                if !selection.is_empty() {
10610                    selection.goal = SelectionGoal::None;
10611                }
10612                let (cursor, goal) = movement::down_by_rows(
10613                    map,
10614                    selection.start,
10615                    action.lines,
10616                    selection.goal,
10617                    false,
10618                    text_layout_details,
10619                );
10620                selection.collapse_to(cursor, goal);
10621            });
10622        })
10623    }
10624
10625    pub fn select_down_by_lines(
10626        &mut self,
10627        action: &SelectDownByLines,
10628        window: &mut Window,
10629        cx: &mut Context<Self>,
10630    ) {
10631        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10632        let text_layout_details = &self.text_layout_details(window);
10633        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10634            s.move_heads_with(|map, head, goal| {
10635                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10636            })
10637        })
10638    }
10639
10640    pub fn select_up_by_lines(
10641        &mut self,
10642        action: &SelectUpByLines,
10643        window: &mut Window,
10644        cx: &mut Context<Self>,
10645    ) {
10646        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10647        let text_layout_details = &self.text_layout_details(window);
10648        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10649            s.move_heads_with(|map, head, goal| {
10650                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10651            })
10652        })
10653    }
10654
10655    pub fn select_page_up(
10656        &mut self,
10657        _: &SelectPageUp,
10658        window: &mut Window,
10659        cx: &mut Context<Self>,
10660    ) {
10661        let Some(row_count) = self.visible_row_count() else {
10662            return;
10663        };
10664
10665        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10666
10667        let text_layout_details = &self.text_layout_details(window);
10668
10669        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10670            s.move_heads_with(|map, head, goal| {
10671                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10672            })
10673        })
10674    }
10675
10676    pub fn move_page_up(
10677        &mut self,
10678        action: &MovePageUp,
10679        window: &mut Window,
10680        cx: &mut Context<Self>,
10681    ) {
10682        if self.take_rename(true, window, cx).is_some() {
10683            return;
10684        }
10685
10686        if self
10687            .context_menu
10688            .borrow_mut()
10689            .as_mut()
10690            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10691            .unwrap_or(false)
10692        {
10693            return;
10694        }
10695
10696        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10697            cx.propagate();
10698            return;
10699        }
10700
10701        let Some(row_count) = self.visible_row_count() else {
10702            return;
10703        };
10704
10705        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10706
10707        let autoscroll = if action.center_cursor {
10708            Autoscroll::center()
10709        } else {
10710            Autoscroll::fit()
10711        };
10712
10713        let text_layout_details = &self.text_layout_details(window);
10714
10715        self.change_selections(Some(autoscroll), window, cx, |s| {
10716            s.move_with(|map, selection| {
10717                if !selection.is_empty() {
10718                    selection.goal = SelectionGoal::None;
10719                }
10720                let (cursor, goal) = movement::up_by_rows(
10721                    map,
10722                    selection.end,
10723                    row_count,
10724                    selection.goal,
10725                    false,
10726                    text_layout_details,
10727                );
10728                selection.collapse_to(cursor, goal);
10729            });
10730        });
10731    }
10732
10733    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10734        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10735        let text_layout_details = &self.text_layout_details(window);
10736        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10737            s.move_heads_with(|map, head, goal| {
10738                movement::up(map, head, goal, false, text_layout_details)
10739            })
10740        })
10741    }
10742
10743    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10744        self.take_rename(true, window, cx);
10745
10746        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10747            cx.propagate();
10748            return;
10749        }
10750
10751        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10752
10753        let text_layout_details = &self.text_layout_details(window);
10754        let selection_count = self.selections.count();
10755        let first_selection = self.selections.first_anchor();
10756
10757        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10758            s.move_with(|map, selection| {
10759                if !selection.is_empty() {
10760                    selection.goal = SelectionGoal::None;
10761                }
10762                let (cursor, goal) = movement::down(
10763                    map,
10764                    selection.end,
10765                    selection.goal,
10766                    false,
10767                    text_layout_details,
10768                );
10769                selection.collapse_to(cursor, goal);
10770            });
10771        });
10772
10773        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10774        {
10775            cx.propagate();
10776        }
10777    }
10778
10779    pub fn select_page_down(
10780        &mut self,
10781        _: &SelectPageDown,
10782        window: &mut Window,
10783        cx: &mut Context<Self>,
10784    ) {
10785        let Some(row_count) = self.visible_row_count() else {
10786            return;
10787        };
10788
10789        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10790
10791        let text_layout_details = &self.text_layout_details(window);
10792
10793        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10794            s.move_heads_with(|map, head, goal| {
10795                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10796            })
10797        })
10798    }
10799
10800    pub fn move_page_down(
10801        &mut self,
10802        action: &MovePageDown,
10803        window: &mut Window,
10804        cx: &mut Context<Self>,
10805    ) {
10806        if self.take_rename(true, window, cx).is_some() {
10807            return;
10808        }
10809
10810        if self
10811            .context_menu
10812            .borrow_mut()
10813            .as_mut()
10814            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10815            .unwrap_or(false)
10816        {
10817            return;
10818        }
10819
10820        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10821            cx.propagate();
10822            return;
10823        }
10824
10825        let Some(row_count) = self.visible_row_count() else {
10826            return;
10827        };
10828
10829        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10830
10831        let autoscroll = if action.center_cursor {
10832            Autoscroll::center()
10833        } else {
10834            Autoscroll::fit()
10835        };
10836
10837        let text_layout_details = &self.text_layout_details(window);
10838        self.change_selections(Some(autoscroll), window, cx, |s| {
10839            s.move_with(|map, selection| {
10840                if !selection.is_empty() {
10841                    selection.goal = SelectionGoal::None;
10842                }
10843                let (cursor, goal) = movement::down_by_rows(
10844                    map,
10845                    selection.end,
10846                    row_count,
10847                    selection.goal,
10848                    false,
10849                    text_layout_details,
10850                );
10851                selection.collapse_to(cursor, goal);
10852            });
10853        });
10854    }
10855
10856    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10857        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10858        let text_layout_details = &self.text_layout_details(window);
10859        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10860            s.move_heads_with(|map, head, goal| {
10861                movement::down(map, head, goal, false, text_layout_details)
10862            })
10863        });
10864    }
10865
10866    pub fn context_menu_first(
10867        &mut self,
10868        _: &ContextMenuFirst,
10869        _window: &mut Window,
10870        cx: &mut Context<Self>,
10871    ) {
10872        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10873            context_menu.select_first(self.completion_provider.as_deref(), cx);
10874        }
10875    }
10876
10877    pub fn context_menu_prev(
10878        &mut self,
10879        _: &ContextMenuPrevious,
10880        _window: &mut Window,
10881        cx: &mut Context<Self>,
10882    ) {
10883        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10884            context_menu.select_prev(self.completion_provider.as_deref(), cx);
10885        }
10886    }
10887
10888    pub fn context_menu_next(
10889        &mut self,
10890        _: &ContextMenuNext,
10891        _window: &mut Window,
10892        cx: &mut Context<Self>,
10893    ) {
10894        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10895            context_menu.select_next(self.completion_provider.as_deref(), cx);
10896        }
10897    }
10898
10899    pub fn context_menu_last(
10900        &mut self,
10901        _: &ContextMenuLast,
10902        _window: &mut Window,
10903        cx: &mut Context<Self>,
10904    ) {
10905        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10906            context_menu.select_last(self.completion_provider.as_deref(), cx);
10907        }
10908    }
10909
10910    pub fn move_to_previous_word_start(
10911        &mut self,
10912        _: &MoveToPreviousWordStart,
10913        window: &mut Window,
10914        cx: &mut Context<Self>,
10915    ) {
10916        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10917        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10918            s.move_cursors_with(|map, head, _| {
10919                (
10920                    movement::previous_word_start(map, head),
10921                    SelectionGoal::None,
10922                )
10923            });
10924        })
10925    }
10926
10927    pub fn move_to_previous_subword_start(
10928        &mut self,
10929        _: &MoveToPreviousSubwordStart,
10930        window: &mut Window,
10931        cx: &mut Context<Self>,
10932    ) {
10933        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10934        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10935            s.move_cursors_with(|map, head, _| {
10936                (
10937                    movement::previous_subword_start(map, head),
10938                    SelectionGoal::None,
10939                )
10940            });
10941        })
10942    }
10943
10944    pub fn select_to_previous_word_start(
10945        &mut self,
10946        _: &SelectToPreviousWordStart,
10947        window: &mut Window,
10948        cx: &mut Context<Self>,
10949    ) {
10950        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10951        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10952            s.move_heads_with(|map, head, _| {
10953                (
10954                    movement::previous_word_start(map, head),
10955                    SelectionGoal::None,
10956                )
10957            });
10958        })
10959    }
10960
10961    pub fn select_to_previous_subword_start(
10962        &mut self,
10963        _: &SelectToPreviousSubwordStart,
10964        window: &mut Window,
10965        cx: &mut Context<Self>,
10966    ) {
10967        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10968        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10969            s.move_heads_with(|map, head, _| {
10970                (
10971                    movement::previous_subword_start(map, head),
10972                    SelectionGoal::None,
10973                )
10974            });
10975        })
10976    }
10977
10978    pub fn delete_to_previous_word_start(
10979        &mut self,
10980        action: &DeleteToPreviousWordStart,
10981        window: &mut Window,
10982        cx: &mut Context<Self>,
10983    ) {
10984        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10985        self.transact(window, cx, |this, window, cx| {
10986            this.select_autoclose_pair(window, cx);
10987            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10988                s.move_with(|map, selection| {
10989                    if selection.is_empty() {
10990                        let cursor = if action.ignore_newlines {
10991                            movement::previous_word_start(map, selection.head())
10992                        } else {
10993                            movement::previous_word_start_or_newline(map, selection.head())
10994                        };
10995                        selection.set_head(cursor, SelectionGoal::None);
10996                    }
10997                });
10998            });
10999            this.insert("", window, cx);
11000        });
11001    }
11002
11003    pub fn delete_to_previous_subword_start(
11004        &mut self,
11005        _: &DeleteToPreviousSubwordStart,
11006        window: &mut Window,
11007        cx: &mut Context<Self>,
11008    ) {
11009        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11010        self.transact(window, cx, |this, window, cx| {
11011            this.select_autoclose_pair(window, cx);
11012            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11013                s.move_with(|map, selection| {
11014                    if selection.is_empty() {
11015                        let cursor = movement::previous_subword_start(map, selection.head());
11016                        selection.set_head(cursor, SelectionGoal::None);
11017                    }
11018                });
11019            });
11020            this.insert("", window, cx);
11021        });
11022    }
11023
11024    pub fn move_to_next_word_end(
11025        &mut self,
11026        _: &MoveToNextWordEnd,
11027        window: &mut Window,
11028        cx: &mut Context<Self>,
11029    ) {
11030        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11031        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11032            s.move_cursors_with(|map, head, _| {
11033                (movement::next_word_end(map, head), SelectionGoal::None)
11034            });
11035        })
11036    }
11037
11038    pub fn move_to_next_subword_end(
11039        &mut self,
11040        _: &MoveToNextSubwordEnd,
11041        window: &mut Window,
11042        cx: &mut Context<Self>,
11043    ) {
11044        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11045        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11046            s.move_cursors_with(|map, head, _| {
11047                (movement::next_subword_end(map, head), SelectionGoal::None)
11048            });
11049        })
11050    }
11051
11052    pub fn select_to_next_word_end(
11053        &mut self,
11054        _: &SelectToNextWordEnd,
11055        window: &mut Window,
11056        cx: &mut Context<Self>,
11057    ) {
11058        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11059        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11060            s.move_heads_with(|map, head, _| {
11061                (movement::next_word_end(map, head), SelectionGoal::None)
11062            });
11063        })
11064    }
11065
11066    pub fn select_to_next_subword_end(
11067        &mut self,
11068        _: &SelectToNextSubwordEnd,
11069        window: &mut Window,
11070        cx: &mut Context<Self>,
11071    ) {
11072        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11073        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11074            s.move_heads_with(|map, head, _| {
11075                (movement::next_subword_end(map, head), SelectionGoal::None)
11076            });
11077        })
11078    }
11079
11080    pub fn delete_to_next_word_end(
11081        &mut self,
11082        action: &DeleteToNextWordEnd,
11083        window: &mut Window,
11084        cx: &mut Context<Self>,
11085    ) {
11086        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11087        self.transact(window, cx, |this, window, cx| {
11088            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11089                s.move_with(|map, selection| {
11090                    if selection.is_empty() {
11091                        let cursor = if action.ignore_newlines {
11092                            movement::next_word_end(map, selection.head())
11093                        } else {
11094                            movement::next_word_end_or_newline(map, selection.head())
11095                        };
11096                        selection.set_head(cursor, SelectionGoal::None);
11097                    }
11098                });
11099            });
11100            this.insert("", window, cx);
11101        });
11102    }
11103
11104    pub fn delete_to_next_subword_end(
11105        &mut self,
11106        _: &DeleteToNextSubwordEnd,
11107        window: &mut Window,
11108        cx: &mut Context<Self>,
11109    ) {
11110        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11111        self.transact(window, cx, |this, window, cx| {
11112            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11113                s.move_with(|map, selection| {
11114                    if selection.is_empty() {
11115                        let cursor = movement::next_subword_end(map, selection.head());
11116                        selection.set_head(cursor, SelectionGoal::None);
11117                    }
11118                });
11119            });
11120            this.insert("", window, cx);
11121        });
11122    }
11123
11124    pub fn move_to_beginning_of_line(
11125        &mut self,
11126        action: &MoveToBeginningOfLine,
11127        window: &mut Window,
11128        cx: &mut Context<Self>,
11129    ) {
11130        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11131        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11132            s.move_cursors_with(|map, head, _| {
11133                (
11134                    movement::indented_line_beginning(
11135                        map,
11136                        head,
11137                        action.stop_at_soft_wraps,
11138                        action.stop_at_indent,
11139                    ),
11140                    SelectionGoal::None,
11141                )
11142            });
11143        })
11144    }
11145
11146    pub fn select_to_beginning_of_line(
11147        &mut self,
11148        action: &SelectToBeginningOfLine,
11149        window: &mut Window,
11150        cx: &mut Context<Self>,
11151    ) {
11152        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11153        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11154            s.move_heads_with(|map, head, _| {
11155                (
11156                    movement::indented_line_beginning(
11157                        map,
11158                        head,
11159                        action.stop_at_soft_wraps,
11160                        action.stop_at_indent,
11161                    ),
11162                    SelectionGoal::None,
11163                )
11164            });
11165        });
11166    }
11167
11168    pub fn delete_to_beginning_of_line(
11169        &mut self,
11170        action: &DeleteToBeginningOfLine,
11171        window: &mut Window,
11172        cx: &mut Context<Self>,
11173    ) {
11174        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11175        self.transact(window, cx, |this, window, cx| {
11176            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11177                s.move_with(|_, selection| {
11178                    selection.reversed = true;
11179                });
11180            });
11181
11182            this.select_to_beginning_of_line(
11183                &SelectToBeginningOfLine {
11184                    stop_at_soft_wraps: false,
11185                    stop_at_indent: action.stop_at_indent,
11186                },
11187                window,
11188                cx,
11189            );
11190            this.backspace(&Backspace, window, cx);
11191        });
11192    }
11193
11194    pub fn move_to_end_of_line(
11195        &mut self,
11196        action: &MoveToEndOfLine,
11197        window: &mut Window,
11198        cx: &mut Context<Self>,
11199    ) {
11200        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11201        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11202            s.move_cursors_with(|map, head, _| {
11203                (
11204                    movement::line_end(map, head, action.stop_at_soft_wraps),
11205                    SelectionGoal::None,
11206                )
11207            });
11208        })
11209    }
11210
11211    pub fn select_to_end_of_line(
11212        &mut self,
11213        action: &SelectToEndOfLine,
11214        window: &mut Window,
11215        cx: &mut Context<Self>,
11216    ) {
11217        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11218        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11219            s.move_heads_with(|map, head, _| {
11220                (
11221                    movement::line_end(map, head, action.stop_at_soft_wraps),
11222                    SelectionGoal::None,
11223                )
11224            });
11225        })
11226    }
11227
11228    pub fn delete_to_end_of_line(
11229        &mut self,
11230        _: &DeleteToEndOfLine,
11231        window: &mut Window,
11232        cx: &mut Context<Self>,
11233    ) {
11234        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11235        self.transact(window, cx, |this, window, cx| {
11236            this.select_to_end_of_line(
11237                &SelectToEndOfLine {
11238                    stop_at_soft_wraps: false,
11239                },
11240                window,
11241                cx,
11242            );
11243            this.delete(&Delete, window, cx);
11244        });
11245    }
11246
11247    pub fn cut_to_end_of_line(
11248        &mut self,
11249        _: &CutToEndOfLine,
11250        window: &mut Window,
11251        cx: &mut Context<Self>,
11252    ) {
11253        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11254        self.transact(window, cx, |this, window, cx| {
11255            this.select_to_end_of_line(
11256                &SelectToEndOfLine {
11257                    stop_at_soft_wraps: false,
11258                },
11259                window,
11260                cx,
11261            );
11262            this.cut(&Cut, window, cx);
11263        });
11264    }
11265
11266    pub fn move_to_start_of_paragraph(
11267        &mut self,
11268        _: &MoveToStartOfParagraph,
11269        window: &mut Window,
11270        cx: &mut Context<Self>,
11271    ) {
11272        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11273            cx.propagate();
11274            return;
11275        }
11276        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11277        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11278            s.move_with(|map, selection| {
11279                selection.collapse_to(
11280                    movement::start_of_paragraph(map, selection.head(), 1),
11281                    SelectionGoal::None,
11282                )
11283            });
11284        })
11285    }
11286
11287    pub fn move_to_end_of_paragraph(
11288        &mut self,
11289        _: &MoveToEndOfParagraph,
11290        window: &mut Window,
11291        cx: &mut Context<Self>,
11292    ) {
11293        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11294            cx.propagate();
11295            return;
11296        }
11297        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11298        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11299            s.move_with(|map, selection| {
11300                selection.collapse_to(
11301                    movement::end_of_paragraph(map, selection.head(), 1),
11302                    SelectionGoal::None,
11303                )
11304            });
11305        })
11306    }
11307
11308    pub fn select_to_start_of_paragraph(
11309        &mut self,
11310        _: &SelectToStartOfParagraph,
11311        window: &mut Window,
11312        cx: &mut Context<Self>,
11313    ) {
11314        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11315            cx.propagate();
11316            return;
11317        }
11318        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11319        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11320            s.move_heads_with(|map, head, _| {
11321                (
11322                    movement::start_of_paragraph(map, head, 1),
11323                    SelectionGoal::None,
11324                )
11325            });
11326        })
11327    }
11328
11329    pub fn select_to_end_of_paragraph(
11330        &mut self,
11331        _: &SelectToEndOfParagraph,
11332        window: &mut Window,
11333        cx: &mut Context<Self>,
11334    ) {
11335        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11336            cx.propagate();
11337            return;
11338        }
11339        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11340        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11341            s.move_heads_with(|map, head, _| {
11342                (
11343                    movement::end_of_paragraph(map, head, 1),
11344                    SelectionGoal::None,
11345                )
11346            });
11347        })
11348    }
11349
11350    pub fn move_to_start_of_excerpt(
11351        &mut self,
11352        _: &MoveToStartOfExcerpt,
11353        window: &mut Window,
11354        cx: &mut Context<Self>,
11355    ) {
11356        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11357            cx.propagate();
11358            return;
11359        }
11360        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11361        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11362            s.move_with(|map, selection| {
11363                selection.collapse_to(
11364                    movement::start_of_excerpt(
11365                        map,
11366                        selection.head(),
11367                        workspace::searchable::Direction::Prev,
11368                    ),
11369                    SelectionGoal::None,
11370                )
11371            });
11372        })
11373    }
11374
11375    pub fn move_to_start_of_next_excerpt(
11376        &mut self,
11377        _: &MoveToStartOfNextExcerpt,
11378        window: &mut Window,
11379        cx: &mut Context<Self>,
11380    ) {
11381        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11382            cx.propagate();
11383            return;
11384        }
11385
11386        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11387            s.move_with(|map, selection| {
11388                selection.collapse_to(
11389                    movement::start_of_excerpt(
11390                        map,
11391                        selection.head(),
11392                        workspace::searchable::Direction::Next,
11393                    ),
11394                    SelectionGoal::None,
11395                )
11396            });
11397        })
11398    }
11399
11400    pub fn move_to_end_of_excerpt(
11401        &mut self,
11402        _: &MoveToEndOfExcerpt,
11403        window: &mut Window,
11404        cx: &mut Context<Self>,
11405    ) {
11406        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11407            cx.propagate();
11408            return;
11409        }
11410        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11411        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11412            s.move_with(|map, selection| {
11413                selection.collapse_to(
11414                    movement::end_of_excerpt(
11415                        map,
11416                        selection.head(),
11417                        workspace::searchable::Direction::Next,
11418                    ),
11419                    SelectionGoal::None,
11420                )
11421            });
11422        })
11423    }
11424
11425    pub fn move_to_end_of_previous_excerpt(
11426        &mut self,
11427        _: &MoveToEndOfPreviousExcerpt,
11428        window: &mut Window,
11429        cx: &mut Context<Self>,
11430    ) {
11431        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11432            cx.propagate();
11433            return;
11434        }
11435        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11436        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11437            s.move_with(|map, selection| {
11438                selection.collapse_to(
11439                    movement::end_of_excerpt(
11440                        map,
11441                        selection.head(),
11442                        workspace::searchable::Direction::Prev,
11443                    ),
11444                    SelectionGoal::None,
11445                )
11446            });
11447        })
11448    }
11449
11450    pub fn select_to_start_of_excerpt(
11451        &mut self,
11452        _: &SelectToStartOfExcerpt,
11453        window: &mut Window,
11454        cx: &mut Context<Self>,
11455    ) {
11456        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11457            cx.propagate();
11458            return;
11459        }
11460        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11461        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11462            s.move_heads_with(|map, head, _| {
11463                (
11464                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11465                    SelectionGoal::None,
11466                )
11467            });
11468        })
11469    }
11470
11471    pub fn select_to_start_of_next_excerpt(
11472        &mut self,
11473        _: &SelectToStartOfNextExcerpt,
11474        window: &mut Window,
11475        cx: &mut Context<Self>,
11476    ) {
11477        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11478            cx.propagate();
11479            return;
11480        }
11481        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11482        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11483            s.move_heads_with(|map, head, _| {
11484                (
11485                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11486                    SelectionGoal::None,
11487                )
11488            });
11489        })
11490    }
11491
11492    pub fn select_to_end_of_excerpt(
11493        &mut self,
11494        _: &SelectToEndOfExcerpt,
11495        window: &mut Window,
11496        cx: &mut Context<Self>,
11497    ) {
11498        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11499            cx.propagate();
11500            return;
11501        }
11502        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11503        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11504            s.move_heads_with(|map, head, _| {
11505                (
11506                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11507                    SelectionGoal::None,
11508                )
11509            });
11510        })
11511    }
11512
11513    pub fn select_to_end_of_previous_excerpt(
11514        &mut self,
11515        _: &SelectToEndOfPreviousExcerpt,
11516        window: &mut Window,
11517        cx: &mut Context<Self>,
11518    ) {
11519        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11520            cx.propagate();
11521            return;
11522        }
11523        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11524        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11525            s.move_heads_with(|map, head, _| {
11526                (
11527                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11528                    SelectionGoal::None,
11529                )
11530            });
11531        })
11532    }
11533
11534    pub fn move_to_beginning(
11535        &mut self,
11536        _: &MoveToBeginning,
11537        window: &mut Window,
11538        cx: &mut Context<Self>,
11539    ) {
11540        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11541            cx.propagate();
11542            return;
11543        }
11544        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11545        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11546            s.select_ranges(vec![0..0]);
11547        });
11548    }
11549
11550    pub fn select_to_beginning(
11551        &mut self,
11552        _: &SelectToBeginning,
11553        window: &mut Window,
11554        cx: &mut Context<Self>,
11555    ) {
11556        let mut selection = self.selections.last::<Point>(cx);
11557        selection.set_head(Point::zero(), SelectionGoal::None);
11558        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11559        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11560            s.select(vec![selection]);
11561        });
11562    }
11563
11564    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11565        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11566            cx.propagate();
11567            return;
11568        }
11569        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11570        let cursor = self.buffer.read(cx).read(cx).len();
11571        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11572            s.select_ranges(vec![cursor..cursor])
11573        });
11574    }
11575
11576    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11577        self.nav_history = nav_history;
11578    }
11579
11580    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11581        self.nav_history.as_ref()
11582    }
11583
11584    pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11585        self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11586    }
11587
11588    fn push_to_nav_history(
11589        &mut self,
11590        cursor_anchor: Anchor,
11591        new_position: Option<Point>,
11592        is_deactivate: bool,
11593        cx: &mut Context<Self>,
11594    ) {
11595        if let Some(nav_history) = self.nav_history.as_mut() {
11596            let buffer = self.buffer.read(cx).read(cx);
11597            let cursor_position = cursor_anchor.to_point(&buffer);
11598            let scroll_state = self.scroll_manager.anchor();
11599            let scroll_top_row = scroll_state.top_row(&buffer);
11600            drop(buffer);
11601
11602            if let Some(new_position) = new_position {
11603                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11604                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11605                    return;
11606                }
11607            }
11608
11609            nav_history.push(
11610                Some(NavigationData {
11611                    cursor_anchor,
11612                    cursor_position,
11613                    scroll_anchor: scroll_state,
11614                    scroll_top_row,
11615                }),
11616                cx,
11617            );
11618            cx.emit(EditorEvent::PushedToNavHistory {
11619                anchor: cursor_anchor,
11620                is_deactivate,
11621            })
11622        }
11623    }
11624
11625    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11626        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11627        let buffer = self.buffer.read(cx).snapshot(cx);
11628        let mut selection = self.selections.first::<usize>(cx);
11629        selection.set_head(buffer.len(), SelectionGoal::None);
11630        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11631            s.select(vec![selection]);
11632        });
11633    }
11634
11635    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11636        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11637        let end = self.buffer.read(cx).read(cx).len();
11638        self.change_selections(None, window, cx, |s| {
11639            s.select_ranges(vec![0..end]);
11640        });
11641    }
11642
11643    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11644        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11645        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11646        let mut selections = self.selections.all::<Point>(cx);
11647        let max_point = display_map.buffer_snapshot.max_point();
11648        for selection in &mut selections {
11649            let rows = selection.spanned_rows(true, &display_map);
11650            selection.start = Point::new(rows.start.0, 0);
11651            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11652            selection.reversed = false;
11653        }
11654        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11655            s.select(selections);
11656        });
11657    }
11658
11659    pub fn split_selection_into_lines(
11660        &mut self,
11661        _: &SplitSelectionIntoLines,
11662        window: &mut Window,
11663        cx: &mut Context<Self>,
11664    ) {
11665        let selections = self
11666            .selections
11667            .all::<Point>(cx)
11668            .into_iter()
11669            .map(|selection| selection.start..selection.end)
11670            .collect::<Vec<_>>();
11671        self.unfold_ranges(&selections, true, true, cx);
11672
11673        let mut new_selection_ranges = Vec::new();
11674        {
11675            let buffer = self.buffer.read(cx).read(cx);
11676            for selection in selections {
11677                for row in selection.start.row..selection.end.row {
11678                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11679                    new_selection_ranges.push(cursor..cursor);
11680                }
11681
11682                let is_multiline_selection = selection.start.row != selection.end.row;
11683                // Don't insert last one if it's a multi-line selection ending at the start of a line,
11684                // so this action feels more ergonomic when paired with other selection operations
11685                let should_skip_last = is_multiline_selection && selection.end.column == 0;
11686                if !should_skip_last {
11687                    new_selection_ranges.push(selection.end..selection.end);
11688                }
11689            }
11690        }
11691        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11692            s.select_ranges(new_selection_ranges);
11693        });
11694    }
11695
11696    pub fn add_selection_above(
11697        &mut self,
11698        _: &AddSelectionAbove,
11699        window: &mut Window,
11700        cx: &mut Context<Self>,
11701    ) {
11702        self.add_selection(true, window, cx);
11703    }
11704
11705    pub fn add_selection_below(
11706        &mut self,
11707        _: &AddSelectionBelow,
11708        window: &mut Window,
11709        cx: &mut Context<Self>,
11710    ) {
11711        self.add_selection(false, window, cx);
11712    }
11713
11714    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11715        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11716
11717        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11718        let mut selections = self.selections.all::<Point>(cx);
11719        let text_layout_details = self.text_layout_details(window);
11720        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11721            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11722            let range = oldest_selection.display_range(&display_map).sorted();
11723
11724            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11725            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11726            let positions = start_x.min(end_x)..start_x.max(end_x);
11727
11728            selections.clear();
11729            let mut stack = Vec::new();
11730            for row in range.start.row().0..=range.end.row().0 {
11731                if let Some(selection) = self.selections.build_columnar_selection(
11732                    &display_map,
11733                    DisplayRow(row),
11734                    &positions,
11735                    oldest_selection.reversed,
11736                    &text_layout_details,
11737                ) {
11738                    stack.push(selection.id);
11739                    selections.push(selection);
11740                }
11741            }
11742
11743            if above {
11744                stack.reverse();
11745            }
11746
11747            AddSelectionsState { above, stack }
11748        });
11749
11750        let last_added_selection = *state.stack.last().unwrap();
11751        let mut new_selections = Vec::new();
11752        if above == state.above {
11753            let end_row = if above {
11754                DisplayRow(0)
11755            } else {
11756                display_map.max_point().row()
11757            };
11758
11759            'outer: for selection in selections {
11760                if selection.id == last_added_selection {
11761                    let range = selection.display_range(&display_map).sorted();
11762                    debug_assert_eq!(range.start.row(), range.end.row());
11763                    let mut row = range.start.row();
11764                    let positions =
11765                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11766                            px(start)..px(end)
11767                        } else {
11768                            let start_x =
11769                                display_map.x_for_display_point(range.start, &text_layout_details);
11770                            let end_x =
11771                                display_map.x_for_display_point(range.end, &text_layout_details);
11772                            start_x.min(end_x)..start_x.max(end_x)
11773                        };
11774
11775                    while row != end_row {
11776                        if above {
11777                            row.0 -= 1;
11778                        } else {
11779                            row.0 += 1;
11780                        }
11781
11782                        if let Some(new_selection) = self.selections.build_columnar_selection(
11783                            &display_map,
11784                            row,
11785                            &positions,
11786                            selection.reversed,
11787                            &text_layout_details,
11788                        ) {
11789                            state.stack.push(new_selection.id);
11790                            if above {
11791                                new_selections.push(new_selection);
11792                                new_selections.push(selection);
11793                            } else {
11794                                new_selections.push(selection);
11795                                new_selections.push(new_selection);
11796                            }
11797
11798                            continue 'outer;
11799                        }
11800                    }
11801                }
11802
11803                new_selections.push(selection);
11804            }
11805        } else {
11806            new_selections = selections;
11807            new_selections.retain(|s| s.id != last_added_selection);
11808            state.stack.pop();
11809        }
11810
11811        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11812            s.select(new_selections);
11813        });
11814        if state.stack.len() > 1 {
11815            self.add_selections_state = Some(state);
11816        }
11817    }
11818
11819    pub fn select_next_match_internal(
11820        &mut self,
11821        display_map: &DisplaySnapshot,
11822        replace_newest: bool,
11823        autoscroll: Option<Autoscroll>,
11824        window: &mut Window,
11825        cx: &mut Context<Self>,
11826    ) -> Result<()> {
11827        fn select_next_match_ranges(
11828            this: &mut Editor,
11829            range: Range<usize>,
11830            replace_newest: bool,
11831            auto_scroll: Option<Autoscroll>,
11832            window: &mut Window,
11833            cx: &mut Context<Editor>,
11834        ) {
11835            this.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
11836            this.change_selections(auto_scroll, window, cx, |s| {
11837                if replace_newest {
11838                    s.delete(s.newest_anchor().id);
11839                }
11840                s.insert_range(range.clone());
11841            });
11842        }
11843
11844        let buffer = &display_map.buffer_snapshot;
11845        let mut selections = self.selections.all::<usize>(cx);
11846        if let Some(mut select_next_state) = self.select_next_state.take() {
11847            let query = &select_next_state.query;
11848            if !select_next_state.done {
11849                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11850                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11851                let mut next_selected_range = None;
11852
11853                let bytes_after_last_selection =
11854                    buffer.bytes_in_range(last_selection.end..buffer.len());
11855                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11856                let query_matches = query
11857                    .stream_find_iter(bytes_after_last_selection)
11858                    .map(|result| (last_selection.end, result))
11859                    .chain(
11860                        query
11861                            .stream_find_iter(bytes_before_first_selection)
11862                            .map(|result| (0, result)),
11863                    );
11864
11865                for (start_offset, query_match) in query_matches {
11866                    let query_match = query_match.unwrap(); // can only fail due to I/O
11867                    let offset_range =
11868                        start_offset + query_match.start()..start_offset + query_match.end();
11869                    let display_range = offset_range.start.to_display_point(display_map)
11870                        ..offset_range.end.to_display_point(display_map);
11871
11872                    if !select_next_state.wordwise
11873                        || (!movement::is_inside_word(display_map, display_range.start)
11874                            && !movement::is_inside_word(display_map, display_range.end))
11875                    {
11876                        // TODO: This is n^2, because we might check all the selections
11877                        if !selections
11878                            .iter()
11879                            .any(|selection| selection.range().overlaps(&offset_range))
11880                        {
11881                            next_selected_range = Some(offset_range);
11882                            break;
11883                        }
11884                    }
11885                }
11886
11887                if let Some(next_selected_range) = next_selected_range {
11888                    select_next_match_ranges(
11889                        self,
11890                        next_selected_range,
11891                        replace_newest,
11892                        autoscroll,
11893                        window,
11894                        cx,
11895                    );
11896                } else {
11897                    select_next_state.done = true;
11898                }
11899            }
11900
11901            self.select_next_state = Some(select_next_state);
11902        } else {
11903            let mut only_carets = true;
11904            let mut same_text_selected = true;
11905            let mut selected_text = None;
11906
11907            let mut selections_iter = selections.iter().peekable();
11908            while let Some(selection) = selections_iter.next() {
11909                if selection.start != selection.end {
11910                    only_carets = false;
11911                }
11912
11913                if same_text_selected {
11914                    if selected_text.is_none() {
11915                        selected_text =
11916                            Some(buffer.text_for_range(selection.range()).collect::<String>());
11917                    }
11918
11919                    if let Some(next_selection) = selections_iter.peek() {
11920                        if next_selection.range().len() == selection.range().len() {
11921                            let next_selected_text = buffer
11922                                .text_for_range(next_selection.range())
11923                                .collect::<String>();
11924                            if Some(next_selected_text) != selected_text {
11925                                same_text_selected = false;
11926                                selected_text = None;
11927                            }
11928                        } else {
11929                            same_text_selected = false;
11930                            selected_text = None;
11931                        }
11932                    }
11933                }
11934            }
11935
11936            if only_carets {
11937                for selection in &mut selections {
11938                    let word_range = movement::surrounding_word(
11939                        display_map,
11940                        selection.start.to_display_point(display_map),
11941                    );
11942                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
11943                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
11944                    selection.goal = SelectionGoal::None;
11945                    selection.reversed = false;
11946                    select_next_match_ranges(
11947                        self,
11948                        selection.start..selection.end,
11949                        replace_newest,
11950                        autoscroll,
11951                        window,
11952                        cx,
11953                    );
11954                }
11955
11956                if selections.len() == 1 {
11957                    let selection = selections
11958                        .last()
11959                        .expect("ensured that there's only one selection");
11960                    let query = buffer
11961                        .text_for_range(selection.start..selection.end)
11962                        .collect::<String>();
11963                    let is_empty = query.is_empty();
11964                    let select_state = SelectNextState {
11965                        query: AhoCorasick::new(&[query])?,
11966                        wordwise: true,
11967                        done: is_empty,
11968                    };
11969                    self.select_next_state = Some(select_state);
11970                } else {
11971                    self.select_next_state = None;
11972                }
11973            } else if let Some(selected_text) = selected_text {
11974                self.select_next_state = Some(SelectNextState {
11975                    query: AhoCorasick::new(&[selected_text])?,
11976                    wordwise: false,
11977                    done: false,
11978                });
11979                self.select_next_match_internal(
11980                    display_map,
11981                    replace_newest,
11982                    autoscroll,
11983                    window,
11984                    cx,
11985                )?;
11986            }
11987        }
11988        Ok(())
11989    }
11990
11991    pub fn select_all_matches(
11992        &mut self,
11993        _action: &SelectAllMatches,
11994        window: &mut Window,
11995        cx: &mut Context<Self>,
11996    ) -> Result<()> {
11997        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11998
11999        self.push_to_selection_history();
12000        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12001
12002        self.select_next_match_internal(&display_map, false, None, window, cx)?;
12003        let Some(select_next_state) = self.select_next_state.as_mut() else {
12004            return Ok(());
12005        };
12006        if select_next_state.done {
12007            return Ok(());
12008        }
12009
12010        let mut new_selections = Vec::new();
12011
12012        let reversed = self.selections.oldest::<usize>(cx).reversed;
12013        let buffer = &display_map.buffer_snapshot;
12014        let query_matches = select_next_state
12015            .query
12016            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
12017
12018        for query_match in query_matches.into_iter() {
12019            let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
12020            let offset_range = if reversed {
12021                query_match.end()..query_match.start()
12022            } else {
12023                query_match.start()..query_match.end()
12024            };
12025            let display_range = offset_range.start.to_display_point(&display_map)
12026                ..offset_range.end.to_display_point(&display_map);
12027
12028            if !select_next_state.wordwise
12029                || (!movement::is_inside_word(&display_map, display_range.start)
12030                    && !movement::is_inside_word(&display_map, display_range.end))
12031            {
12032                new_selections.push(offset_range.start..offset_range.end);
12033            }
12034        }
12035
12036        select_next_state.done = true;
12037        self.unfold_ranges(&new_selections.clone(), false, false, cx);
12038        self.change_selections(None, window, cx, |selections| {
12039            selections.select_ranges(new_selections)
12040        });
12041
12042        Ok(())
12043    }
12044
12045    pub fn select_next(
12046        &mut self,
12047        action: &SelectNext,
12048        window: &mut Window,
12049        cx: &mut Context<Self>,
12050    ) -> Result<()> {
12051        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12052        self.push_to_selection_history();
12053        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12054        self.select_next_match_internal(
12055            &display_map,
12056            action.replace_newest,
12057            Some(Autoscroll::newest()),
12058            window,
12059            cx,
12060        )?;
12061        Ok(())
12062    }
12063
12064    pub fn select_previous(
12065        &mut self,
12066        action: &SelectPrevious,
12067        window: &mut Window,
12068        cx: &mut Context<Self>,
12069    ) -> Result<()> {
12070        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12071        self.push_to_selection_history();
12072        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12073        let buffer = &display_map.buffer_snapshot;
12074        let mut selections = self.selections.all::<usize>(cx);
12075        if let Some(mut select_prev_state) = self.select_prev_state.take() {
12076            let query = &select_prev_state.query;
12077            if !select_prev_state.done {
12078                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12079                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12080                let mut next_selected_range = None;
12081                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
12082                let bytes_before_last_selection =
12083                    buffer.reversed_bytes_in_range(0..last_selection.start);
12084                let bytes_after_first_selection =
12085                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
12086                let query_matches = query
12087                    .stream_find_iter(bytes_before_last_selection)
12088                    .map(|result| (last_selection.start, result))
12089                    .chain(
12090                        query
12091                            .stream_find_iter(bytes_after_first_selection)
12092                            .map(|result| (buffer.len(), result)),
12093                    );
12094                for (end_offset, query_match) in query_matches {
12095                    let query_match = query_match.unwrap(); // can only fail due to I/O
12096                    let offset_range =
12097                        end_offset - query_match.end()..end_offset - query_match.start();
12098                    let display_range = offset_range.start.to_display_point(&display_map)
12099                        ..offset_range.end.to_display_point(&display_map);
12100
12101                    if !select_prev_state.wordwise
12102                        || (!movement::is_inside_word(&display_map, display_range.start)
12103                            && !movement::is_inside_word(&display_map, display_range.end))
12104                    {
12105                        next_selected_range = Some(offset_range);
12106                        break;
12107                    }
12108                }
12109
12110                if let Some(next_selected_range) = next_selected_range {
12111                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
12112                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12113                        if action.replace_newest {
12114                            s.delete(s.newest_anchor().id);
12115                        }
12116                        s.insert_range(next_selected_range);
12117                    });
12118                } else {
12119                    select_prev_state.done = true;
12120                }
12121            }
12122
12123            self.select_prev_state = Some(select_prev_state);
12124        } else {
12125            let mut only_carets = true;
12126            let mut same_text_selected = true;
12127            let mut selected_text = None;
12128
12129            let mut selections_iter = selections.iter().peekable();
12130            while let Some(selection) = selections_iter.next() {
12131                if selection.start != selection.end {
12132                    only_carets = false;
12133                }
12134
12135                if same_text_selected {
12136                    if selected_text.is_none() {
12137                        selected_text =
12138                            Some(buffer.text_for_range(selection.range()).collect::<String>());
12139                    }
12140
12141                    if let Some(next_selection) = selections_iter.peek() {
12142                        if next_selection.range().len() == selection.range().len() {
12143                            let next_selected_text = buffer
12144                                .text_for_range(next_selection.range())
12145                                .collect::<String>();
12146                            if Some(next_selected_text) != selected_text {
12147                                same_text_selected = false;
12148                                selected_text = None;
12149                            }
12150                        } else {
12151                            same_text_selected = false;
12152                            selected_text = None;
12153                        }
12154                    }
12155                }
12156            }
12157
12158            if only_carets {
12159                for selection in &mut selections {
12160                    let word_range = movement::surrounding_word(
12161                        &display_map,
12162                        selection.start.to_display_point(&display_map),
12163                    );
12164                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12165                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12166                    selection.goal = SelectionGoal::None;
12167                    selection.reversed = false;
12168                }
12169                if selections.len() == 1 {
12170                    let selection = selections
12171                        .last()
12172                        .expect("ensured that there's only one selection");
12173                    let query = buffer
12174                        .text_for_range(selection.start..selection.end)
12175                        .collect::<String>();
12176                    let is_empty = query.is_empty();
12177                    let select_state = SelectNextState {
12178                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12179                        wordwise: true,
12180                        done: is_empty,
12181                    };
12182                    self.select_prev_state = Some(select_state);
12183                } else {
12184                    self.select_prev_state = None;
12185                }
12186
12187                self.unfold_ranges(
12188                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
12189                    false,
12190                    true,
12191                    cx,
12192                );
12193                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12194                    s.select(selections);
12195                });
12196            } else if let Some(selected_text) = selected_text {
12197                self.select_prev_state = Some(SelectNextState {
12198                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12199                    wordwise: false,
12200                    done: false,
12201                });
12202                self.select_previous(action, window, cx)?;
12203            }
12204        }
12205        Ok(())
12206    }
12207
12208    pub fn find_next_match(
12209        &mut self,
12210        _: &FindNextMatch,
12211        window: &mut Window,
12212        cx: &mut Context<Self>,
12213    ) -> Result<()> {
12214        let selections = self.selections.disjoint_anchors();
12215        match selections.first() {
12216            Some(first) if selections.len() >= 2 => {
12217                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12218                    s.select_ranges([first.range()]);
12219                });
12220            }
12221            _ => self.select_next(
12222                &SelectNext {
12223                    replace_newest: true,
12224                },
12225                window,
12226                cx,
12227            )?,
12228        }
12229        Ok(())
12230    }
12231
12232    pub fn find_previous_match(
12233        &mut self,
12234        _: &FindPreviousMatch,
12235        window: &mut Window,
12236        cx: &mut Context<Self>,
12237    ) -> Result<()> {
12238        let selections = self.selections.disjoint_anchors();
12239        match selections.last() {
12240            Some(last) if selections.len() >= 2 => {
12241                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12242                    s.select_ranges([last.range()]);
12243                });
12244            }
12245            _ => self.select_previous(
12246                &SelectPrevious {
12247                    replace_newest: true,
12248                },
12249                window,
12250                cx,
12251            )?,
12252        }
12253        Ok(())
12254    }
12255
12256    pub fn toggle_comments(
12257        &mut self,
12258        action: &ToggleComments,
12259        window: &mut Window,
12260        cx: &mut Context<Self>,
12261    ) {
12262        if self.read_only(cx) {
12263            return;
12264        }
12265        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12266        let text_layout_details = &self.text_layout_details(window);
12267        self.transact(window, cx, |this, window, cx| {
12268            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12269            let mut edits = Vec::new();
12270            let mut selection_edit_ranges = Vec::new();
12271            let mut last_toggled_row = None;
12272            let snapshot = this.buffer.read(cx).read(cx);
12273            let empty_str: Arc<str> = Arc::default();
12274            let mut suffixes_inserted = Vec::new();
12275            let ignore_indent = action.ignore_indent;
12276
12277            fn comment_prefix_range(
12278                snapshot: &MultiBufferSnapshot,
12279                row: MultiBufferRow,
12280                comment_prefix: &str,
12281                comment_prefix_whitespace: &str,
12282                ignore_indent: bool,
12283            ) -> Range<Point> {
12284                let indent_size = if ignore_indent {
12285                    0
12286                } else {
12287                    snapshot.indent_size_for_line(row).len
12288                };
12289
12290                let start = Point::new(row.0, indent_size);
12291
12292                let mut line_bytes = snapshot
12293                    .bytes_in_range(start..snapshot.max_point())
12294                    .flatten()
12295                    .copied();
12296
12297                // If this line currently begins with the line comment prefix, then record
12298                // the range containing the prefix.
12299                if line_bytes
12300                    .by_ref()
12301                    .take(comment_prefix.len())
12302                    .eq(comment_prefix.bytes())
12303                {
12304                    // Include any whitespace that matches the comment prefix.
12305                    let matching_whitespace_len = line_bytes
12306                        .zip(comment_prefix_whitespace.bytes())
12307                        .take_while(|(a, b)| a == b)
12308                        .count() as u32;
12309                    let end = Point::new(
12310                        start.row,
12311                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12312                    );
12313                    start..end
12314                } else {
12315                    start..start
12316                }
12317            }
12318
12319            fn comment_suffix_range(
12320                snapshot: &MultiBufferSnapshot,
12321                row: MultiBufferRow,
12322                comment_suffix: &str,
12323                comment_suffix_has_leading_space: bool,
12324            ) -> Range<Point> {
12325                let end = Point::new(row.0, snapshot.line_len(row));
12326                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12327
12328                let mut line_end_bytes = snapshot
12329                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12330                    .flatten()
12331                    .copied();
12332
12333                let leading_space_len = if suffix_start_column > 0
12334                    && line_end_bytes.next() == Some(b' ')
12335                    && comment_suffix_has_leading_space
12336                {
12337                    1
12338                } else {
12339                    0
12340                };
12341
12342                // If this line currently begins with the line comment prefix, then record
12343                // the range containing the prefix.
12344                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12345                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
12346                    start..end
12347                } else {
12348                    end..end
12349                }
12350            }
12351
12352            // TODO: Handle selections that cross excerpts
12353            for selection in &mut selections {
12354                let start_column = snapshot
12355                    .indent_size_for_line(MultiBufferRow(selection.start.row))
12356                    .len;
12357                let language = if let Some(language) =
12358                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12359                {
12360                    language
12361                } else {
12362                    continue;
12363                };
12364
12365                selection_edit_ranges.clear();
12366
12367                // If multiple selections contain a given row, avoid processing that
12368                // row more than once.
12369                let mut start_row = MultiBufferRow(selection.start.row);
12370                if last_toggled_row == Some(start_row) {
12371                    start_row = start_row.next_row();
12372                }
12373                let end_row =
12374                    if selection.end.row > selection.start.row && selection.end.column == 0 {
12375                        MultiBufferRow(selection.end.row - 1)
12376                    } else {
12377                        MultiBufferRow(selection.end.row)
12378                    };
12379                last_toggled_row = Some(end_row);
12380
12381                if start_row > end_row {
12382                    continue;
12383                }
12384
12385                // If the language has line comments, toggle those.
12386                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12387
12388                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12389                if ignore_indent {
12390                    full_comment_prefixes = full_comment_prefixes
12391                        .into_iter()
12392                        .map(|s| Arc::from(s.trim_end()))
12393                        .collect();
12394                }
12395
12396                if !full_comment_prefixes.is_empty() {
12397                    let first_prefix = full_comment_prefixes
12398                        .first()
12399                        .expect("prefixes is non-empty");
12400                    let prefix_trimmed_lengths = full_comment_prefixes
12401                        .iter()
12402                        .map(|p| p.trim_end_matches(' ').len())
12403                        .collect::<SmallVec<[usize; 4]>>();
12404
12405                    let mut all_selection_lines_are_comments = true;
12406
12407                    for row in start_row.0..=end_row.0 {
12408                        let row = MultiBufferRow(row);
12409                        if start_row < end_row && snapshot.is_line_blank(row) {
12410                            continue;
12411                        }
12412
12413                        let prefix_range = full_comment_prefixes
12414                            .iter()
12415                            .zip(prefix_trimmed_lengths.iter().copied())
12416                            .map(|(prefix, trimmed_prefix_len)| {
12417                                comment_prefix_range(
12418                                    snapshot.deref(),
12419                                    row,
12420                                    &prefix[..trimmed_prefix_len],
12421                                    &prefix[trimmed_prefix_len..],
12422                                    ignore_indent,
12423                                )
12424                            })
12425                            .max_by_key(|range| range.end.column - range.start.column)
12426                            .expect("prefixes is non-empty");
12427
12428                        if prefix_range.is_empty() {
12429                            all_selection_lines_are_comments = false;
12430                        }
12431
12432                        selection_edit_ranges.push(prefix_range);
12433                    }
12434
12435                    if all_selection_lines_are_comments {
12436                        edits.extend(
12437                            selection_edit_ranges
12438                                .iter()
12439                                .cloned()
12440                                .map(|range| (range, empty_str.clone())),
12441                        );
12442                    } else {
12443                        let min_column = selection_edit_ranges
12444                            .iter()
12445                            .map(|range| range.start.column)
12446                            .min()
12447                            .unwrap_or(0);
12448                        edits.extend(selection_edit_ranges.iter().map(|range| {
12449                            let position = Point::new(range.start.row, min_column);
12450                            (position..position, first_prefix.clone())
12451                        }));
12452                    }
12453                } else if let Some((full_comment_prefix, comment_suffix)) =
12454                    language.block_comment_delimiters()
12455                {
12456                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12457                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12458                    let prefix_range = comment_prefix_range(
12459                        snapshot.deref(),
12460                        start_row,
12461                        comment_prefix,
12462                        comment_prefix_whitespace,
12463                        ignore_indent,
12464                    );
12465                    let suffix_range = comment_suffix_range(
12466                        snapshot.deref(),
12467                        end_row,
12468                        comment_suffix.trim_start_matches(' '),
12469                        comment_suffix.starts_with(' '),
12470                    );
12471
12472                    if prefix_range.is_empty() || suffix_range.is_empty() {
12473                        edits.push((
12474                            prefix_range.start..prefix_range.start,
12475                            full_comment_prefix.clone(),
12476                        ));
12477                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12478                        suffixes_inserted.push((end_row, comment_suffix.len()));
12479                    } else {
12480                        edits.push((prefix_range, empty_str.clone()));
12481                        edits.push((suffix_range, empty_str.clone()));
12482                    }
12483                } else {
12484                    continue;
12485                }
12486            }
12487
12488            drop(snapshot);
12489            this.buffer.update(cx, |buffer, cx| {
12490                buffer.edit(edits, None, cx);
12491            });
12492
12493            // Adjust selections so that they end before any comment suffixes that
12494            // were inserted.
12495            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12496            let mut selections = this.selections.all::<Point>(cx);
12497            let snapshot = this.buffer.read(cx).read(cx);
12498            for selection in &mut selections {
12499                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12500                    match row.cmp(&MultiBufferRow(selection.end.row)) {
12501                        Ordering::Less => {
12502                            suffixes_inserted.next();
12503                            continue;
12504                        }
12505                        Ordering::Greater => break,
12506                        Ordering::Equal => {
12507                            if selection.end.column == snapshot.line_len(row) {
12508                                if selection.is_empty() {
12509                                    selection.start.column -= suffix_len as u32;
12510                                }
12511                                selection.end.column -= suffix_len as u32;
12512                            }
12513                            break;
12514                        }
12515                    }
12516                }
12517            }
12518
12519            drop(snapshot);
12520            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12521                s.select(selections)
12522            });
12523
12524            let selections = this.selections.all::<Point>(cx);
12525            let selections_on_single_row = selections.windows(2).all(|selections| {
12526                selections[0].start.row == selections[1].start.row
12527                    && selections[0].end.row == selections[1].end.row
12528                    && selections[0].start.row == selections[0].end.row
12529            });
12530            let selections_selecting = selections
12531                .iter()
12532                .any(|selection| selection.start != selection.end);
12533            let advance_downwards = action.advance_downwards
12534                && selections_on_single_row
12535                && !selections_selecting
12536                && !matches!(this.mode, EditorMode::SingleLine { .. });
12537
12538            if advance_downwards {
12539                let snapshot = this.buffer.read(cx).snapshot(cx);
12540
12541                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12542                    s.move_cursors_with(|display_snapshot, display_point, _| {
12543                        let mut point = display_point.to_point(display_snapshot);
12544                        point.row += 1;
12545                        point = snapshot.clip_point(point, Bias::Left);
12546                        let display_point = point.to_display_point(display_snapshot);
12547                        let goal = SelectionGoal::HorizontalPosition(
12548                            display_snapshot
12549                                .x_for_display_point(display_point, text_layout_details)
12550                                .into(),
12551                        );
12552                        (display_point, goal)
12553                    })
12554                });
12555            }
12556        });
12557    }
12558
12559    pub fn select_enclosing_symbol(
12560        &mut self,
12561        _: &SelectEnclosingSymbol,
12562        window: &mut Window,
12563        cx: &mut Context<Self>,
12564    ) {
12565        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12566
12567        let buffer = self.buffer.read(cx).snapshot(cx);
12568        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12569
12570        fn update_selection(
12571            selection: &Selection<usize>,
12572            buffer_snap: &MultiBufferSnapshot,
12573        ) -> Option<Selection<usize>> {
12574            let cursor = selection.head();
12575            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12576            for symbol in symbols.iter().rev() {
12577                let start = symbol.range.start.to_offset(buffer_snap);
12578                let end = symbol.range.end.to_offset(buffer_snap);
12579                let new_range = start..end;
12580                if start < selection.start || end > selection.end {
12581                    return Some(Selection {
12582                        id: selection.id,
12583                        start: new_range.start,
12584                        end: new_range.end,
12585                        goal: SelectionGoal::None,
12586                        reversed: selection.reversed,
12587                    });
12588                }
12589            }
12590            None
12591        }
12592
12593        let mut selected_larger_symbol = false;
12594        let new_selections = old_selections
12595            .iter()
12596            .map(|selection| match update_selection(selection, &buffer) {
12597                Some(new_selection) => {
12598                    if new_selection.range() != selection.range() {
12599                        selected_larger_symbol = true;
12600                    }
12601                    new_selection
12602                }
12603                None => selection.clone(),
12604            })
12605            .collect::<Vec<_>>();
12606
12607        if selected_larger_symbol {
12608            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12609                s.select(new_selections);
12610            });
12611        }
12612    }
12613
12614    pub fn select_larger_syntax_node(
12615        &mut self,
12616        _: &SelectLargerSyntaxNode,
12617        window: &mut Window,
12618        cx: &mut Context<Self>,
12619    ) {
12620        let Some(visible_row_count) = self.visible_row_count() else {
12621            return;
12622        };
12623        let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12624        if old_selections.is_empty() {
12625            return;
12626        }
12627
12628        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12629
12630        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12631        let buffer = self.buffer.read(cx).snapshot(cx);
12632
12633        let mut selected_larger_node = false;
12634        let mut new_selections = old_selections
12635            .iter()
12636            .map(|selection| {
12637                let old_range = selection.start..selection.end;
12638
12639                if let Some((node, _)) = buffer.syntax_ancestor(old_range.clone()) {
12640                    // manually select word at selection
12641                    if ["string_content", "inline"].contains(&node.kind()) {
12642                        let word_range = {
12643                            let display_point = buffer
12644                                .offset_to_point(old_range.start)
12645                                .to_display_point(&display_map);
12646                            let Range { start, end } =
12647                                movement::surrounding_word(&display_map, display_point);
12648                            start.to_point(&display_map).to_offset(&buffer)
12649                                ..end.to_point(&display_map).to_offset(&buffer)
12650                        };
12651                        // ignore if word is already selected
12652                        if !word_range.is_empty() && old_range != word_range {
12653                            let last_word_range = {
12654                                let display_point = buffer
12655                                    .offset_to_point(old_range.end)
12656                                    .to_display_point(&display_map);
12657                                let Range { start, end } =
12658                                    movement::surrounding_word(&display_map, display_point);
12659                                start.to_point(&display_map).to_offset(&buffer)
12660                                    ..end.to_point(&display_map).to_offset(&buffer)
12661                            };
12662                            // only select word if start and end point belongs to same word
12663                            if word_range == last_word_range {
12664                                selected_larger_node = true;
12665                                return Selection {
12666                                    id: selection.id,
12667                                    start: word_range.start,
12668                                    end: word_range.end,
12669                                    goal: SelectionGoal::None,
12670                                    reversed: selection.reversed,
12671                                };
12672                            }
12673                        }
12674                    }
12675                }
12676
12677                let mut new_range = old_range.clone();
12678                let mut new_node = None;
12679                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
12680                {
12681                    new_node = Some(node);
12682                    new_range = match containing_range {
12683                        MultiOrSingleBufferOffsetRange::Single(_) => break,
12684                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
12685                    };
12686                    if !display_map.intersects_fold(new_range.start)
12687                        && !display_map.intersects_fold(new_range.end)
12688                    {
12689                        break;
12690                    }
12691                }
12692
12693                if let Some(node) = new_node {
12694                    // Log the ancestor, to support using this action as a way to explore TreeSitter
12695                    // nodes. Parent and grandparent are also logged because this operation will not
12696                    // visit nodes that have the same range as their parent.
12697                    log::info!("Node: {node:?}");
12698                    let parent = node.parent();
12699                    log::info!("Parent: {parent:?}");
12700                    let grandparent = parent.and_then(|x| x.parent());
12701                    log::info!("Grandparent: {grandparent:?}");
12702                }
12703
12704                selected_larger_node |= new_range != old_range;
12705                Selection {
12706                    id: selection.id,
12707                    start: new_range.start,
12708                    end: new_range.end,
12709                    goal: SelectionGoal::None,
12710                    reversed: selection.reversed,
12711                }
12712            })
12713            .collect::<Vec<_>>();
12714
12715        if !selected_larger_node {
12716            return; // don't put this call in the history
12717        }
12718
12719        // scroll based on transformation done to the last selection created by the user
12720        let (last_old, last_new) = old_selections
12721            .last()
12722            .zip(new_selections.last().cloned())
12723            .expect("old_selections isn't empty");
12724
12725        // revert selection
12726        let is_selection_reversed = {
12727            let should_newest_selection_be_reversed = last_old.start != last_new.start;
12728            new_selections.last_mut().expect("checked above").reversed =
12729                should_newest_selection_be_reversed;
12730            should_newest_selection_be_reversed
12731        };
12732
12733        if selected_larger_node {
12734            self.select_syntax_node_history.disable_clearing = true;
12735            self.change_selections(None, window, cx, |s| {
12736                s.select(new_selections.clone());
12737            });
12738            self.select_syntax_node_history.disable_clearing = false;
12739        }
12740
12741        let start_row = last_new.start.to_display_point(&display_map).row().0;
12742        let end_row = last_new.end.to_display_point(&display_map).row().0;
12743        let selection_height = end_row - start_row + 1;
12744        let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12745
12746        let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
12747        let scroll_behavior = if fits_on_the_screen {
12748            self.request_autoscroll(Autoscroll::fit(), cx);
12749            SelectSyntaxNodeScrollBehavior::FitSelection
12750        } else if is_selection_reversed {
12751            self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12752            SelectSyntaxNodeScrollBehavior::CursorTop
12753        } else {
12754            self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12755            SelectSyntaxNodeScrollBehavior::CursorBottom
12756        };
12757
12758        self.select_syntax_node_history.push((
12759            old_selections,
12760            scroll_behavior,
12761            is_selection_reversed,
12762        ));
12763    }
12764
12765    pub fn select_smaller_syntax_node(
12766        &mut self,
12767        _: &SelectSmallerSyntaxNode,
12768        window: &mut Window,
12769        cx: &mut Context<Self>,
12770    ) {
12771        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12772
12773        if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12774            self.select_syntax_node_history.pop()
12775        {
12776            if let Some(selection) = selections.last_mut() {
12777                selection.reversed = is_selection_reversed;
12778            }
12779
12780            self.select_syntax_node_history.disable_clearing = true;
12781            self.change_selections(None, window, cx, |s| {
12782                s.select(selections.to_vec());
12783            });
12784            self.select_syntax_node_history.disable_clearing = false;
12785
12786            match scroll_behavior {
12787                SelectSyntaxNodeScrollBehavior::CursorTop => {
12788                    self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12789                }
12790                SelectSyntaxNodeScrollBehavior::FitSelection => {
12791                    self.request_autoscroll(Autoscroll::fit(), cx);
12792                }
12793                SelectSyntaxNodeScrollBehavior::CursorBottom => {
12794                    self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12795                }
12796            }
12797        }
12798    }
12799
12800    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12801        if !EditorSettings::get_global(cx).gutter.runnables {
12802            self.clear_tasks();
12803            return Task::ready(());
12804        }
12805        let project = self.project.as_ref().map(Entity::downgrade);
12806        let task_sources = self.lsp_task_sources(cx);
12807        cx.spawn_in(window, async move |editor, cx| {
12808            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12809            let Some(project) = project.and_then(|p| p.upgrade()) else {
12810                return;
12811            };
12812            let Ok(display_snapshot) = editor.update(cx, |this, cx| {
12813                this.display_map.update(cx, |map, cx| map.snapshot(cx))
12814            }) else {
12815                return;
12816            };
12817
12818            let hide_runnables = project
12819                .update(cx, |project, cx| {
12820                    // Do not display any test indicators in non-dev server remote projects.
12821                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12822                })
12823                .unwrap_or(true);
12824            if hide_runnables {
12825                return;
12826            }
12827            let new_rows =
12828                cx.background_spawn({
12829                    let snapshot = display_snapshot.clone();
12830                    async move {
12831                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12832                    }
12833                })
12834                    .await;
12835            let Ok(lsp_tasks) =
12836                cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
12837            else {
12838                return;
12839            };
12840            let lsp_tasks = lsp_tasks.await;
12841
12842            let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
12843                lsp_tasks
12844                    .into_iter()
12845                    .flat_map(|(kind, tasks)| {
12846                        tasks.into_iter().filter_map(move |(location, task)| {
12847                            Some((kind.clone(), location?, task))
12848                        })
12849                    })
12850                    .fold(HashMap::default(), |mut acc, (kind, location, task)| {
12851                        let buffer = location.target.buffer;
12852                        let buffer_snapshot = buffer.read(cx).snapshot();
12853                        let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
12854                            |(excerpt_id, snapshot, _)| {
12855                                if snapshot.remote_id() == buffer_snapshot.remote_id() {
12856                                    display_snapshot
12857                                        .buffer_snapshot
12858                                        .anchor_in_excerpt(excerpt_id, location.target.range.start)
12859                                } else {
12860                                    None
12861                                }
12862                            },
12863                        );
12864                        if let Some(offset) = offset {
12865                            let task_buffer_range =
12866                                location.target.range.to_point(&buffer_snapshot);
12867                            let context_buffer_range =
12868                                task_buffer_range.to_offset(&buffer_snapshot);
12869                            let context_range = BufferOffset(context_buffer_range.start)
12870                                ..BufferOffset(context_buffer_range.end);
12871
12872                            acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
12873                                .or_insert_with(|| RunnableTasks {
12874                                    templates: Vec::new(),
12875                                    offset,
12876                                    column: task_buffer_range.start.column,
12877                                    extra_variables: HashMap::default(),
12878                                    context_range,
12879                                })
12880                                .templates
12881                                .push((kind, task.original_task().clone()));
12882                        }
12883
12884                        acc
12885                    })
12886            }) else {
12887                return;
12888            };
12889
12890            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12891            editor
12892                .update(cx, |editor, _| {
12893                    editor.clear_tasks();
12894                    for (key, mut value) in rows {
12895                        if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
12896                            value.templates.extend(lsp_tasks.templates);
12897                        }
12898
12899                        editor.insert_tasks(key, value);
12900                    }
12901                    for (key, value) in lsp_tasks_by_rows {
12902                        editor.insert_tasks(key, value);
12903                    }
12904                })
12905                .ok();
12906        })
12907    }
12908    fn fetch_runnable_ranges(
12909        snapshot: &DisplaySnapshot,
12910        range: Range<Anchor>,
12911    ) -> Vec<language::RunnableRange> {
12912        snapshot.buffer_snapshot.runnable_ranges(range).collect()
12913    }
12914
12915    fn runnable_rows(
12916        project: Entity<Project>,
12917        snapshot: DisplaySnapshot,
12918        runnable_ranges: Vec<RunnableRange>,
12919        mut cx: AsyncWindowContext,
12920    ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
12921        runnable_ranges
12922            .into_iter()
12923            .filter_map(|mut runnable| {
12924                let tasks = cx
12925                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12926                    .ok()?;
12927                if tasks.is_empty() {
12928                    return None;
12929                }
12930
12931                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12932
12933                let row = snapshot
12934                    .buffer_snapshot
12935                    .buffer_line_for_row(MultiBufferRow(point.row))?
12936                    .1
12937                    .start
12938                    .row;
12939
12940                let context_range =
12941                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12942                Some((
12943                    (runnable.buffer_id, row),
12944                    RunnableTasks {
12945                        templates: tasks,
12946                        offset: snapshot
12947                            .buffer_snapshot
12948                            .anchor_before(runnable.run_range.start),
12949                        context_range,
12950                        column: point.column,
12951                        extra_variables: runnable.extra_captures,
12952                    },
12953                ))
12954            })
12955            .collect()
12956    }
12957
12958    fn templates_with_tags(
12959        project: &Entity<Project>,
12960        runnable: &mut Runnable,
12961        cx: &mut App,
12962    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12963        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12964            let (worktree_id, file) = project
12965                .buffer_for_id(runnable.buffer, cx)
12966                .and_then(|buffer| buffer.read(cx).file())
12967                .map(|file| (file.worktree_id(cx), file.clone()))
12968                .unzip();
12969
12970            (
12971                project.task_store().read(cx).task_inventory().cloned(),
12972                worktree_id,
12973                file,
12974            )
12975        });
12976
12977        let mut templates_with_tags = mem::take(&mut runnable.tags)
12978            .into_iter()
12979            .flat_map(|RunnableTag(tag)| {
12980                inventory
12981                    .as_ref()
12982                    .into_iter()
12983                    .flat_map(|inventory| {
12984                        inventory.read(cx).list_tasks(
12985                            file.clone(),
12986                            Some(runnable.language.clone()),
12987                            worktree_id,
12988                            cx,
12989                        )
12990                    })
12991                    .filter(move |(_, template)| {
12992                        template.tags.iter().any(|source_tag| source_tag == &tag)
12993                    })
12994            })
12995            .sorted_by_key(|(kind, _)| kind.to_owned())
12996            .collect::<Vec<_>>();
12997        if let Some((leading_tag_source, _)) = templates_with_tags.first() {
12998            // Strongest source wins; if we have worktree tag binding, prefer that to
12999            // global and language bindings;
13000            // if we have a global binding, prefer that to language binding.
13001            let first_mismatch = templates_with_tags
13002                .iter()
13003                .position(|(tag_source, _)| tag_source != leading_tag_source);
13004            if let Some(index) = first_mismatch {
13005                templates_with_tags.truncate(index);
13006            }
13007        }
13008
13009        templates_with_tags
13010    }
13011
13012    pub fn move_to_enclosing_bracket(
13013        &mut self,
13014        _: &MoveToEnclosingBracket,
13015        window: &mut Window,
13016        cx: &mut Context<Self>,
13017    ) {
13018        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13019        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13020            s.move_offsets_with(|snapshot, selection| {
13021                let Some(enclosing_bracket_ranges) =
13022                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
13023                else {
13024                    return;
13025                };
13026
13027                let mut best_length = usize::MAX;
13028                let mut best_inside = false;
13029                let mut best_in_bracket_range = false;
13030                let mut best_destination = None;
13031                for (open, close) in enclosing_bracket_ranges {
13032                    let close = close.to_inclusive();
13033                    let length = close.end() - open.start;
13034                    let inside = selection.start >= open.end && selection.end <= *close.start();
13035                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
13036                        || close.contains(&selection.head());
13037
13038                    // If best is next to a bracket and current isn't, skip
13039                    if !in_bracket_range && best_in_bracket_range {
13040                        continue;
13041                    }
13042
13043                    // Prefer smaller lengths unless best is inside and current isn't
13044                    if length > best_length && (best_inside || !inside) {
13045                        continue;
13046                    }
13047
13048                    best_length = length;
13049                    best_inside = inside;
13050                    best_in_bracket_range = in_bracket_range;
13051                    best_destination = Some(
13052                        if close.contains(&selection.start) && close.contains(&selection.end) {
13053                            if inside { open.end } else { open.start }
13054                        } else if inside {
13055                            *close.start()
13056                        } else {
13057                            *close.end()
13058                        },
13059                    );
13060                }
13061
13062                if let Some(destination) = best_destination {
13063                    selection.collapse_to(destination, SelectionGoal::None);
13064                }
13065            })
13066        });
13067    }
13068
13069    pub fn undo_selection(
13070        &mut self,
13071        _: &UndoSelection,
13072        window: &mut Window,
13073        cx: &mut Context<Self>,
13074    ) {
13075        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13076        self.end_selection(window, cx);
13077        self.selection_history.mode = SelectionHistoryMode::Undoing;
13078        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
13079            self.change_selections(None, window, cx, |s| {
13080                s.select_anchors(entry.selections.to_vec())
13081            });
13082            self.select_next_state = entry.select_next_state;
13083            self.select_prev_state = entry.select_prev_state;
13084            self.add_selections_state = entry.add_selections_state;
13085            self.request_autoscroll(Autoscroll::newest(), cx);
13086        }
13087        self.selection_history.mode = SelectionHistoryMode::Normal;
13088    }
13089
13090    pub fn redo_selection(
13091        &mut self,
13092        _: &RedoSelection,
13093        window: &mut Window,
13094        cx: &mut Context<Self>,
13095    ) {
13096        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13097        self.end_selection(window, cx);
13098        self.selection_history.mode = SelectionHistoryMode::Redoing;
13099        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
13100            self.change_selections(None, window, cx, |s| {
13101                s.select_anchors(entry.selections.to_vec())
13102            });
13103            self.select_next_state = entry.select_next_state;
13104            self.select_prev_state = entry.select_prev_state;
13105            self.add_selections_state = entry.add_selections_state;
13106            self.request_autoscroll(Autoscroll::newest(), cx);
13107        }
13108        self.selection_history.mode = SelectionHistoryMode::Normal;
13109    }
13110
13111    pub fn expand_excerpts(
13112        &mut self,
13113        action: &ExpandExcerpts,
13114        _: &mut Window,
13115        cx: &mut Context<Self>,
13116    ) {
13117        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
13118    }
13119
13120    pub fn expand_excerpts_down(
13121        &mut self,
13122        action: &ExpandExcerptsDown,
13123        _: &mut Window,
13124        cx: &mut Context<Self>,
13125    ) {
13126        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
13127    }
13128
13129    pub fn expand_excerpts_up(
13130        &mut self,
13131        action: &ExpandExcerptsUp,
13132        _: &mut Window,
13133        cx: &mut Context<Self>,
13134    ) {
13135        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
13136    }
13137
13138    pub fn expand_excerpts_for_direction(
13139        &mut self,
13140        lines: u32,
13141        direction: ExpandExcerptDirection,
13142
13143        cx: &mut Context<Self>,
13144    ) {
13145        let selections = self.selections.disjoint_anchors();
13146
13147        let lines = if lines == 0 {
13148            EditorSettings::get_global(cx).expand_excerpt_lines
13149        } else {
13150            lines
13151        };
13152
13153        self.buffer.update(cx, |buffer, cx| {
13154            let snapshot = buffer.snapshot(cx);
13155            let mut excerpt_ids = selections
13156                .iter()
13157                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13158                .collect::<Vec<_>>();
13159            excerpt_ids.sort();
13160            excerpt_ids.dedup();
13161            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13162        })
13163    }
13164
13165    pub fn expand_excerpt(
13166        &mut self,
13167        excerpt: ExcerptId,
13168        direction: ExpandExcerptDirection,
13169        window: &mut Window,
13170        cx: &mut Context<Self>,
13171    ) {
13172        let current_scroll_position = self.scroll_position(cx);
13173        let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13174        let mut should_scroll_up = false;
13175
13176        if direction == ExpandExcerptDirection::Down {
13177            let multi_buffer = self.buffer.read(cx);
13178            let snapshot = multi_buffer.snapshot(cx);
13179            if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13180                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13181                    if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13182                        let buffer_snapshot = buffer.read(cx).snapshot();
13183                        let excerpt_end_row =
13184                            Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13185                        let last_row = buffer_snapshot.max_point().row;
13186                        let lines_below = last_row.saturating_sub(excerpt_end_row);
13187                        should_scroll_up = lines_below >= lines_to_expand;
13188                    }
13189                }
13190            }
13191        }
13192
13193        self.buffer.update(cx, |buffer, cx| {
13194            buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13195        });
13196
13197        if should_scroll_up {
13198            let new_scroll_position =
13199                current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13200            self.set_scroll_position(new_scroll_position, window, cx);
13201        }
13202    }
13203
13204    pub fn go_to_singleton_buffer_point(
13205        &mut self,
13206        point: Point,
13207        window: &mut Window,
13208        cx: &mut Context<Self>,
13209    ) {
13210        self.go_to_singleton_buffer_range(point..point, window, cx);
13211    }
13212
13213    pub fn go_to_singleton_buffer_range(
13214        &mut self,
13215        range: Range<Point>,
13216        window: &mut Window,
13217        cx: &mut Context<Self>,
13218    ) {
13219        let multibuffer = self.buffer().read(cx);
13220        let Some(buffer) = multibuffer.as_singleton() else {
13221            return;
13222        };
13223        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13224            return;
13225        };
13226        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13227            return;
13228        };
13229        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13230            s.select_anchor_ranges([start..end])
13231        });
13232    }
13233
13234    pub fn go_to_diagnostic(
13235        &mut self,
13236        _: &GoToDiagnostic,
13237        window: &mut Window,
13238        cx: &mut Context<Self>,
13239    ) {
13240        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13241        self.go_to_diagnostic_impl(Direction::Next, window, cx)
13242    }
13243
13244    pub fn go_to_prev_diagnostic(
13245        &mut self,
13246        _: &GoToPreviousDiagnostic,
13247        window: &mut Window,
13248        cx: &mut Context<Self>,
13249    ) {
13250        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13251        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13252    }
13253
13254    pub fn go_to_diagnostic_impl(
13255        &mut self,
13256        direction: Direction,
13257        window: &mut Window,
13258        cx: &mut Context<Self>,
13259    ) {
13260        let buffer = self.buffer.read(cx).snapshot(cx);
13261        let selection = self.selections.newest::<usize>(cx);
13262
13263        let mut active_group_id = None;
13264        if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13265            if active_group.active_range.start.to_offset(&buffer) == selection.start {
13266                active_group_id = Some(active_group.group_id);
13267            }
13268        }
13269
13270        fn filtered(
13271            snapshot: EditorSnapshot,
13272            diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13273        ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13274            diagnostics
13275                .filter(|entry| entry.range.start != entry.range.end)
13276                .filter(|entry| !entry.diagnostic.is_unnecessary)
13277                .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13278        }
13279
13280        let snapshot = self.snapshot(window, cx);
13281        let before = filtered(
13282            snapshot.clone(),
13283            buffer
13284                .diagnostics_in_range(0..selection.start)
13285                .filter(|entry| entry.range.start <= selection.start),
13286        );
13287        let after = filtered(
13288            snapshot,
13289            buffer
13290                .diagnostics_in_range(selection.start..buffer.len())
13291                .filter(|entry| entry.range.start >= selection.start),
13292        );
13293
13294        let mut found: Option<DiagnosticEntry<usize>> = None;
13295        if direction == Direction::Prev {
13296            'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13297            {
13298                for diagnostic in prev_diagnostics.into_iter().rev() {
13299                    if diagnostic.range.start != selection.start
13300                        || active_group_id
13301                            .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13302                    {
13303                        found = Some(diagnostic);
13304                        break 'outer;
13305                    }
13306                }
13307            }
13308        } else {
13309            for diagnostic in after.chain(before) {
13310                if diagnostic.range.start != selection.start
13311                    || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13312                {
13313                    found = Some(diagnostic);
13314                    break;
13315                }
13316            }
13317        }
13318        let Some(next_diagnostic) = found else {
13319            return;
13320        };
13321
13322        let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13323            return;
13324        };
13325        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13326            s.select_ranges(vec![
13327                next_diagnostic.range.start..next_diagnostic.range.start,
13328            ])
13329        });
13330        self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13331        self.refresh_inline_completion(false, true, window, cx);
13332    }
13333
13334    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13335        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13336        let snapshot = self.snapshot(window, cx);
13337        let selection = self.selections.newest::<Point>(cx);
13338        self.go_to_hunk_before_or_after_position(
13339            &snapshot,
13340            selection.head(),
13341            Direction::Next,
13342            window,
13343            cx,
13344        );
13345    }
13346
13347    pub fn go_to_hunk_before_or_after_position(
13348        &mut self,
13349        snapshot: &EditorSnapshot,
13350        position: Point,
13351        direction: Direction,
13352        window: &mut Window,
13353        cx: &mut Context<Editor>,
13354    ) {
13355        let row = if direction == Direction::Next {
13356            self.hunk_after_position(snapshot, position)
13357                .map(|hunk| hunk.row_range.start)
13358        } else {
13359            self.hunk_before_position(snapshot, position)
13360        };
13361
13362        if let Some(row) = row {
13363            let destination = Point::new(row.0, 0);
13364            let autoscroll = Autoscroll::center();
13365
13366            self.unfold_ranges(&[destination..destination], false, false, cx);
13367            self.change_selections(Some(autoscroll), window, cx, |s| {
13368                s.select_ranges([destination..destination]);
13369            });
13370        }
13371    }
13372
13373    fn hunk_after_position(
13374        &mut self,
13375        snapshot: &EditorSnapshot,
13376        position: Point,
13377    ) -> Option<MultiBufferDiffHunk> {
13378        snapshot
13379            .buffer_snapshot
13380            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13381            .find(|hunk| hunk.row_range.start.0 > position.row)
13382            .or_else(|| {
13383                snapshot
13384                    .buffer_snapshot
13385                    .diff_hunks_in_range(Point::zero()..position)
13386                    .find(|hunk| hunk.row_range.end.0 < position.row)
13387            })
13388    }
13389
13390    fn go_to_prev_hunk(
13391        &mut self,
13392        _: &GoToPreviousHunk,
13393        window: &mut Window,
13394        cx: &mut Context<Self>,
13395    ) {
13396        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13397        let snapshot = self.snapshot(window, cx);
13398        let selection = self.selections.newest::<Point>(cx);
13399        self.go_to_hunk_before_or_after_position(
13400            &snapshot,
13401            selection.head(),
13402            Direction::Prev,
13403            window,
13404            cx,
13405        );
13406    }
13407
13408    fn hunk_before_position(
13409        &mut self,
13410        snapshot: &EditorSnapshot,
13411        position: Point,
13412    ) -> Option<MultiBufferRow> {
13413        snapshot
13414            .buffer_snapshot
13415            .diff_hunk_before(position)
13416            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13417    }
13418
13419    fn go_to_next_change(
13420        &mut self,
13421        _: &GoToNextChange,
13422        window: &mut Window,
13423        cx: &mut Context<Self>,
13424    ) {
13425        if let Some(selections) = self
13426            .change_list
13427            .next_change(1, Direction::Next)
13428            .map(|s| s.to_vec())
13429        {
13430            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13431                let map = s.display_map();
13432                s.select_display_ranges(selections.iter().map(|a| {
13433                    let point = a.to_display_point(&map);
13434                    point..point
13435                }))
13436            })
13437        }
13438    }
13439
13440    fn go_to_previous_change(
13441        &mut self,
13442        _: &GoToPreviousChange,
13443        window: &mut Window,
13444        cx: &mut Context<Self>,
13445    ) {
13446        if let Some(selections) = self
13447            .change_list
13448            .next_change(1, Direction::Prev)
13449            .map(|s| s.to_vec())
13450        {
13451            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13452                let map = s.display_map();
13453                s.select_display_ranges(selections.iter().map(|a| {
13454                    let point = a.to_display_point(&map);
13455                    point..point
13456                }))
13457            })
13458        }
13459    }
13460
13461    fn go_to_line<T: 'static>(
13462        &mut self,
13463        position: Anchor,
13464        highlight_color: Option<Hsla>,
13465        window: &mut Window,
13466        cx: &mut Context<Self>,
13467    ) {
13468        let snapshot = self.snapshot(window, cx).display_snapshot;
13469        let position = position.to_point(&snapshot.buffer_snapshot);
13470        let start = snapshot
13471            .buffer_snapshot
13472            .clip_point(Point::new(position.row, 0), Bias::Left);
13473        let end = start + Point::new(1, 0);
13474        let start = snapshot.buffer_snapshot.anchor_before(start);
13475        let end = snapshot.buffer_snapshot.anchor_before(end);
13476
13477        self.highlight_rows::<T>(
13478            start..end,
13479            highlight_color
13480                .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13481            Default::default(),
13482            cx,
13483        );
13484        self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13485    }
13486
13487    pub fn go_to_definition(
13488        &mut self,
13489        _: &GoToDefinition,
13490        window: &mut Window,
13491        cx: &mut Context<Self>,
13492    ) -> Task<Result<Navigated>> {
13493        let definition =
13494            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13495        let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13496        cx.spawn_in(window, async move |editor, cx| {
13497            if definition.await? == Navigated::Yes {
13498                return Ok(Navigated::Yes);
13499            }
13500            match fallback_strategy {
13501                GoToDefinitionFallback::None => Ok(Navigated::No),
13502                GoToDefinitionFallback::FindAllReferences => {
13503                    match editor.update_in(cx, |editor, window, cx| {
13504                        editor.find_all_references(&FindAllReferences, window, cx)
13505                    })? {
13506                        Some(references) => references.await,
13507                        None => Ok(Navigated::No),
13508                    }
13509                }
13510            }
13511        })
13512    }
13513
13514    pub fn go_to_declaration(
13515        &mut self,
13516        _: &GoToDeclaration,
13517        window: &mut Window,
13518        cx: &mut Context<Self>,
13519    ) -> Task<Result<Navigated>> {
13520        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13521    }
13522
13523    pub fn go_to_declaration_split(
13524        &mut self,
13525        _: &GoToDeclaration,
13526        window: &mut Window,
13527        cx: &mut Context<Self>,
13528    ) -> Task<Result<Navigated>> {
13529        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13530    }
13531
13532    pub fn go_to_implementation(
13533        &mut self,
13534        _: &GoToImplementation,
13535        window: &mut Window,
13536        cx: &mut Context<Self>,
13537    ) -> Task<Result<Navigated>> {
13538        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13539    }
13540
13541    pub fn go_to_implementation_split(
13542        &mut self,
13543        _: &GoToImplementationSplit,
13544        window: &mut Window,
13545        cx: &mut Context<Self>,
13546    ) -> Task<Result<Navigated>> {
13547        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13548    }
13549
13550    pub fn go_to_type_definition(
13551        &mut self,
13552        _: &GoToTypeDefinition,
13553        window: &mut Window,
13554        cx: &mut Context<Self>,
13555    ) -> Task<Result<Navigated>> {
13556        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13557    }
13558
13559    pub fn go_to_definition_split(
13560        &mut self,
13561        _: &GoToDefinitionSplit,
13562        window: &mut Window,
13563        cx: &mut Context<Self>,
13564    ) -> Task<Result<Navigated>> {
13565        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13566    }
13567
13568    pub fn go_to_type_definition_split(
13569        &mut self,
13570        _: &GoToTypeDefinitionSplit,
13571        window: &mut Window,
13572        cx: &mut Context<Self>,
13573    ) -> Task<Result<Navigated>> {
13574        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13575    }
13576
13577    fn go_to_definition_of_kind(
13578        &mut self,
13579        kind: GotoDefinitionKind,
13580        split: bool,
13581        window: &mut Window,
13582        cx: &mut Context<Self>,
13583    ) -> Task<Result<Navigated>> {
13584        let Some(provider) = self.semantics_provider.clone() else {
13585            return Task::ready(Ok(Navigated::No));
13586        };
13587        let head = self.selections.newest::<usize>(cx).head();
13588        let buffer = self.buffer.read(cx);
13589        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13590            text_anchor
13591        } else {
13592            return Task::ready(Ok(Navigated::No));
13593        };
13594
13595        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13596            return Task::ready(Ok(Navigated::No));
13597        };
13598
13599        cx.spawn_in(window, async move |editor, cx| {
13600            let definitions = definitions.await?;
13601            let navigated = editor
13602                .update_in(cx, |editor, window, cx| {
13603                    editor.navigate_to_hover_links(
13604                        Some(kind),
13605                        definitions
13606                            .into_iter()
13607                            .filter(|location| {
13608                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13609                            })
13610                            .map(HoverLink::Text)
13611                            .collect::<Vec<_>>(),
13612                        split,
13613                        window,
13614                        cx,
13615                    )
13616                })?
13617                .await?;
13618            anyhow::Ok(navigated)
13619        })
13620    }
13621
13622    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13623        let selection = self.selections.newest_anchor();
13624        let head = selection.head();
13625        let tail = selection.tail();
13626
13627        let Some((buffer, start_position)) =
13628            self.buffer.read(cx).text_anchor_for_position(head, cx)
13629        else {
13630            return;
13631        };
13632
13633        let end_position = if head != tail {
13634            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13635                return;
13636            };
13637            Some(pos)
13638        } else {
13639            None
13640        };
13641
13642        let url_finder = cx.spawn_in(window, async move |editor, cx| {
13643            let url = if let Some(end_pos) = end_position {
13644                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13645            } else {
13646                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13647            };
13648
13649            if let Some(url) = url {
13650                editor.update(cx, |_, cx| {
13651                    cx.open_url(&url);
13652                })
13653            } else {
13654                Ok(())
13655            }
13656        });
13657
13658        url_finder.detach();
13659    }
13660
13661    pub fn open_selected_filename(
13662        &mut self,
13663        _: &OpenSelectedFilename,
13664        window: &mut Window,
13665        cx: &mut Context<Self>,
13666    ) {
13667        let Some(workspace) = self.workspace() else {
13668            return;
13669        };
13670
13671        let position = self.selections.newest_anchor().head();
13672
13673        let Some((buffer, buffer_position)) =
13674            self.buffer.read(cx).text_anchor_for_position(position, cx)
13675        else {
13676            return;
13677        };
13678
13679        let project = self.project.clone();
13680
13681        cx.spawn_in(window, async move |_, cx| {
13682            let result = find_file(&buffer, project, buffer_position, cx).await;
13683
13684            if let Some((_, path)) = result {
13685                workspace
13686                    .update_in(cx, |workspace, window, cx| {
13687                        workspace.open_resolved_path(path, window, cx)
13688                    })?
13689                    .await?;
13690            }
13691            anyhow::Ok(())
13692        })
13693        .detach();
13694    }
13695
13696    pub(crate) fn navigate_to_hover_links(
13697        &mut self,
13698        kind: Option<GotoDefinitionKind>,
13699        mut definitions: Vec<HoverLink>,
13700        split: bool,
13701        window: &mut Window,
13702        cx: &mut Context<Editor>,
13703    ) -> Task<Result<Navigated>> {
13704        // If there is one definition, just open it directly
13705        if definitions.len() == 1 {
13706            let definition = definitions.pop().unwrap();
13707
13708            enum TargetTaskResult {
13709                Location(Option<Location>),
13710                AlreadyNavigated,
13711            }
13712
13713            let target_task = match definition {
13714                HoverLink::Text(link) => {
13715                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13716                }
13717                HoverLink::InlayHint(lsp_location, server_id) => {
13718                    let computation =
13719                        self.compute_target_location(lsp_location, server_id, window, cx);
13720                    cx.background_spawn(async move {
13721                        let location = computation.await?;
13722                        Ok(TargetTaskResult::Location(location))
13723                    })
13724                }
13725                HoverLink::Url(url) => {
13726                    cx.open_url(&url);
13727                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13728                }
13729                HoverLink::File(path) => {
13730                    if let Some(workspace) = self.workspace() {
13731                        cx.spawn_in(window, async move |_, cx| {
13732                            workspace
13733                                .update_in(cx, |workspace, window, cx| {
13734                                    workspace.open_resolved_path(path, window, cx)
13735                                })?
13736                                .await
13737                                .map(|_| TargetTaskResult::AlreadyNavigated)
13738                        })
13739                    } else {
13740                        Task::ready(Ok(TargetTaskResult::Location(None)))
13741                    }
13742                }
13743            };
13744            cx.spawn_in(window, async move |editor, cx| {
13745                let target = match target_task.await.context("target resolution task")? {
13746                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13747                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
13748                    TargetTaskResult::Location(Some(target)) => target,
13749                };
13750
13751                editor.update_in(cx, |editor, window, cx| {
13752                    let Some(workspace) = editor.workspace() else {
13753                        return Navigated::No;
13754                    };
13755                    let pane = workspace.read(cx).active_pane().clone();
13756
13757                    let range = target.range.to_point(target.buffer.read(cx));
13758                    let range = editor.range_for_match(&range);
13759                    let range = collapse_multiline_range(range);
13760
13761                    if !split
13762                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13763                    {
13764                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13765                    } else {
13766                        window.defer(cx, move |window, cx| {
13767                            let target_editor: Entity<Self> =
13768                                workspace.update(cx, |workspace, cx| {
13769                                    let pane = if split {
13770                                        workspace.adjacent_pane(window, cx)
13771                                    } else {
13772                                        workspace.active_pane().clone()
13773                                    };
13774
13775                                    workspace.open_project_item(
13776                                        pane,
13777                                        target.buffer.clone(),
13778                                        true,
13779                                        true,
13780                                        window,
13781                                        cx,
13782                                    )
13783                                });
13784                            target_editor.update(cx, |target_editor, cx| {
13785                                // When selecting a definition in a different buffer, disable the nav history
13786                                // to avoid creating a history entry at the previous cursor location.
13787                                pane.update(cx, |pane, _| pane.disable_history());
13788                                target_editor.go_to_singleton_buffer_range(range, window, cx);
13789                                pane.update(cx, |pane, _| pane.enable_history());
13790                            });
13791                        });
13792                    }
13793                    Navigated::Yes
13794                })
13795            })
13796        } else if !definitions.is_empty() {
13797            cx.spawn_in(window, async move |editor, cx| {
13798                let (title, location_tasks, workspace) = editor
13799                    .update_in(cx, |editor, window, cx| {
13800                        let tab_kind = match kind {
13801                            Some(GotoDefinitionKind::Implementation) => "Implementations",
13802                            _ => "Definitions",
13803                        };
13804                        let title = definitions
13805                            .iter()
13806                            .find_map(|definition| match definition {
13807                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
13808                                    let buffer = origin.buffer.read(cx);
13809                                    format!(
13810                                        "{} for {}",
13811                                        tab_kind,
13812                                        buffer
13813                                            .text_for_range(origin.range.clone())
13814                                            .collect::<String>()
13815                                    )
13816                                }),
13817                                HoverLink::InlayHint(_, _) => None,
13818                                HoverLink::Url(_) => None,
13819                                HoverLink::File(_) => None,
13820                            })
13821                            .unwrap_or(tab_kind.to_string());
13822                        let location_tasks = definitions
13823                            .into_iter()
13824                            .map(|definition| match definition {
13825                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
13826                                HoverLink::InlayHint(lsp_location, server_id) => editor
13827                                    .compute_target_location(lsp_location, server_id, window, cx),
13828                                HoverLink::Url(_) => Task::ready(Ok(None)),
13829                                HoverLink::File(_) => Task::ready(Ok(None)),
13830                            })
13831                            .collect::<Vec<_>>();
13832                        (title, location_tasks, editor.workspace().clone())
13833                    })
13834                    .context("location tasks preparation")?;
13835
13836                let locations = future::join_all(location_tasks)
13837                    .await
13838                    .into_iter()
13839                    .filter_map(|location| location.transpose())
13840                    .collect::<Result<_>>()
13841                    .context("location tasks")?;
13842
13843                let Some(workspace) = workspace else {
13844                    return Ok(Navigated::No);
13845                };
13846                let opened = workspace
13847                    .update_in(cx, |workspace, window, cx| {
13848                        Self::open_locations_in_multibuffer(
13849                            workspace,
13850                            locations,
13851                            title,
13852                            split,
13853                            MultibufferSelectionMode::First,
13854                            window,
13855                            cx,
13856                        )
13857                    })
13858                    .ok();
13859
13860                anyhow::Ok(Navigated::from_bool(opened.is_some()))
13861            })
13862        } else {
13863            Task::ready(Ok(Navigated::No))
13864        }
13865    }
13866
13867    fn compute_target_location(
13868        &self,
13869        lsp_location: lsp::Location,
13870        server_id: LanguageServerId,
13871        window: &mut Window,
13872        cx: &mut Context<Self>,
13873    ) -> Task<anyhow::Result<Option<Location>>> {
13874        let Some(project) = self.project.clone() else {
13875            return Task::ready(Ok(None));
13876        };
13877
13878        cx.spawn_in(window, async move |editor, cx| {
13879            let location_task = editor.update(cx, |_, cx| {
13880                project.update(cx, |project, cx| {
13881                    let language_server_name = project
13882                        .language_server_statuses(cx)
13883                        .find(|(id, _)| server_id == *id)
13884                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13885                    language_server_name.map(|language_server_name| {
13886                        project.open_local_buffer_via_lsp(
13887                            lsp_location.uri.clone(),
13888                            server_id,
13889                            language_server_name,
13890                            cx,
13891                        )
13892                    })
13893                })
13894            })?;
13895            let location = match location_task {
13896                Some(task) => Some({
13897                    let target_buffer_handle = task.await.context("open local buffer")?;
13898                    let range = target_buffer_handle.update(cx, |target_buffer, _| {
13899                        let target_start = target_buffer
13900                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13901                        let target_end = target_buffer
13902                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13903                        target_buffer.anchor_after(target_start)
13904                            ..target_buffer.anchor_before(target_end)
13905                    })?;
13906                    Location {
13907                        buffer: target_buffer_handle,
13908                        range,
13909                    }
13910                }),
13911                None => None,
13912            };
13913            Ok(location)
13914        })
13915    }
13916
13917    pub fn find_all_references(
13918        &mut self,
13919        _: &FindAllReferences,
13920        window: &mut Window,
13921        cx: &mut Context<Self>,
13922    ) -> Option<Task<Result<Navigated>>> {
13923        let selection = self.selections.newest::<usize>(cx);
13924        let multi_buffer = self.buffer.read(cx);
13925        let head = selection.head();
13926
13927        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13928        let head_anchor = multi_buffer_snapshot.anchor_at(
13929            head,
13930            if head < selection.tail() {
13931                Bias::Right
13932            } else {
13933                Bias::Left
13934            },
13935        );
13936
13937        match self
13938            .find_all_references_task_sources
13939            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13940        {
13941            Ok(_) => {
13942                log::info!(
13943                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
13944                );
13945                return None;
13946            }
13947            Err(i) => {
13948                self.find_all_references_task_sources.insert(i, head_anchor);
13949            }
13950        }
13951
13952        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13953        let workspace = self.workspace()?;
13954        let project = workspace.read(cx).project().clone();
13955        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13956        Some(cx.spawn_in(window, async move |editor, cx| {
13957            let _cleanup = cx.on_drop(&editor, move |editor, _| {
13958                if let Ok(i) = editor
13959                    .find_all_references_task_sources
13960                    .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13961                {
13962                    editor.find_all_references_task_sources.remove(i);
13963                }
13964            });
13965
13966            let locations = references.await?;
13967            if locations.is_empty() {
13968                return anyhow::Ok(Navigated::No);
13969            }
13970
13971            workspace.update_in(cx, |workspace, window, cx| {
13972                let title = locations
13973                    .first()
13974                    .as_ref()
13975                    .map(|location| {
13976                        let buffer = location.buffer.read(cx);
13977                        format!(
13978                            "References to `{}`",
13979                            buffer
13980                                .text_for_range(location.range.clone())
13981                                .collect::<String>()
13982                        )
13983                    })
13984                    .unwrap();
13985                Self::open_locations_in_multibuffer(
13986                    workspace,
13987                    locations,
13988                    title,
13989                    false,
13990                    MultibufferSelectionMode::First,
13991                    window,
13992                    cx,
13993                );
13994                Navigated::Yes
13995            })
13996        }))
13997    }
13998
13999    /// Opens a multibuffer with the given project locations in it
14000    pub fn open_locations_in_multibuffer(
14001        workspace: &mut Workspace,
14002        mut locations: Vec<Location>,
14003        title: String,
14004        split: bool,
14005        multibuffer_selection_mode: MultibufferSelectionMode,
14006        window: &mut Window,
14007        cx: &mut Context<Workspace>,
14008    ) {
14009        // If there are multiple definitions, open them in a multibuffer
14010        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
14011        let mut locations = locations.into_iter().peekable();
14012        let mut ranges: Vec<Range<Anchor>> = Vec::new();
14013        let capability = workspace.project().read(cx).capability();
14014
14015        let excerpt_buffer = cx.new(|cx| {
14016            let mut multibuffer = MultiBuffer::new(capability);
14017            while let Some(location) = locations.next() {
14018                let buffer = location.buffer.read(cx);
14019                let mut ranges_for_buffer = Vec::new();
14020                let range = location.range.to_point(buffer);
14021                ranges_for_buffer.push(range.clone());
14022
14023                while let Some(next_location) = locations.peek() {
14024                    if next_location.buffer == location.buffer {
14025                        ranges_for_buffer.push(next_location.range.to_point(buffer));
14026                        locations.next();
14027                    } else {
14028                        break;
14029                    }
14030                }
14031
14032                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
14033                let (new_ranges, _) = multibuffer.set_excerpts_for_path(
14034                    PathKey::for_buffer(&location.buffer, cx),
14035                    location.buffer.clone(),
14036                    ranges_for_buffer,
14037                    DEFAULT_MULTIBUFFER_CONTEXT,
14038                    cx,
14039                );
14040                ranges.extend(new_ranges)
14041            }
14042
14043            multibuffer.with_title(title)
14044        });
14045
14046        let editor = cx.new(|cx| {
14047            Editor::for_multibuffer(
14048                excerpt_buffer,
14049                Some(workspace.project().clone()),
14050                window,
14051                cx,
14052            )
14053        });
14054        editor.update(cx, |editor, cx| {
14055            match multibuffer_selection_mode {
14056                MultibufferSelectionMode::First => {
14057                    if let Some(first_range) = ranges.first() {
14058                        editor.change_selections(None, window, cx, |selections| {
14059                            selections.clear_disjoint();
14060                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
14061                        });
14062                    }
14063                    editor.highlight_background::<Self>(
14064                        &ranges,
14065                        |theme| theme.editor_highlighted_line_background,
14066                        cx,
14067                    );
14068                }
14069                MultibufferSelectionMode::All => {
14070                    editor.change_selections(None, window, cx, |selections| {
14071                        selections.clear_disjoint();
14072                        selections.select_anchor_ranges(ranges);
14073                    });
14074                }
14075            }
14076            editor.register_buffers_with_language_servers(cx);
14077        });
14078
14079        let item = Box::new(editor);
14080        let item_id = item.item_id();
14081
14082        if split {
14083            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
14084        } else {
14085            if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
14086                let (preview_item_id, preview_item_idx) =
14087                    workspace.active_pane().update(cx, |pane, _| {
14088                        (pane.preview_item_id(), pane.preview_item_idx())
14089                    });
14090
14091                workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
14092
14093                if let Some(preview_item_id) = preview_item_id {
14094                    workspace.active_pane().update(cx, |pane, cx| {
14095                        pane.remove_item(preview_item_id, false, false, window, cx);
14096                    });
14097                }
14098            } else {
14099                workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
14100            }
14101        }
14102        workspace.active_pane().update(cx, |pane, cx| {
14103            pane.set_preview_item_id(Some(item_id), cx);
14104        });
14105    }
14106
14107    pub fn rename(
14108        &mut self,
14109        _: &Rename,
14110        window: &mut Window,
14111        cx: &mut Context<Self>,
14112    ) -> Option<Task<Result<()>>> {
14113        use language::ToOffset as _;
14114
14115        let provider = self.semantics_provider.clone()?;
14116        let selection = self.selections.newest_anchor().clone();
14117        let (cursor_buffer, cursor_buffer_position) = self
14118            .buffer
14119            .read(cx)
14120            .text_anchor_for_position(selection.head(), cx)?;
14121        let (tail_buffer, cursor_buffer_position_end) = self
14122            .buffer
14123            .read(cx)
14124            .text_anchor_for_position(selection.tail(), cx)?;
14125        if tail_buffer != cursor_buffer {
14126            return None;
14127        }
14128
14129        let snapshot = cursor_buffer.read(cx).snapshot();
14130        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
14131        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
14132        let prepare_rename = provider
14133            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
14134            .unwrap_or_else(|| Task::ready(Ok(None)));
14135        drop(snapshot);
14136
14137        Some(cx.spawn_in(window, async move |this, cx| {
14138            let rename_range = if let Some(range) = prepare_rename.await? {
14139                Some(range)
14140            } else {
14141                this.update(cx, |this, cx| {
14142                    let buffer = this.buffer.read(cx).snapshot(cx);
14143                    let mut buffer_highlights = this
14144                        .document_highlights_for_position(selection.head(), &buffer)
14145                        .filter(|highlight| {
14146                            highlight.start.excerpt_id == selection.head().excerpt_id
14147                                && highlight.end.excerpt_id == selection.head().excerpt_id
14148                        });
14149                    buffer_highlights
14150                        .next()
14151                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
14152                })?
14153            };
14154            if let Some(rename_range) = rename_range {
14155                this.update_in(cx, |this, window, cx| {
14156                    let snapshot = cursor_buffer.read(cx).snapshot();
14157                    let rename_buffer_range = rename_range.to_offset(&snapshot);
14158                    let cursor_offset_in_rename_range =
14159                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
14160                    let cursor_offset_in_rename_range_end =
14161                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
14162
14163                    this.take_rename(false, window, cx);
14164                    let buffer = this.buffer.read(cx).read(cx);
14165                    let cursor_offset = selection.head().to_offset(&buffer);
14166                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
14167                    let rename_end = rename_start + rename_buffer_range.len();
14168                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
14169                    let mut old_highlight_id = None;
14170                    let old_name: Arc<str> = buffer
14171                        .chunks(rename_start..rename_end, true)
14172                        .map(|chunk| {
14173                            if old_highlight_id.is_none() {
14174                                old_highlight_id = chunk.syntax_highlight_id;
14175                            }
14176                            chunk.text
14177                        })
14178                        .collect::<String>()
14179                        .into();
14180
14181                    drop(buffer);
14182
14183                    // Position the selection in the rename editor so that it matches the current selection.
14184                    this.show_local_selections = false;
14185                    let rename_editor = cx.new(|cx| {
14186                        let mut editor = Editor::single_line(window, cx);
14187                        editor.buffer.update(cx, |buffer, cx| {
14188                            buffer.edit([(0..0, old_name.clone())], None, cx)
14189                        });
14190                        let rename_selection_range = match cursor_offset_in_rename_range
14191                            .cmp(&cursor_offset_in_rename_range_end)
14192                        {
14193                            Ordering::Equal => {
14194                                editor.select_all(&SelectAll, window, cx);
14195                                return editor;
14196                            }
14197                            Ordering::Less => {
14198                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14199                            }
14200                            Ordering::Greater => {
14201                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14202                            }
14203                        };
14204                        if rename_selection_range.end > old_name.len() {
14205                            editor.select_all(&SelectAll, window, cx);
14206                        } else {
14207                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14208                                s.select_ranges([rename_selection_range]);
14209                            });
14210                        }
14211                        editor
14212                    });
14213                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14214                        if e == &EditorEvent::Focused {
14215                            cx.emit(EditorEvent::FocusedIn)
14216                        }
14217                    })
14218                    .detach();
14219
14220                    let write_highlights =
14221                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14222                    let read_highlights =
14223                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
14224                    let ranges = write_highlights
14225                        .iter()
14226                        .flat_map(|(_, ranges)| ranges.iter())
14227                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14228                        .cloned()
14229                        .collect();
14230
14231                    this.highlight_text::<Rename>(
14232                        ranges,
14233                        HighlightStyle {
14234                            fade_out: Some(0.6),
14235                            ..Default::default()
14236                        },
14237                        cx,
14238                    );
14239                    let rename_focus_handle = rename_editor.focus_handle(cx);
14240                    window.focus(&rename_focus_handle);
14241                    let block_id = this.insert_blocks(
14242                        [BlockProperties {
14243                            style: BlockStyle::Flex,
14244                            placement: BlockPlacement::Below(range.start),
14245                            height: Some(1),
14246                            render: Arc::new({
14247                                let rename_editor = rename_editor.clone();
14248                                move |cx: &mut BlockContext| {
14249                                    let mut text_style = cx.editor_style.text.clone();
14250                                    if let Some(highlight_style) = old_highlight_id
14251                                        .and_then(|h| h.style(&cx.editor_style.syntax))
14252                                    {
14253                                        text_style = text_style.highlight(highlight_style);
14254                                    }
14255                                    div()
14256                                        .block_mouse_down()
14257                                        .pl(cx.anchor_x)
14258                                        .child(EditorElement::new(
14259                                            &rename_editor,
14260                                            EditorStyle {
14261                                                background: cx.theme().system().transparent,
14262                                                local_player: cx.editor_style.local_player,
14263                                                text: text_style,
14264                                                scrollbar_width: cx.editor_style.scrollbar_width,
14265                                                syntax: cx.editor_style.syntax.clone(),
14266                                                status: cx.editor_style.status.clone(),
14267                                                inlay_hints_style: HighlightStyle {
14268                                                    font_weight: Some(FontWeight::BOLD),
14269                                                    ..make_inlay_hints_style(cx.app)
14270                                                },
14271                                                inline_completion_styles: make_suggestion_styles(
14272                                                    cx.app,
14273                                                ),
14274                                                ..EditorStyle::default()
14275                                            },
14276                                        ))
14277                                        .into_any_element()
14278                                }
14279                            }),
14280                            priority: 0,
14281                        }],
14282                        Some(Autoscroll::fit()),
14283                        cx,
14284                    )[0];
14285                    this.pending_rename = Some(RenameState {
14286                        range,
14287                        old_name,
14288                        editor: rename_editor,
14289                        block_id,
14290                    });
14291                })?;
14292            }
14293
14294            Ok(())
14295        }))
14296    }
14297
14298    pub fn confirm_rename(
14299        &mut self,
14300        _: &ConfirmRename,
14301        window: &mut Window,
14302        cx: &mut Context<Self>,
14303    ) -> Option<Task<Result<()>>> {
14304        let rename = self.take_rename(false, window, cx)?;
14305        let workspace = self.workspace()?.downgrade();
14306        let (buffer, start) = self
14307            .buffer
14308            .read(cx)
14309            .text_anchor_for_position(rename.range.start, cx)?;
14310        let (end_buffer, _) = self
14311            .buffer
14312            .read(cx)
14313            .text_anchor_for_position(rename.range.end, cx)?;
14314        if buffer != end_buffer {
14315            return None;
14316        }
14317
14318        let old_name = rename.old_name;
14319        let new_name = rename.editor.read(cx).text(cx);
14320
14321        let rename = self.semantics_provider.as_ref()?.perform_rename(
14322            &buffer,
14323            start,
14324            new_name.clone(),
14325            cx,
14326        )?;
14327
14328        Some(cx.spawn_in(window, async move |editor, cx| {
14329            let project_transaction = rename.await?;
14330            Self::open_project_transaction(
14331                &editor,
14332                workspace,
14333                project_transaction,
14334                format!("Rename: {}{}", old_name, new_name),
14335                cx,
14336            )
14337            .await?;
14338
14339            editor.update(cx, |editor, cx| {
14340                editor.refresh_document_highlights(cx);
14341            })?;
14342            Ok(())
14343        }))
14344    }
14345
14346    fn take_rename(
14347        &mut self,
14348        moving_cursor: bool,
14349        window: &mut Window,
14350        cx: &mut Context<Self>,
14351    ) -> Option<RenameState> {
14352        let rename = self.pending_rename.take()?;
14353        if rename.editor.focus_handle(cx).is_focused(window) {
14354            window.focus(&self.focus_handle);
14355        }
14356
14357        self.remove_blocks(
14358            [rename.block_id].into_iter().collect(),
14359            Some(Autoscroll::fit()),
14360            cx,
14361        );
14362        self.clear_highlights::<Rename>(cx);
14363        self.show_local_selections = true;
14364
14365        if moving_cursor {
14366            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14367                editor.selections.newest::<usize>(cx).head()
14368            });
14369
14370            // Update the selection to match the position of the selection inside
14371            // the rename editor.
14372            let snapshot = self.buffer.read(cx).read(cx);
14373            let rename_range = rename.range.to_offset(&snapshot);
14374            let cursor_in_editor = snapshot
14375                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14376                .min(rename_range.end);
14377            drop(snapshot);
14378
14379            self.change_selections(None, window, cx, |s| {
14380                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14381            });
14382        } else {
14383            self.refresh_document_highlights(cx);
14384        }
14385
14386        Some(rename)
14387    }
14388
14389    pub fn pending_rename(&self) -> Option<&RenameState> {
14390        self.pending_rename.as_ref()
14391    }
14392
14393    fn format(
14394        &mut self,
14395        _: &Format,
14396        window: &mut Window,
14397        cx: &mut Context<Self>,
14398    ) -> Option<Task<Result<()>>> {
14399        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14400
14401        let project = match &self.project {
14402            Some(project) => project.clone(),
14403            None => return None,
14404        };
14405
14406        Some(self.perform_format(
14407            project,
14408            FormatTrigger::Manual,
14409            FormatTarget::Buffers,
14410            window,
14411            cx,
14412        ))
14413    }
14414
14415    fn format_selections(
14416        &mut self,
14417        _: &FormatSelections,
14418        window: &mut Window,
14419        cx: &mut Context<Self>,
14420    ) -> Option<Task<Result<()>>> {
14421        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14422
14423        let project = match &self.project {
14424            Some(project) => project.clone(),
14425            None => return None,
14426        };
14427
14428        let ranges = self
14429            .selections
14430            .all_adjusted(cx)
14431            .into_iter()
14432            .map(|selection| selection.range())
14433            .collect_vec();
14434
14435        Some(self.perform_format(
14436            project,
14437            FormatTrigger::Manual,
14438            FormatTarget::Ranges(ranges),
14439            window,
14440            cx,
14441        ))
14442    }
14443
14444    fn perform_format(
14445        &mut self,
14446        project: Entity<Project>,
14447        trigger: FormatTrigger,
14448        target: FormatTarget,
14449        window: &mut Window,
14450        cx: &mut Context<Self>,
14451    ) -> Task<Result<()>> {
14452        let buffer = self.buffer.clone();
14453        let (buffers, target) = match target {
14454            FormatTarget::Buffers => {
14455                let mut buffers = buffer.read(cx).all_buffers();
14456                if trigger == FormatTrigger::Save {
14457                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
14458                }
14459                (buffers, LspFormatTarget::Buffers)
14460            }
14461            FormatTarget::Ranges(selection_ranges) => {
14462                let multi_buffer = buffer.read(cx);
14463                let snapshot = multi_buffer.read(cx);
14464                let mut buffers = HashSet::default();
14465                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14466                    BTreeMap::new();
14467                for selection_range in selection_ranges {
14468                    for (buffer, buffer_range, _) in
14469                        snapshot.range_to_buffer_ranges(selection_range)
14470                    {
14471                        let buffer_id = buffer.remote_id();
14472                        let start = buffer.anchor_before(buffer_range.start);
14473                        let end = buffer.anchor_after(buffer_range.end);
14474                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14475                        buffer_id_to_ranges
14476                            .entry(buffer_id)
14477                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14478                            .or_insert_with(|| vec![start..end]);
14479                    }
14480                }
14481                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14482            }
14483        };
14484
14485        let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14486        let selections_prev = transaction_id_prev
14487            .and_then(|transaction_id_prev| {
14488                // default to selections as they were after the last edit, if we have them,
14489                // instead of how they are now.
14490                // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14491                // will take you back to where you made the last edit, instead of staying where you scrolled
14492                self.selection_history
14493                    .transaction(transaction_id_prev)
14494                    .map(|t| t.0.clone())
14495            })
14496            .unwrap_or_else(|| {
14497                log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14498                self.selections.disjoint_anchors()
14499            });
14500
14501        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14502        let format = project.update(cx, |project, cx| {
14503            project.format(buffers, target, true, trigger, cx)
14504        });
14505
14506        cx.spawn_in(window, async move |editor, cx| {
14507            let transaction = futures::select_biased! {
14508                transaction = format.log_err().fuse() => transaction,
14509                () = timeout => {
14510                    log::warn!("timed out waiting for formatting");
14511                    None
14512                }
14513            };
14514
14515            buffer
14516                .update(cx, |buffer, cx| {
14517                    if let Some(transaction) = transaction {
14518                        if !buffer.is_singleton() {
14519                            buffer.push_transaction(&transaction.0, cx);
14520                        }
14521                    }
14522                    cx.notify();
14523                })
14524                .ok();
14525
14526            if let Some(transaction_id_now) =
14527                buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14528            {
14529                let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14530                if has_new_transaction {
14531                    _ = editor.update(cx, |editor, _| {
14532                        editor
14533                            .selection_history
14534                            .insert_transaction(transaction_id_now, selections_prev);
14535                    });
14536                }
14537            }
14538
14539            Ok(())
14540        })
14541    }
14542
14543    fn organize_imports(
14544        &mut self,
14545        _: &OrganizeImports,
14546        window: &mut Window,
14547        cx: &mut Context<Self>,
14548    ) -> Option<Task<Result<()>>> {
14549        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14550        let project = match &self.project {
14551            Some(project) => project.clone(),
14552            None => return None,
14553        };
14554        Some(self.perform_code_action_kind(
14555            project,
14556            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14557            window,
14558            cx,
14559        ))
14560    }
14561
14562    fn perform_code_action_kind(
14563        &mut self,
14564        project: Entity<Project>,
14565        kind: CodeActionKind,
14566        window: &mut Window,
14567        cx: &mut Context<Self>,
14568    ) -> Task<Result<()>> {
14569        let buffer = self.buffer.clone();
14570        let buffers = buffer.read(cx).all_buffers();
14571        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14572        let apply_action = project.update(cx, |project, cx| {
14573            project.apply_code_action_kind(buffers, kind, true, cx)
14574        });
14575        cx.spawn_in(window, async move |_, cx| {
14576            let transaction = futures::select_biased! {
14577                () = timeout => {
14578                    log::warn!("timed out waiting for executing code action");
14579                    None
14580                }
14581                transaction = apply_action.log_err().fuse() => transaction,
14582            };
14583            buffer
14584                .update(cx, |buffer, cx| {
14585                    // check if we need this
14586                    if let Some(transaction) = transaction {
14587                        if !buffer.is_singleton() {
14588                            buffer.push_transaction(&transaction.0, cx);
14589                        }
14590                    }
14591                    cx.notify();
14592                })
14593                .ok();
14594            Ok(())
14595        })
14596    }
14597
14598    fn restart_language_server(
14599        &mut self,
14600        _: &RestartLanguageServer,
14601        _: &mut Window,
14602        cx: &mut Context<Self>,
14603    ) {
14604        if let Some(project) = self.project.clone() {
14605            self.buffer.update(cx, |multi_buffer, cx| {
14606                project.update(cx, |project, cx| {
14607                    project.restart_language_servers_for_buffers(
14608                        multi_buffer.all_buffers().into_iter().collect(),
14609                        cx,
14610                    );
14611                });
14612            })
14613        }
14614    }
14615
14616    fn stop_language_server(
14617        &mut self,
14618        _: &StopLanguageServer,
14619        _: &mut Window,
14620        cx: &mut Context<Self>,
14621    ) {
14622        if let Some(project) = self.project.clone() {
14623            self.buffer.update(cx, |multi_buffer, cx| {
14624                project.update(cx, |project, cx| {
14625                    project.stop_language_servers_for_buffers(
14626                        multi_buffer.all_buffers().into_iter().collect(),
14627                        cx,
14628                    );
14629                    cx.emit(project::Event::RefreshInlayHints);
14630                });
14631            });
14632        }
14633    }
14634
14635    fn cancel_language_server_work(
14636        workspace: &mut Workspace,
14637        _: &actions::CancelLanguageServerWork,
14638        _: &mut Window,
14639        cx: &mut Context<Workspace>,
14640    ) {
14641        let project = workspace.project();
14642        let buffers = workspace
14643            .active_item(cx)
14644            .and_then(|item| item.act_as::<Editor>(cx))
14645            .map_or(HashSet::default(), |editor| {
14646                editor.read(cx).buffer.read(cx).all_buffers()
14647            });
14648        project.update(cx, |project, cx| {
14649            project.cancel_language_server_work_for_buffers(buffers, cx);
14650        });
14651    }
14652
14653    fn show_character_palette(
14654        &mut self,
14655        _: &ShowCharacterPalette,
14656        window: &mut Window,
14657        _: &mut Context<Self>,
14658    ) {
14659        window.show_character_palette();
14660    }
14661
14662    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14663        if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
14664            let buffer = self.buffer.read(cx).snapshot(cx);
14665            let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
14666            let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
14667            let is_valid = buffer
14668                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14669                .any(|entry| {
14670                    entry.diagnostic.is_primary
14671                        && !entry.range.is_empty()
14672                        && entry.range.start == primary_range_start
14673                        && entry.diagnostic.message == active_diagnostics.active_message
14674                });
14675
14676            if !is_valid {
14677                self.dismiss_diagnostics(cx);
14678            }
14679        }
14680    }
14681
14682    pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
14683        match &self.active_diagnostics {
14684            ActiveDiagnostic::Group(group) => Some(group),
14685            _ => None,
14686        }
14687    }
14688
14689    pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
14690        self.dismiss_diagnostics(cx);
14691        self.active_diagnostics = ActiveDiagnostic::All;
14692    }
14693
14694    fn activate_diagnostics(
14695        &mut self,
14696        buffer_id: BufferId,
14697        diagnostic: DiagnosticEntry<usize>,
14698        window: &mut Window,
14699        cx: &mut Context<Self>,
14700    ) {
14701        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14702            return;
14703        }
14704        self.dismiss_diagnostics(cx);
14705        let snapshot = self.snapshot(window, cx);
14706        let Some(diagnostic_renderer) = cx
14707            .try_global::<GlobalDiagnosticRenderer>()
14708            .map(|g| g.0.clone())
14709        else {
14710            return;
14711        };
14712        let buffer = self.buffer.read(cx).snapshot(cx);
14713
14714        let diagnostic_group = buffer
14715            .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
14716            .collect::<Vec<_>>();
14717
14718        let blocks = diagnostic_renderer.render_group(
14719            diagnostic_group,
14720            buffer_id,
14721            snapshot,
14722            cx.weak_entity(),
14723            cx,
14724        );
14725
14726        let blocks = self.display_map.update(cx, |display_map, cx| {
14727            display_map.insert_blocks(blocks, cx).into_iter().collect()
14728        });
14729        self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
14730            active_range: buffer.anchor_before(diagnostic.range.start)
14731                ..buffer.anchor_after(diagnostic.range.end),
14732            active_message: diagnostic.diagnostic.message.clone(),
14733            group_id: diagnostic.diagnostic.group_id,
14734            blocks,
14735        });
14736        cx.notify();
14737    }
14738
14739    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14740        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14741            return;
14742        };
14743
14744        let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
14745        if let ActiveDiagnostic::Group(group) = prev {
14746            self.display_map.update(cx, |display_map, cx| {
14747                display_map.remove_blocks(group.blocks, cx);
14748            });
14749            cx.notify();
14750        }
14751    }
14752
14753    /// Disable inline diagnostics rendering for this editor.
14754    pub fn disable_inline_diagnostics(&mut self) {
14755        self.inline_diagnostics_enabled = false;
14756        self.inline_diagnostics_update = Task::ready(());
14757        self.inline_diagnostics.clear();
14758    }
14759
14760    pub fn inline_diagnostics_enabled(&self) -> bool {
14761        self.inline_diagnostics_enabled
14762    }
14763
14764    pub fn show_inline_diagnostics(&self) -> bool {
14765        self.show_inline_diagnostics
14766    }
14767
14768    pub fn toggle_inline_diagnostics(
14769        &mut self,
14770        _: &ToggleInlineDiagnostics,
14771        window: &mut Window,
14772        cx: &mut Context<Editor>,
14773    ) {
14774        self.show_inline_diagnostics = !self.show_inline_diagnostics;
14775        self.refresh_inline_diagnostics(false, window, cx);
14776    }
14777
14778    fn refresh_inline_diagnostics(
14779        &mut self,
14780        debounce: bool,
14781        window: &mut Window,
14782        cx: &mut Context<Self>,
14783    ) {
14784        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14785            self.inline_diagnostics_update = Task::ready(());
14786            self.inline_diagnostics.clear();
14787            return;
14788        }
14789
14790        let debounce_ms = ProjectSettings::get_global(cx)
14791            .diagnostics
14792            .inline
14793            .update_debounce_ms;
14794        let debounce = if debounce && debounce_ms > 0 {
14795            Some(Duration::from_millis(debounce_ms))
14796        } else {
14797            None
14798        };
14799        self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14800            let editor = editor.upgrade().unwrap();
14801
14802            if let Some(debounce) = debounce {
14803                cx.background_executor().timer(debounce).await;
14804            }
14805            let Some(snapshot) = editor
14806                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14807                .ok()
14808            else {
14809                return;
14810            };
14811
14812            let new_inline_diagnostics = cx
14813                .background_spawn(async move {
14814                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14815                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14816                        let message = diagnostic_entry
14817                            .diagnostic
14818                            .message
14819                            .split_once('\n')
14820                            .map(|(line, _)| line)
14821                            .map(SharedString::new)
14822                            .unwrap_or_else(|| {
14823                                SharedString::from(diagnostic_entry.diagnostic.message)
14824                            });
14825                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14826                        let (Ok(i) | Err(i)) = inline_diagnostics
14827                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14828                        inline_diagnostics.insert(
14829                            i,
14830                            (
14831                                start_anchor,
14832                                InlineDiagnostic {
14833                                    message,
14834                                    group_id: diagnostic_entry.diagnostic.group_id,
14835                                    start: diagnostic_entry.range.start.to_point(&snapshot),
14836                                    is_primary: diagnostic_entry.diagnostic.is_primary,
14837                                    severity: diagnostic_entry.diagnostic.severity,
14838                                },
14839                            ),
14840                        );
14841                    }
14842                    inline_diagnostics
14843                })
14844                .await;
14845
14846            editor
14847                .update(cx, |editor, cx| {
14848                    editor.inline_diagnostics = new_inline_diagnostics;
14849                    cx.notify();
14850                })
14851                .ok();
14852        });
14853    }
14854
14855    pub fn set_selections_from_remote(
14856        &mut self,
14857        selections: Vec<Selection<Anchor>>,
14858        pending_selection: Option<Selection<Anchor>>,
14859        window: &mut Window,
14860        cx: &mut Context<Self>,
14861    ) {
14862        let old_cursor_position = self.selections.newest_anchor().head();
14863        self.selections.change_with(cx, |s| {
14864            s.select_anchors(selections);
14865            if let Some(pending_selection) = pending_selection {
14866                s.set_pending(pending_selection, SelectMode::Character);
14867            } else {
14868                s.clear_pending();
14869            }
14870        });
14871        self.selections_did_change(false, &old_cursor_position, true, window, cx);
14872    }
14873
14874    fn push_to_selection_history(&mut self) {
14875        self.selection_history.push(SelectionHistoryEntry {
14876            selections: self.selections.disjoint_anchors(),
14877            select_next_state: self.select_next_state.clone(),
14878            select_prev_state: self.select_prev_state.clone(),
14879            add_selections_state: self.add_selections_state.clone(),
14880        });
14881    }
14882
14883    pub fn transact(
14884        &mut self,
14885        window: &mut Window,
14886        cx: &mut Context<Self>,
14887        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14888    ) -> Option<TransactionId> {
14889        self.start_transaction_at(Instant::now(), window, cx);
14890        update(self, window, cx);
14891        self.end_transaction_at(Instant::now(), cx)
14892    }
14893
14894    pub fn start_transaction_at(
14895        &mut self,
14896        now: Instant,
14897        window: &mut Window,
14898        cx: &mut Context<Self>,
14899    ) {
14900        self.end_selection(window, cx);
14901        if let Some(tx_id) = self
14902            .buffer
14903            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14904        {
14905            self.selection_history
14906                .insert_transaction(tx_id, self.selections.disjoint_anchors());
14907            cx.emit(EditorEvent::TransactionBegun {
14908                transaction_id: tx_id,
14909            })
14910        }
14911    }
14912
14913    pub fn end_transaction_at(
14914        &mut self,
14915        now: Instant,
14916        cx: &mut Context<Self>,
14917    ) -> Option<TransactionId> {
14918        if let Some(transaction_id) = self
14919            .buffer
14920            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14921        {
14922            if let Some((_, end_selections)) =
14923                self.selection_history.transaction_mut(transaction_id)
14924            {
14925                *end_selections = Some(self.selections.disjoint_anchors());
14926            } else {
14927                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14928            }
14929
14930            cx.emit(EditorEvent::Edited { transaction_id });
14931            Some(transaction_id)
14932        } else {
14933            None
14934        }
14935    }
14936
14937    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14938        if self.selection_mark_mode {
14939            self.change_selections(None, window, cx, |s| {
14940                s.move_with(|_, sel| {
14941                    sel.collapse_to(sel.head(), SelectionGoal::None);
14942                });
14943            })
14944        }
14945        self.selection_mark_mode = true;
14946        cx.notify();
14947    }
14948
14949    pub fn swap_selection_ends(
14950        &mut self,
14951        _: &actions::SwapSelectionEnds,
14952        window: &mut Window,
14953        cx: &mut Context<Self>,
14954    ) {
14955        self.change_selections(None, window, cx, |s| {
14956            s.move_with(|_, sel| {
14957                if sel.start != sel.end {
14958                    sel.reversed = !sel.reversed
14959                }
14960            });
14961        });
14962        self.request_autoscroll(Autoscroll::newest(), cx);
14963        cx.notify();
14964    }
14965
14966    pub fn toggle_fold(
14967        &mut self,
14968        _: &actions::ToggleFold,
14969        window: &mut Window,
14970        cx: &mut Context<Self>,
14971    ) {
14972        if self.is_singleton(cx) {
14973            let selection = self.selections.newest::<Point>(cx);
14974
14975            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14976            let range = if selection.is_empty() {
14977                let point = selection.head().to_display_point(&display_map);
14978                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14979                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14980                    .to_point(&display_map);
14981                start..end
14982            } else {
14983                selection.range()
14984            };
14985            if display_map.folds_in_range(range).next().is_some() {
14986                self.unfold_lines(&Default::default(), window, cx)
14987            } else {
14988                self.fold(&Default::default(), window, cx)
14989            }
14990        } else {
14991            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14992            let buffer_ids: HashSet<_> = self
14993                .selections
14994                .disjoint_anchor_ranges()
14995                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14996                .collect();
14997
14998            let should_unfold = buffer_ids
14999                .iter()
15000                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
15001
15002            for buffer_id in buffer_ids {
15003                if should_unfold {
15004                    self.unfold_buffer(buffer_id, cx);
15005                } else {
15006                    self.fold_buffer(buffer_id, cx);
15007                }
15008            }
15009        }
15010    }
15011
15012    pub fn toggle_fold_recursive(
15013        &mut self,
15014        _: &actions::ToggleFoldRecursive,
15015        window: &mut Window,
15016        cx: &mut Context<Self>,
15017    ) {
15018        let selection = self.selections.newest::<Point>(cx);
15019
15020        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15021        let range = if selection.is_empty() {
15022            let point = selection.head().to_display_point(&display_map);
15023            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15024            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15025                .to_point(&display_map);
15026            start..end
15027        } else {
15028            selection.range()
15029        };
15030        if display_map.folds_in_range(range).next().is_some() {
15031            self.unfold_recursive(&Default::default(), window, cx)
15032        } else {
15033            self.fold_recursive(&Default::default(), window, cx)
15034        }
15035    }
15036
15037    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
15038        if self.is_singleton(cx) {
15039            let mut to_fold = Vec::new();
15040            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15041            let selections = self.selections.all_adjusted(cx);
15042
15043            for selection in selections {
15044                let range = selection.range().sorted();
15045                let buffer_start_row = range.start.row;
15046
15047                if range.start.row != range.end.row {
15048                    let mut found = false;
15049                    let mut row = range.start.row;
15050                    while row <= range.end.row {
15051                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
15052                        {
15053                            found = true;
15054                            row = crease.range().end.row + 1;
15055                            to_fold.push(crease);
15056                        } else {
15057                            row += 1
15058                        }
15059                    }
15060                    if found {
15061                        continue;
15062                    }
15063                }
15064
15065                for row in (0..=range.start.row).rev() {
15066                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15067                        if crease.range().end.row >= buffer_start_row {
15068                            to_fold.push(crease);
15069                            if row <= range.start.row {
15070                                break;
15071                            }
15072                        }
15073                    }
15074                }
15075            }
15076
15077            self.fold_creases(to_fold, true, window, cx);
15078        } else {
15079            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15080            let buffer_ids = self
15081                .selections
15082                .disjoint_anchor_ranges()
15083                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15084                .collect::<HashSet<_>>();
15085            for buffer_id in buffer_ids {
15086                self.fold_buffer(buffer_id, cx);
15087            }
15088        }
15089    }
15090
15091    fn fold_at_level(
15092        &mut self,
15093        fold_at: &FoldAtLevel,
15094        window: &mut Window,
15095        cx: &mut Context<Self>,
15096    ) {
15097        if !self.buffer.read(cx).is_singleton() {
15098            return;
15099        }
15100
15101        let fold_at_level = fold_at.0;
15102        let snapshot = self.buffer.read(cx).snapshot(cx);
15103        let mut to_fold = Vec::new();
15104        let mut stack = vec![(0, snapshot.max_row().0, 1)];
15105
15106        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
15107            while start_row < end_row {
15108                match self
15109                    .snapshot(window, cx)
15110                    .crease_for_buffer_row(MultiBufferRow(start_row))
15111                {
15112                    Some(crease) => {
15113                        let nested_start_row = crease.range().start.row + 1;
15114                        let nested_end_row = crease.range().end.row;
15115
15116                        if current_level < fold_at_level {
15117                            stack.push((nested_start_row, nested_end_row, current_level + 1));
15118                        } else if current_level == fold_at_level {
15119                            to_fold.push(crease);
15120                        }
15121
15122                        start_row = nested_end_row + 1;
15123                    }
15124                    None => start_row += 1,
15125                }
15126            }
15127        }
15128
15129        self.fold_creases(to_fold, true, window, cx);
15130    }
15131
15132    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
15133        if self.buffer.read(cx).is_singleton() {
15134            let mut fold_ranges = Vec::new();
15135            let snapshot = self.buffer.read(cx).snapshot(cx);
15136
15137            for row in 0..snapshot.max_row().0 {
15138                if let Some(foldable_range) = self
15139                    .snapshot(window, cx)
15140                    .crease_for_buffer_row(MultiBufferRow(row))
15141                {
15142                    fold_ranges.push(foldable_range);
15143                }
15144            }
15145
15146            self.fold_creases(fold_ranges, true, window, cx);
15147        } else {
15148            self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
15149                editor
15150                    .update_in(cx, |editor, _, cx| {
15151                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15152                            editor.fold_buffer(buffer_id, cx);
15153                        }
15154                    })
15155                    .ok();
15156            });
15157        }
15158    }
15159
15160    pub fn fold_function_bodies(
15161        &mut self,
15162        _: &actions::FoldFunctionBodies,
15163        window: &mut Window,
15164        cx: &mut Context<Self>,
15165    ) {
15166        let snapshot = self.buffer.read(cx).snapshot(cx);
15167
15168        let ranges = snapshot
15169            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
15170            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
15171            .collect::<Vec<_>>();
15172
15173        let creases = ranges
15174            .into_iter()
15175            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
15176            .collect();
15177
15178        self.fold_creases(creases, true, window, cx);
15179    }
15180
15181    pub fn fold_recursive(
15182        &mut self,
15183        _: &actions::FoldRecursive,
15184        window: &mut Window,
15185        cx: &mut Context<Self>,
15186    ) {
15187        let mut to_fold = Vec::new();
15188        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15189        let selections = self.selections.all_adjusted(cx);
15190
15191        for selection in selections {
15192            let range = selection.range().sorted();
15193            let buffer_start_row = range.start.row;
15194
15195            if range.start.row != range.end.row {
15196                let mut found = false;
15197                for row in range.start.row..=range.end.row {
15198                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15199                        found = true;
15200                        to_fold.push(crease);
15201                    }
15202                }
15203                if found {
15204                    continue;
15205                }
15206            }
15207
15208            for row in (0..=range.start.row).rev() {
15209                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15210                    if crease.range().end.row >= buffer_start_row {
15211                        to_fold.push(crease);
15212                    } else {
15213                        break;
15214                    }
15215                }
15216            }
15217        }
15218
15219        self.fold_creases(to_fold, true, window, cx);
15220    }
15221
15222    pub fn fold_at(
15223        &mut self,
15224        buffer_row: MultiBufferRow,
15225        window: &mut Window,
15226        cx: &mut Context<Self>,
15227    ) {
15228        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15229
15230        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15231            let autoscroll = self
15232                .selections
15233                .all::<Point>(cx)
15234                .iter()
15235                .any(|selection| crease.range().overlaps(&selection.range()));
15236
15237            self.fold_creases(vec![crease], autoscroll, window, cx);
15238        }
15239    }
15240
15241    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15242        if self.is_singleton(cx) {
15243            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15244            let buffer = &display_map.buffer_snapshot;
15245            let selections = self.selections.all::<Point>(cx);
15246            let ranges = selections
15247                .iter()
15248                .map(|s| {
15249                    let range = s.display_range(&display_map).sorted();
15250                    let mut start = range.start.to_point(&display_map);
15251                    let mut end = range.end.to_point(&display_map);
15252                    start.column = 0;
15253                    end.column = buffer.line_len(MultiBufferRow(end.row));
15254                    start..end
15255                })
15256                .collect::<Vec<_>>();
15257
15258            self.unfold_ranges(&ranges, true, true, cx);
15259        } else {
15260            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15261            let buffer_ids = self
15262                .selections
15263                .disjoint_anchor_ranges()
15264                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15265                .collect::<HashSet<_>>();
15266            for buffer_id in buffer_ids {
15267                self.unfold_buffer(buffer_id, cx);
15268            }
15269        }
15270    }
15271
15272    pub fn unfold_recursive(
15273        &mut self,
15274        _: &UnfoldRecursive,
15275        _window: &mut Window,
15276        cx: &mut Context<Self>,
15277    ) {
15278        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15279        let selections = self.selections.all::<Point>(cx);
15280        let ranges = selections
15281            .iter()
15282            .map(|s| {
15283                let mut range = s.display_range(&display_map).sorted();
15284                *range.start.column_mut() = 0;
15285                *range.end.column_mut() = display_map.line_len(range.end.row());
15286                let start = range.start.to_point(&display_map);
15287                let end = range.end.to_point(&display_map);
15288                start..end
15289            })
15290            .collect::<Vec<_>>();
15291
15292        self.unfold_ranges(&ranges, true, true, cx);
15293    }
15294
15295    pub fn unfold_at(
15296        &mut self,
15297        buffer_row: MultiBufferRow,
15298        _window: &mut Window,
15299        cx: &mut Context<Self>,
15300    ) {
15301        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15302
15303        let intersection_range = Point::new(buffer_row.0, 0)
15304            ..Point::new(
15305                buffer_row.0,
15306                display_map.buffer_snapshot.line_len(buffer_row),
15307            );
15308
15309        let autoscroll = self
15310            .selections
15311            .all::<Point>(cx)
15312            .iter()
15313            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15314
15315        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15316    }
15317
15318    pub fn unfold_all(
15319        &mut self,
15320        _: &actions::UnfoldAll,
15321        _window: &mut Window,
15322        cx: &mut Context<Self>,
15323    ) {
15324        if self.buffer.read(cx).is_singleton() {
15325            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15326            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15327        } else {
15328            self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15329                editor
15330                    .update(cx, |editor, cx| {
15331                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15332                            editor.unfold_buffer(buffer_id, cx);
15333                        }
15334                    })
15335                    .ok();
15336            });
15337        }
15338    }
15339
15340    pub fn fold_selected_ranges(
15341        &mut self,
15342        _: &FoldSelectedRanges,
15343        window: &mut Window,
15344        cx: &mut Context<Self>,
15345    ) {
15346        let selections = self.selections.all_adjusted(cx);
15347        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15348        let ranges = selections
15349            .into_iter()
15350            .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15351            .collect::<Vec<_>>();
15352        self.fold_creases(ranges, true, window, cx);
15353    }
15354
15355    pub fn fold_ranges<T: ToOffset + Clone>(
15356        &mut self,
15357        ranges: Vec<Range<T>>,
15358        auto_scroll: bool,
15359        window: &mut Window,
15360        cx: &mut Context<Self>,
15361    ) {
15362        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15363        let ranges = ranges
15364            .into_iter()
15365            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15366            .collect::<Vec<_>>();
15367        self.fold_creases(ranges, auto_scroll, window, cx);
15368    }
15369
15370    pub fn fold_creases<T: ToOffset + Clone>(
15371        &mut self,
15372        creases: Vec<Crease<T>>,
15373        auto_scroll: bool,
15374        _window: &mut Window,
15375        cx: &mut Context<Self>,
15376    ) {
15377        if creases.is_empty() {
15378            return;
15379        }
15380
15381        let mut buffers_affected = HashSet::default();
15382        let multi_buffer = self.buffer().read(cx);
15383        for crease in &creases {
15384            if let Some((_, buffer, _)) =
15385                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15386            {
15387                buffers_affected.insert(buffer.read(cx).remote_id());
15388            };
15389        }
15390
15391        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15392
15393        if auto_scroll {
15394            self.request_autoscroll(Autoscroll::fit(), cx);
15395        }
15396
15397        cx.notify();
15398
15399        self.scrollbar_marker_state.dirty = true;
15400        self.folds_did_change(cx);
15401    }
15402
15403    /// Removes any folds whose ranges intersect any of the given ranges.
15404    pub fn unfold_ranges<T: ToOffset + Clone>(
15405        &mut self,
15406        ranges: &[Range<T>],
15407        inclusive: bool,
15408        auto_scroll: bool,
15409        cx: &mut Context<Self>,
15410    ) {
15411        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15412            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15413        });
15414        self.folds_did_change(cx);
15415    }
15416
15417    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15418        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15419            return;
15420        }
15421        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15422        self.display_map.update(cx, |display_map, cx| {
15423            display_map.fold_buffers([buffer_id], cx)
15424        });
15425        cx.emit(EditorEvent::BufferFoldToggled {
15426            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15427            folded: true,
15428        });
15429        cx.notify();
15430    }
15431
15432    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15433        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15434            return;
15435        }
15436        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15437        self.display_map.update(cx, |display_map, cx| {
15438            display_map.unfold_buffers([buffer_id], cx);
15439        });
15440        cx.emit(EditorEvent::BufferFoldToggled {
15441            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15442            folded: false,
15443        });
15444        cx.notify();
15445    }
15446
15447    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15448        self.display_map.read(cx).is_buffer_folded(buffer)
15449    }
15450
15451    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15452        self.display_map.read(cx).folded_buffers()
15453    }
15454
15455    pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15456        self.display_map.update(cx, |display_map, cx| {
15457            display_map.disable_header_for_buffer(buffer_id, cx);
15458        });
15459        cx.notify();
15460    }
15461
15462    /// Removes any folds with the given ranges.
15463    pub fn remove_folds_with_type<T: ToOffset + Clone>(
15464        &mut self,
15465        ranges: &[Range<T>],
15466        type_id: TypeId,
15467        auto_scroll: bool,
15468        cx: &mut Context<Self>,
15469    ) {
15470        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15471            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15472        });
15473        self.folds_did_change(cx);
15474    }
15475
15476    fn remove_folds_with<T: ToOffset + Clone>(
15477        &mut self,
15478        ranges: &[Range<T>],
15479        auto_scroll: bool,
15480        cx: &mut Context<Self>,
15481        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15482    ) {
15483        if ranges.is_empty() {
15484            return;
15485        }
15486
15487        let mut buffers_affected = HashSet::default();
15488        let multi_buffer = self.buffer().read(cx);
15489        for range in ranges {
15490            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15491                buffers_affected.insert(buffer.read(cx).remote_id());
15492            };
15493        }
15494
15495        self.display_map.update(cx, update);
15496
15497        if auto_scroll {
15498            self.request_autoscroll(Autoscroll::fit(), cx);
15499        }
15500
15501        cx.notify();
15502        self.scrollbar_marker_state.dirty = true;
15503        self.active_indent_guides_state.dirty = true;
15504    }
15505
15506    pub fn update_fold_widths(
15507        &mut self,
15508        widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15509        cx: &mut Context<Self>,
15510    ) -> bool {
15511        self.display_map
15512            .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15513    }
15514
15515    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15516        self.display_map.read(cx).fold_placeholder.clone()
15517    }
15518
15519    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15520        self.buffer.update(cx, |buffer, cx| {
15521            buffer.set_all_diff_hunks_expanded(cx);
15522        });
15523    }
15524
15525    pub fn expand_all_diff_hunks(
15526        &mut self,
15527        _: &ExpandAllDiffHunks,
15528        _window: &mut Window,
15529        cx: &mut Context<Self>,
15530    ) {
15531        self.buffer.update(cx, |buffer, cx| {
15532            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15533        });
15534    }
15535
15536    pub fn toggle_selected_diff_hunks(
15537        &mut self,
15538        _: &ToggleSelectedDiffHunks,
15539        _window: &mut Window,
15540        cx: &mut Context<Self>,
15541    ) {
15542        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15543        self.toggle_diff_hunks_in_ranges(ranges, cx);
15544    }
15545
15546    pub fn diff_hunks_in_ranges<'a>(
15547        &'a self,
15548        ranges: &'a [Range<Anchor>],
15549        buffer: &'a MultiBufferSnapshot,
15550    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15551        ranges.iter().flat_map(move |range| {
15552            let end_excerpt_id = range.end.excerpt_id;
15553            let range = range.to_point(buffer);
15554            let mut peek_end = range.end;
15555            if range.end.row < buffer.max_row().0 {
15556                peek_end = Point::new(range.end.row + 1, 0);
15557            }
15558            buffer
15559                .diff_hunks_in_range(range.start..peek_end)
15560                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15561        })
15562    }
15563
15564    pub fn has_stageable_diff_hunks_in_ranges(
15565        &self,
15566        ranges: &[Range<Anchor>],
15567        snapshot: &MultiBufferSnapshot,
15568    ) -> bool {
15569        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15570        hunks.any(|hunk| hunk.status().has_secondary_hunk())
15571    }
15572
15573    pub fn toggle_staged_selected_diff_hunks(
15574        &mut self,
15575        _: &::git::ToggleStaged,
15576        _: &mut Window,
15577        cx: &mut Context<Self>,
15578    ) {
15579        let snapshot = self.buffer.read(cx).snapshot(cx);
15580        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15581        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15582        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15583    }
15584
15585    pub fn set_render_diff_hunk_controls(
15586        &mut self,
15587        render_diff_hunk_controls: RenderDiffHunkControlsFn,
15588        cx: &mut Context<Self>,
15589    ) {
15590        self.render_diff_hunk_controls = render_diff_hunk_controls;
15591        cx.notify();
15592    }
15593
15594    pub fn stage_and_next(
15595        &mut self,
15596        _: &::git::StageAndNext,
15597        window: &mut Window,
15598        cx: &mut Context<Self>,
15599    ) {
15600        self.do_stage_or_unstage_and_next(true, window, cx);
15601    }
15602
15603    pub fn unstage_and_next(
15604        &mut self,
15605        _: &::git::UnstageAndNext,
15606        window: &mut Window,
15607        cx: &mut Context<Self>,
15608    ) {
15609        self.do_stage_or_unstage_and_next(false, window, cx);
15610    }
15611
15612    pub fn stage_or_unstage_diff_hunks(
15613        &mut self,
15614        stage: bool,
15615        ranges: Vec<Range<Anchor>>,
15616        cx: &mut Context<Self>,
15617    ) {
15618        let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15619        cx.spawn(async move |this, cx| {
15620            task.await?;
15621            this.update(cx, |this, cx| {
15622                let snapshot = this.buffer.read(cx).snapshot(cx);
15623                let chunk_by = this
15624                    .diff_hunks_in_ranges(&ranges, &snapshot)
15625                    .chunk_by(|hunk| hunk.buffer_id);
15626                for (buffer_id, hunks) in &chunk_by {
15627                    this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15628                }
15629            })
15630        })
15631        .detach_and_log_err(cx);
15632    }
15633
15634    fn save_buffers_for_ranges_if_needed(
15635        &mut self,
15636        ranges: &[Range<Anchor>],
15637        cx: &mut Context<Editor>,
15638    ) -> Task<Result<()>> {
15639        let multibuffer = self.buffer.read(cx);
15640        let snapshot = multibuffer.read(cx);
15641        let buffer_ids: HashSet<_> = ranges
15642            .iter()
15643            .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15644            .collect();
15645        drop(snapshot);
15646
15647        let mut buffers = HashSet::default();
15648        for buffer_id in buffer_ids {
15649            if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15650                let buffer = buffer_entity.read(cx);
15651                if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15652                {
15653                    buffers.insert(buffer_entity);
15654                }
15655            }
15656        }
15657
15658        if let Some(project) = &self.project {
15659            project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15660        } else {
15661            Task::ready(Ok(()))
15662        }
15663    }
15664
15665    fn do_stage_or_unstage_and_next(
15666        &mut self,
15667        stage: bool,
15668        window: &mut Window,
15669        cx: &mut Context<Self>,
15670    ) {
15671        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15672
15673        if ranges.iter().any(|range| range.start != range.end) {
15674            self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15675            return;
15676        }
15677
15678        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15679        let snapshot = self.snapshot(window, cx);
15680        let position = self.selections.newest::<Point>(cx).head();
15681        let mut row = snapshot
15682            .buffer_snapshot
15683            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15684            .find(|hunk| hunk.row_range.start.0 > position.row)
15685            .map(|hunk| hunk.row_range.start);
15686
15687        let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15688        // Outside of the project diff editor, wrap around to the beginning.
15689        if !all_diff_hunks_expanded {
15690            row = row.or_else(|| {
15691                snapshot
15692                    .buffer_snapshot
15693                    .diff_hunks_in_range(Point::zero()..position)
15694                    .find(|hunk| hunk.row_range.end.0 < position.row)
15695                    .map(|hunk| hunk.row_range.start)
15696            });
15697        }
15698
15699        if let Some(row) = row {
15700            let destination = Point::new(row.0, 0);
15701            let autoscroll = Autoscroll::center();
15702
15703            self.unfold_ranges(&[destination..destination], false, false, cx);
15704            self.change_selections(Some(autoscroll), window, cx, |s| {
15705                s.select_ranges([destination..destination]);
15706            });
15707        }
15708    }
15709
15710    fn do_stage_or_unstage(
15711        &self,
15712        stage: bool,
15713        buffer_id: BufferId,
15714        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15715        cx: &mut App,
15716    ) -> Option<()> {
15717        let project = self.project.as_ref()?;
15718        let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15719        let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15720        let buffer_snapshot = buffer.read(cx).snapshot();
15721        let file_exists = buffer_snapshot
15722            .file()
15723            .is_some_and(|file| file.disk_state().exists());
15724        diff.update(cx, |diff, cx| {
15725            diff.stage_or_unstage_hunks(
15726                stage,
15727                &hunks
15728                    .map(|hunk| buffer_diff::DiffHunk {
15729                        buffer_range: hunk.buffer_range,
15730                        diff_base_byte_range: hunk.diff_base_byte_range,
15731                        secondary_status: hunk.secondary_status,
15732                        range: Point::zero()..Point::zero(), // unused
15733                    })
15734                    .collect::<Vec<_>>(),
15735                &buffer_snapshot,
15736                file_exists,
15737                cx,
15738            )
15739        });
15740        None
15741    }
15742
15743    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15744        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15745        self.buffer
15746            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15747    }
15748
15749    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
15750        self.buffer.update(cx, |buffer, cx| {
15751            let ranges = vec![Anchor::min()..Anchor::max()];
15752            if !buffer.all_diff_hunks_expanded()
15753                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
15754            {
15755                buffer.collapse_diff_hunks(ranges, cx);
15756                true
15757            } else {
15758                false
15759            }
15760        })
15761    }
15762
15763    fn toggle_diff_hunks_in_ranges(
15764        &mut self,
15765        ranges: Vec<Range<Anchor>>,
15766        cx: &mut Context<Editor>,
15767    ) {
15768        self.buffer.update(cx, |buffer, cx| {
15769            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
15770            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
15771        })
15772    }
15773
15774    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15775        self.buffer.update(cx, |buffer, cx| {
15776            let snapshot = buffer.snapshot(cx);
15777            let excerpt_id = range.end.excerpt_id;
15778            let point_range = range.to_point(&snapshot);
15779            let expand = !buffer.single_hunk_is_expanded(range, cx);
15780            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15781        })
15782    }
15783
15784    pub(crate) fn apply_all_diff_hunks(
15785        &mut self,
15786        _: &ApplyAllDiffHunks,
15787        window: &mut Window,
15788        cx: &mut Context<Self>,
15789    ) {
15790        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15791
15792        let buffers = self.buffer.read(cx).all_buffers();
15793        for branch_buffer in buffers {
15794            branch_buffer.update(cx, |branch_buffer, cx| {
15795                branch_buffer.merge_into_base(Vec::new(), cx);
15796            });
15797        }
15798
15799        if let Some(project) = self.project.clone() {
15800            self.save(true, project, window, cx).detach_and_log_err(cx);
15801        }
15802    }
15803
15804    pub(crate) fn apply_selected_diff_hunks(
15805        &mut self,
15806        _: &ApplyDiffHunk,
15807        window: &mut Window,
15808        cx: &mut Context<Self>,
15809    ) {
15810        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15811        let snapshot = self.snapshot(window, cx);
15812        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15813        let mut ranges_by_buffer = HashMap::default();
15814        self.transact(window, cx, |editor, _window, cx| {
15815            for hunk in hunks {
15816                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15817                    ranges_by_buffer
15818                        .entry(buffer.clone())
15819                        .or_insert_with(Vec::new)
15820                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15821                }
15822            }
15823
15824            for (buffer, ranges) in ranges_by_buffer {
15825                buffer.update(cx, |buffer, cx| {
15826                    buffer.merge_into_base(ranges, cx);
15827                });
15828            }
15829        });
15830
15831        if let Some(project) = self.project.clone() {
15832            self.save(true, project, window, cx).detach_and_log_err(cx);
15833        }
15834    }
15835
15836    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15837        if hovered != self.gutter_hovered {
15838            self.gutter_hovered = hovered;
15839            cx.notify();
15840        }
15841    }
15842
15843    pub fn insert_blocks(
15844        &mut self,
15845        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15846        autoscroll: Option<Autoscroll>,
15847        cx: &mut Context<Self>,
15848    ) -> Vec<CustomBlockId> {
15849        let blocks = self
15850            .display_map
15851            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15852        if let Some(autoscroll) = autoscroll {
15853            self.request_autoscroll(autoscroll, cx);
15854        }
15855        cx.notify();
15856        blocks
15857    }
15858
15859    pub fn resize_blocks(
15860        &mut self,
15861        heights: HashMap<CustomBlockId, u32>,
15862        autoscroll: Option<Autoscroll>,
15863        cx: &mut Context<Self>,
15864    ) {
15865        self.display_map
15866            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15867        if let Some(autoscroll) = autoscroll {
15868            self.request_autoscroll(autoscroll, cx);
15869        }
15870        cx.notify();
15871    }
15872
15873    pub fn replace_blocks(
15874        &mut self,
15875        renderers: HashMap<CustomBlockId, RenderBlock>,
15876        autoscroll: Option<Autoscroll>,
15877        cx: &mut Context<Self>,
15878    ) {
15879        self.display_map
15880            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15881        if let Some(autoscroll) = autoscroll {
15882            self.request_autoscroll(autoscroll, cx);
15883        }
15884        cx.notify();
15885    }
15886
15887    pub fn remove_blocks(
15888        &mut self,
15889        block_ids: HashSet<CustomBlockId>,
15890        autoscroll: Option<Autoscroll>,
15891        cx: &mut Context<Self>,
15892    ) {
15893        self.display_map.update(cx, |display_map, cx| {
15894            display_map.remove_blocks(block_ids, cx)
15895        });
15896        if let Some(autoscroll) = autoscroll {
15897            self.request_autoscroll(autoscroll, cx);
15898        }
15899        cx.notify();
15900    }
15901
15902    pub fn row_for_block(
15903        &self,
15904        block_id: CustomBlockId,
15905        cx: &mut Context<Self>,
15906    ) -> Option<DisplayRow> {
15907        self.display_map
15908            .update(cx, |map, cx| map.row_for_block(block_id, cx))
15909    }
15910
15911    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15912        self.focused_block = Some(focused_block);
15913    }
15914
15915    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15916        self.focused_block.take()
15917    }
15918
15919    pub fn insert_creases(
15920        &mut self,
15921        creases: impl IntoIterator<Item = Crease<Anchor>>,
15922        cx: &mut Context<Self>,
15923    ) -> Vec<CreaseId> {
15924        self.display_map
15925            .update(cx, |map, cx| map.insert_creases(creases, cx))
15926    }
15927
15928    pub fn remove_creases(
15929        &mut self,
15930        ids: impl IntoIterator<Item = CreaseId>,
15931        cx: &mut Context<Self>,
15932    ) {
15933        self.display_map
15934            .update(cx, |map, cx| map.remove_creases(ids, cx));
15935    }
15936
15937    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15938        self.display_map
15939            .update(cx, |map, cx| map.snapshot(cx))
15940            .longest_row()
15941    }
15942
15943    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15944        self.display_map
15945            .update(cx, |map, cx| map.snapshot(cx))
15946            .max_point()
15947    }
15948
15949    pub fn text(&self, cx: &App) -> String {
15950        self.buffer.read(cx).read(cx).text()
15951    }
15952
15953    pub fn is_empty(&self, cx: &App) -> bool {
15954        self.buffer.read(cx).read(cx).is_empty()
15955    }
15956
15957    pub fn text_option(&self, cx: &App) -> Option<String> {
15958        let text = self.text(cx);
15959        let text = text.trim();
15960
15961        if text.is_empty() {
15962            return None;
15963        }
15964
15965        Some(text.to_string())
15966    }
15967
15968    pub fn set_text(
15969        &mut self,
15970        text: impl Into<Arc<str>>,
15971        window: &mut Window,
15972        cx: &mut Context<Self>,
15973    ) {
15974        self.transact(window, cx, |this, _, cx| {
15975            this.buffer
15976                .read(cx)
15977                .as_singleton()
15978                .expect("you can only call set_text on editors for singleton buffers")
15979                .update(cx, |buffer, cx| buffer.set_text(text, cx));
15980        });
15981    }
15982
15983    pub fn display_text(&self, cx: &mut App) -> String {
15984        self.display_map
15985            .update(cx, |map, cx| map.snapshot(cx))
15986            .text()
15987    }
15988
15989    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15990        let mut wrap_guides = smallvec::smallvec![];
15991
15992        if self.show_wrap_guides == Some(false) {
15993            return wrap_guides;
15994        }
15995
15996        let settings = self.buffer.read(cx).language_settings(cx);
15997        if settings.show_wrap_guides {
15998            match self.soft_wrap_mode(cx) {
15999                SoftWrap::Column(soft_wrap) => {
16000                    wrap_guides.push((soft_wrap as usize, true));
16001                }
16002                SoftWrap::Bounded(soft_wrap) => {
16003                    wrap_guides.push((soft_wrap as usize, true));
16004                }
16005                SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
16006            }
16007            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
16008        }
16009
16010        wrap_guides
16011    }
16012
16013    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
16014        let settings = self.buffer.read(cx).language_settings(cx);
16015        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
16016        match mode {
16017            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
16018                SoftWrap::None
16019            }
16020            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
16021            language_settings::SoftWrap::PreferredLineLength => {
16022                SoftWrap::Column(settings.preferred_line_length)
16023            }
16024            language_settings::SoftWrap::Bounded => {
16025                SoftWrap::Bounded(settings.preferred_line_length)
16026            }
16027        }
16028    }
16029
16030    pub fn set_soft_wrap_mode(
16031        &mut self,
16032        mode: language_settings::SoftWrap,
16033
16034        cx: &mut Context<Self>,
16035    ) {
16036        self.soft_wrap_mode_override = Some(mode);
16037        cx.notify();
16038    }
16039
16040    pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
16041        self.hard_wrap = hard_wrap;
16042        cx.notify();
16043    }
16044
16045    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
16046        self.text_style_refinement = Some(style);
16047    }
16048
16049    /// called by the Element so we know what style we were most recently rendered with.
16050    pub(crate) fn set_style(
16051        &mut self,
16052        style: EditorStyle,
16053        window: &mut Window,
16054        cx: &mut Context<Self>,
16055    ) {
16056        let rem_size = window.rem_size();
16057        self.display_map.update(cx, |map, cx| {
16058            map.set_font(
16059                style.text.font(),
16060                style.text.font_size.to_pixels(rem_size),
16061                cx,
16062            )
16063        });
16064        self.style = Some(style);
16065    }
16066
16067    pub fn style(&self) -> Option<&EditorStyle> {
16068        self.style.as_ref()
16069    }
16070
16071    // Called by the element. This method is not designed to be called outside of the editor
16072    // element's layout code because it does not notify when rewrapping is computed synchronously.
16073    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
16074        self.display_map
16075            .update(cx, |map, cx| map.set_wrap_width(width, cx))
16076    }
16077
16078    pub fn set_soft_wrap(&mut self) {
16079        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
16080    }
16081
16082    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
16083        if self.soft_wrap_mode_override.is_some() {
16084            self.soft_wrap_mode_override.take();
16085        } else {
16086            let soft_wrap = match self.soft_wrap_mode(cx) {
16087                SoftWrap::GitDiff => return,
16088                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
16089                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
16090                    language_settings::SoftWrap::None
16091                }
16092            };
16093            self.soft_wrap_mode_override = Some(soft_wrap);
16094        }
16095        cx.notify();
16096    }
16097
16098    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
16099        let Some(workspace) = self.workspace() else {
16100            return;
16101        };
16102        let fs = workspace.read(cx).app_state().fs.clone();
16103        let current_show = TabBarSettings::get_global(cx).show;
16104        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
16105            setting.show = Some(!current_show);
16106        });
16107    }
16108
16109    pub fn toggle_indent_guides(
16110        &mut self,
16111        _: &ToggleIndentGuides,
16112        _: &mut Window,
16113        cx: &mut Context<Self>,
16114    ) {
16115        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
16116            self.buffer
16117                .read(cx)
16118                .language_settings(cx)
16119                .indent_guides
16120                .enabled
16121        });
16122        self.show_indent_guides = Some(!currently_enabled);
16123        cx.notify();
16124    }
16125
16126    fn should_show_indent_guides(&self) -> Option<bool> {
16127        self.show_indent_guides
16128    }
16129
16130    pub fn toggle_line_numbers(
16131        &mut self,
16132        _: &ToggleLineNumbers,
16133        _: &mut Window,
16134        cx: &mut Context<Self>,
16135    ) {
16136        let mut editor_settings = EditorSettings::get_global(cx).clone();
16137        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
16138        EditorSettings::override_global(editor_settings, cx);
16139    }
16140
16141    pub fn line_numbers_enabled(&self, cx: &App) -> bool {
16142        if let Some(show_line_numbers) = self.show_line_numbers {
16143            return show_line_numbers;
16144        }
16145        EditorSettings::get_global(cx).gutter.line_numbers
16146    }
16147
16148    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
16149        self.use_relative_line_numbers
16150            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
16151    }
16152
16153    pub fn toggle_relative_line_numbers(
16154        &mut self,
16155        _: &ToggleRelativeLineNumbers,
16156        _: &mut Window,
16157        cx: &mut Context<Self>,
16158    ) {
16159        let is_relative = self.should_use_relative_line_numbers(cx);
16160        self.set_relative_line_number(Some(!is_relative), cx)
16161    }
16162
16163    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
16164        self.use_relative_line_numbers = is_relative;
16165        cx.notify();
16166    }
16167
16168    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
16169        self.show_gutter = show_gutter;
16170        cx.notify();
16171    }
16172
16173    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
16174        self.show_scrollbars = show_scrollbars;
16175        cx.notify();
16176    }
16177
16178    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
16179        self.show_line_numbers = Some(show_line_numbers);
16180        cx.notify();
16181    }
16182
16183    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
16184        self.show_git_diff_gutter = Some(show_git_diff_gutter);
16185        cx.notify();
16186    }
16187
16188    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
16189        self.show_code_actions = Some(show_code_actions);
16190        cx.notify();
16191    }
16192
16193    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16194        self.show_runnables = Some(show_runnables);
16195        cx.notify();
16196    }
16197
16198    pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16199        self.show_breakpoints = Some(show_breakpoints);
16200        cx.notify();
16201    }
16202
16203    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16204        if self.display_map.read(cx).masked != masked {
16205            self.display_map.update(cx, |map, _| map.masked = masked);
16206        }
16207        cx.notify()
16208    }
16209
16210    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16211        self.show_wrap_guides = Some(show_wrap_guides);
16212        cx.notify();
16213    }
16214
16215    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16216        self.show_indent_guides = Some(show_indent_guides);
16217        cx.notify();
16218    }
16219
16220    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16221        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16222            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16223                if let Some(dir) = file.abs_path(cx).parent() {
16224                    return Some(dir.to_owned());
16225                }
16226            }
16227
16228            if let Some(project_path) = buffer.read(cx).project_path(cx) {
16229                return Some(project_path.path.to_path_buf());
16230            }
16231        }
16232
16233        None
16234    }
16235
16236    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16237        self.active_excerpt(cx)?
16238            .1
16239            .read(cx)
16240            .file()
16241            .and_then(|f| f.as_local())
16242    }
16243
16244    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16245        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16246            let buffer = buffer.read(cx);
16247            if let Some(project_path) = buffer.project_path(cx) {
16248                let project = self.project.as_ref()?.read(cx);
16249                project.absolute_path(&project_path, cx)
16250            } else {
16251                buffer
16252                    .file()
16253                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16254            }
16255        })
16256    }
16257
16258    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16259        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16260            let project_path = buffer.read(cx).project_path(cx)?;
16261            let project = self.project.as_ref()?.read(cx);
16262            let entry = project.entry_for_path(&project_path, cx)?;
16263            let path = entry.path.to_path_buf();
16264            Some(path)
16265        })
16266    }
16267
16268    pub fn reveal_in_finder(
16269        &mut self,
16270        _: &RevealInFileManager,
16271        _window: &mut Window,
16272        cx: &mut Context<Self>,
16273    ) {
16274        if let Some(target) = self.target_file(cx) {
16275            cx.reveal_path(&target.abs_path(cx));
16276        }
16277    }
16278
16279    pub fn copy_path(
16280        &mut self,
16281        _: &zed_actions::workspace::CopyPath,
16282        _window: &mut Window,
16283        cx: &mut Context<Self>,
16284    ) {
16285        if let Some(path) = self.target_file_abs_path(cx) {
16286            if let Some(path) = path.to_str() {
16287                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16288            }
16289        }
16290    }
16291
16292    pub fn copy_relative_path(
16293        &mut self,
16294        _: &zed_actions::workspace::CopyRelativePath,
16295        _window: &mut Window,
16296        cx: &mut Context<Self>,
16297    ) {
16298        if let Some(path) = self.target_file_path(cx) {
16299            if let Some(path) = path.to_str() {
16300                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16301            }
16302        }
16303    }
16304
16305    pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16306        if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16307            buffer.read(cx).project_path(cx)
16308        } else {
16309            None
16310        }
16311    }
16312
16313    // Returns true if the editor handled a go-to-line request
16314    pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16315        maybe!({
16316            let breakpoint_store = self.breakpoint_store.as_ref()?;
16317
16318            let Some((_, _, active_position)) =
16319                breakpoint_store.read(cx).active_position().cloned()
16320            else {
16321                self.clear_row_highlights::<DebugCurrentRowHighlight>();
16322                return None;
16323            };
16324
16325            let snapshot = self
16326                .project
16327                .as_ref()?
16328                .read(cx)
16329                .buffer_for_id(active_position.buffer_id?, cx)?
16330                .read(cx)
16331                .snapshot();
16332
16333            let mut handled = false;
16334            for (id, ExcerptRange { context, .. }) in self
16335                .buffer
16336                .read(cx)
16337                .excerpts_for_buffer(active_position.buffer_id?, cx)
16338            {
16339                if context.start.cmp(&active_position, &snapshot).is_ge()
16340                    || context.end.cmp(&active_position, &snapshot).is_lt()
16341                {
16342                    continue;
16343                }
16344                let snapshot = self.buffer.read(cx).snapshot(cx);
16345                let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
16346
16347                handled = true;
16348                self.clear_row_highlights::<DebugCurrentRowHighlight>();
16349                self.go_to_line::<DebugCurrentRowHighlight>(
16350                    multibuffer_anchor,
16351                    Some(cx.theme().colors().editor_debugger_active_line_background),
16352                    window,
16353                    cx,
16354                );
16355
16356                cx.notify();
16357            }
16358            handled.then_some(())
16359        })
16360        .is_some()
16361    }
16362
16363    pub fn copy_file_name_without_extension(
16364        &mut self,
16365        _: &CopyFileNameWithoutExtension,
16366        _: &mut Window,
16367        cx: &mut Context<Self>,
16368    ) {
16369        if let Some(file) = self.target_file(cx) {
16370            if let Some(file_stem) = file.path().file_stem() {
16371                if let Some(name) = file_stem.to_str() {
16372                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16373                }
16374            }
16375        }
16376    }
16377
16378    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16379        if let Some(file) = self.target_file(cx) {
16380            if let Some(file_name) = file.path().file_name() {
16381                if let Some(name) = file_name.to_str() {
16382                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16383                }
16384            }
16385        }
16386    }
16387
16388    pub fn toggle_git_blame(
16389        &mut self,
16390        _: &::git::Blame,
16391        window: &mut Window,
16392        cx: &mut Context<Self>,
16393    ) {
16394        self.show_git_blame_gutter = !self.show_git_blame_gutter;
16395
16396        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16397            self.start_git_blame(true, window, cx);
16398        }
16399
16400        cx.notify();
16401    }
16402
16403    pub fn toggle_git_blame_inline(
16404        &mut self,
16405        _: &ToggleGitBlameInline,
16406        window: &mut Window,
16407        cx: &mut Context<Self>,
16408    ) {
16409        self.toggle_git_blame_inline_internal(true, window, cx);
16410        cx.notify();
16411    }
16412
16413    pub fn open_git_blame_commit(
16414        &mut self,
16415        _: &OpenGitBlameCommit,
16416        window: &mut Window,
16417        cx: &mut Context<Self>,
16418    ) {
16419        self.open_git_blame_commit_internal(window, cx);
16420    }
16421
16422    fn open_git_blame_commit_internal(
16423        &mut self,
16424        window: &mut Window,
16425        cx: &mut Context<Self>,
16426    ) -> Option<()> {
16427        let blame = self.blame.as_ref()?;
16428        let snapshot = self.snapshot(window, cx);
16429        let cursor = self.selections.newest::<Point>(cx).head();
16430        let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16431        let blame_entry = blame
16432            .update(cx, |blame, cx| {
16433                blame
16434                    .blame_for_rows(
16435                        &[RowInfo {
16436                            buffer_id: Some(buffer.remote_id()),
16437                            buffer_row: Some(point.row),
16438                            ..Default::default()
16439                        }],
16440                        cx,
16441                    )
16442                    .next()
16443            })
16444            .flatten()?;
16445        let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16446        let repo = blame.read(cx).repository(cx)?;
16447        let workspace = self.workspace()?.downgrade();
16448        renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16449        None
16450    }
16451
16452    pub fn git_blame_inline_enabled(&self) -> bool {
16453        self.git_blame_inline_enabled
16454    }
16455
16456    pub fn toggle_selection_menu(
16457        &mut self,
16458        _: &ToggleSelectionMenu,
16459        _: &mut Window,
16460        cx: &mut Context<Self>,
16461    ) {
16462        self.show_selection_menu = self
16463            .show_selection_menu
16464            .map(|show_selections_menu| !show_selections_menu)
16465            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16466
16467        cx.notify();
16468    }
16469
16470    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16471        self.show_selection_menu
16472            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16473    }
16474
16475    fn start_git_blame(
16476        &mut self,
16477        user_triggered: bool,
16478        window: &mut Window,
16479        cx: &mut Context<Self>,
16480    ) {
16481        if let Some(project) = self.project.as_ref() {
16482            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16483                return;
16484            };
16485
16486            if buffer.read(cx).file().is_none() {
16487                return;
16488            }
16489
16490            let focused = self.focus_handle(cx).contains_focused(window, cx);
16491
16492            let project = project.clone();
16493            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16494            self.blame_subscription =
16495                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16496            self.blame = Some(blame);
16497        }
16498    }
16499
16500    fn toggle_git_blame_inline_internal(
16501        &mut self,
16502        user_triggered: bool,
16503        window: &mut Window,
16504        cx: &mut Context<Self>,
16505    ) {
16506        if self.git_blame_inline_enabled {
16507            self.git_blame_inline_enabled = false;
16508            self.show_git_blame_inline = false;
16509            self.show_git_blame_inline_delay_task.take();
16510        } else {
16511            self.git_blame_inline_enabled = true;
16512            self.start_git_blame_inline(user_triggered, window, cx);
16513        }
16514
16515        cx.notify();
16516    }
16517
16518    fn start_git_blame_inline(
16519        &mut self,
16520        user_triggered: bool,
16521        window: &mut Window,
16522        cx: &mut Context<Self>,
16523    ) {
16524        self.start_git_blame(user_triggered, window, cx);
16525
16526        if ProjectSettings::get_global(cx)
16527            .git
16528            .inline_blame_delay()
16529            .is_some()
16530        {
16531            self.start_inline_blame_timer(window, cx);
16532        } else {
16533            self.show_git_blame_inline = true
16534        }
16535    }
16536
16537    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16538        self.blame.as_ref()
16539    }
16540
16541    pub fn show_git_blame_gutter(&self) -> bool {
16542        self.show_git_blame_gutter
16543    }
16544
16545    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16546        self.show_git_blame_gutter && self.has_blame_entries(cx)
16547    }
16548
16549    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16550        self.show_git_blame_inline
16551            && (self.focus_handle.is_focused(window)
16552                || self
16553                    .git_blame_inline_tooltip
16554                    .as_ref()
16555                    .and_then(|t| t.upgrade())
16556                    .is_some())
16557            && !self.newest_selection_head_on_empty_line(cx)
16558            && self.has_blame_entries(cx)
16559    }
16560
16561    fn has_blame_entries(&self, cx: &App) -> bool {
16562        self.blame()
16563            .map_or(false, |blame| blame.read(cx).has_generated_entries())
16564    }
16565
16566    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16567        let cursor_anchor = self.selections.newest_anchor().head();
16568
16569        let snapshot = self.buffer.read(cx).snapshot(cx);
16570        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16571
16572        snapshot.line_len(buffer_row) == 0
16573    }
16574
16575    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16576        let buffer_and_selection = maybe!({
16577            let selection = self.selections.newest::<Point>(cx);
16578            let selection_range = selection.range();
16579
16580            let multi_buffer = self.buffer().read(cx);
16581            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16582            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16583
16584            let (buffer, range, _) = if selection.reversed {
16585                buffer_ranges.first()
16586            } else {
16587                buffer_ranges.last()
16588            }?;
16589
16590            let selection = text::ToPoint::to_point(&range.start, &buffer).row
16591                ..text::ToPoint::to_point(&range.end, &buffer).row;
16592            Some((
16593                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16594                selection,
16595            ))
16596        });
16597
16598        let Some((buffer, selection)) = buffer_and_selection else {
16599            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16600        };
16601
16602        let Some(project) = self.project.as_ref() else {
16603            return Task::ready(Err(anyhow!("editor does not have project")));
16604        };
16605
16606        project.update(cx, |project, cx| {
16607            project.get_permalink_to_line(&buffer, selection, cx)
16608        })
16609    }
16610
16611    pub fn copy_permalink_to_line(
16612        &mut self,
16613        _: &CopyPermalinkToLine,
16614        window: &mut Window,
16615        cx: &mut Context<Self>,
16616    ) {
16617        let permalink_task = self.get_permalink_to_line(cx);
16618        let workspace = self.workspace();
16619
16620        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16621            Ok(permalink) => {
16622                cx.update(|_, cx| {
16623                    cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16624                })
16625                .ok();
16626            }
16627            Err(err) => {
16628                let message = format!("Failed to copy permalink: {err}");
16629
16630                Err::<(), anyhow::Error>(err).log_err();
16631
16632                if let Some(workspace) = workspace {
16633                    workspace
16634                        .update_in(cx, |workspace, _, cx| {
16635                            struct CopyPermalinkToLine;
16636
16637                            workspace.show_toast(
16638                                Toast::new(
16639                                    NotificationId::unique::<CopyPermalinkToLine>(),
16640                                    message,
16641                                ),
16642                                cx,
16643                            )
16644                        })
16645                        .ok();
16646                }
16647            }
16648        })
16649        .detach();
16650    }
16651
16652    pub fn copy_file_location(
16653        &mut self,
16654        _: &CopyFileLocation,
16655        _: &mut Window,
16656        cx: &mut Context<Self>,
16657    ) {
16658        let selection = self.selections.newest::<Point>(cx).start.row + 1;
16659        if let Some(file) = self.target_file(cx) {
16660            if let Some(path) = file.path().to_str() {
16661                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16662            }
16663        }
16664    }
16665
16666    pub fn open_permalink_to_line(
16667        &mut self,
16668        _: &OpenPermalinkToLine,
16669        window: &mut Window,
16670        cx: &mut Context<Self>,
16671    ) {
16672        let permalink_task = self.get_permalink_to_line(cx);
16673        let workspace = self.workspace();
16674
16675        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16676            Ok(permalink) => {
16677                cx.update(|_, cx| {
16678                    cx.open_url(permalink.as_ref());
16679                })
16680                .ok();
16681            }
16682            Err(err) => {
16683                let message = format!("Failed to open permalink: {err}");
16684
16685                Err::<(), anyhow::Error>(err).log_err();
16686
16687                if let Some(workspace) = workspace {
16688                    workspace
16689                        .update(cx, |workspace, cx| {
16690                            struct OpenPermalinkToLine;
16691
16692                            workspace.show_toast(
16693                                Toast::new(
16694                                    NotificationId::unique::<OpenPermalinkToLine>(),
16695                                    message,
16696                                ),
16697                                cx,
16698                            )
16699                        })
16700                        .ok();
16701                }
16702            }
16703        })
16704        .detach();
16705    }
16706
16707    pub fn insert_uuid_v4(
16708        &mut self,
16709        _: &InsertUuidV4,
16710        window: &mut Window,
16711        cx: &mut Context<Self>,
16712    ) {
16713        self.insert_uuid(UuidVersion::V4, window, cx);
16714    }
16715
16716    pub fn insert_uuid_v7(
16717        &mut self,
16718        _: &InsertUuidV7,
16719        window: &mut Window,
16720        cx: &mut Context<Self>,
16721    ) {
16722        self.insert_uuid(UuidVersion::V7, window, cx);
16723    }
16724
16725    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16726        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16727        self.transact(window, cx, |this, window, cx| {
16728            let edits = this
16729                .selections
16730                .all::<Point>(cx)
16731                .into_iter()
16732                .map(|selection| {
16733                    let uuid = match version {
16734                        UuidVersion::V4 => uuid::Uuid::new_v4(),
16735                        UuidVersion::V7 => uuid::Uuid::now_v7(),
16736                    };
16737
16738                    (selection.range(), uuid.to_string())
16739                });
16740            this.edit(edits, cx);
16741            this.refresh_inline_completion(true, false, window, cx);
16742        });
16743    }
16744
16745    pub fn open_selections_in_multibuffer(
16746        &mut self,
16747        _: &OpenSelectionsInMultibuffer,
16748        window: &mut Window,
16749        cx: &mut Context<Self>,
16750    ) {
16751        let multibuffer = self.buffer.read(cx);
16752
16753        let Some(buffer) = multibuffer.as_singleton() else {
16754            return;
16755        };
16756
16757        let Some(workspace) = self.workspace() else {
16758            return;
16759        };
16760
16761        let locations = self
16762            .selections
16763            .disjoint_anchors()
16764            .iter()
16765            .map(|range| Location {
16766                buffer: buffer.clone(),
16767                range: range.start.text_anchor..range.end.text_anchor,
16768            })
16769            .collect::<Vec<_>>();
16770
16771        let title = multibuffer.title(cx).to_string();
16772
16773        cx.spawn_in(window, async move |_, cx| {
16774            workspace.update_in(cx, |workspace, window, cx| {
16775                Self::open_locations_in_multibuffer(
16776                    workspace,
16777                    locations,
16778                    format!("Selections for '{title}'"),
16779                    false,
16780                    MultibufferSelectionMode::All,
16781                    window,
16782                    cx,
16783                );
16784            })
16785        })
16786        .detach();
16787    }
16788
16789    /// Adds a row highlight for the given range. If a row has multiple highlights, the
16790    /// last highlight added will be used.
16791    ///
16792    /// If the range ends at the beginning of a line, then that line will not be highlighted.
16793    pub fn highlight_rows<T: 'static>(
16794        &mut self,
16795        range: Range<Anchor>,
16796        color: Hsla,
16797        options: RowHighlightOptions,
16798        cx: &mut Context<Self>,
16799    ) {
16800        let snapshot = self.buffer().read(cx).snapshot(cx);
16801        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16802        let ix = row_highlights.binary_search_by(|highlight| {
16803            Ordering::Equal
16804                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
16805                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
16806        });
16807
16808        if let Err(mut ix) = ix {
16809            let index = post_inc(&mut self.highlight_order);
16810
16811            // If this range intersects with the preceding highlight, then merge it with
16812            // the preceding highlight. Otherwise insert a new highlight.
16813            let mut merged = false;
16814            if ix > 0 {
16815                let prev_highlight = &mut row_highlights[ix - 1];
16816                if prev_highlight
16817                    .range
16818                    .end
16819                    .cmp(&range.start, &snapshot)
16820                    .is_ge()
16821                {
16822                    ix -= 1;
16823                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
16824                        prev_highlight.range.end = range.end;
16825                    }
16826                    merged = true;
16827                    prev_highlight.index = index;
16828                    prev_highlight.color = color;
16829                    prev_highlight.options = options;
16830                }
16831            }
16832
16833            if !merged {
16834                row_highlights.insert(
16835                    ix,
16836                    RowHighlight {
16837                        range: range.clone(),
16838                        index,
16839                        color,
16840                        options,
16841                        type_id: TypeId::of::<T>(),
16842                    },
16843                );
16844            }
16845
16846            // If any of the following highlights intersect with this one, merge them.
16847            while let Some(next_highlight) = row_highlights.get(ix + 1) {
16848                let highlight = &row_highlights[ix];
16849                if next_highlight
16850                    .range
16851                    .start
16852                    .cmp(&highlight.range.end, &snapshot)
16853                    .is_le()
16854                {
16855                    if next_highlight
16856                        .range
16857                        .end
16858                        .cmp(&highlight.range.end, &snapshot)
16859                        .is_gt()
16860                    {
16861                        row_highlights[ix].range.end = next_highlight.range.end;
16862                    }
16863                    row_highlights.remove(ix + 1);
16864                } else {
16865                    break;
16866                }
16867            }
16868        }
16869    }
16870
16871    /// Remove any highlighted row ranges of the given type that intersect the
16872    /// given ranges.
16873    pub fn remove_highlighted_rows<T: 'static>(
16874        &mut self,
16875        ranges_to_remove: Vec<Range<Anchor>>,
16876        cx: &mut Context<Self>,
16877    ) {
16878        let snapshot = self.buffer().read(cx).snapshot(cx);
16879        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16880        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16881        row_highlights.retain(|highlight| {
16882            while let Some(range_to_remove) = ranges_to_remove.peek() {
16883                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16884                    Ordering::Less | Ordering::Equal => {
16885                        ranges_to_remove.next();
16886                    }
16887                    Ordering::Greater => {
16888                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16889                            Ordering::Less | Ordering::Equal => {
16890                                return false;
16891                            }
16892                            Ordering::Greater => break,
16893                        }
16894                    }
16895                }
16896            }
16897
16898            true
16899        })
16900    }
16901
16902    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16903    pub fn clear_row_highlights<T: 'static>(&mut self) {
16904        self.highlighted_rows.remove(&TypeId::of::<T>());
16905    }
16906
16907    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
16908    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
16909        self.highlighted_rows
16910            .get(&TypeId::of::<T>())
16911            .map_or(&[] as &[_], |vec| vec.as_slice())
16912            .iter()
16913            .map(|highlight| (highlight.range.clone(), highlight.color))
16914    }
16915
16916    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
16917    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
16918    /// Allows to ignore certain kinds of highlights.
16919    pub fn highlighted_display_rows(
16920        &self,
16921        window: &mut Window,
16922        cx: &mut App,
16923    ) -> BTreeMap<DisplayRow, LineHighlight> {
16924        let snapshot = self.snapshot(window, cx);
16925        let mut used_highlight_orders = HashMap::default();
16926        self.highlighted_rows
16927            .iter()
16928            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16929            .fold(
16930                BTreeMap::<DisplayRow, LineHighlight>::new(),
16931                |mut unique_rows, highlight| {
16932                    let start = highlight.range.start.to_display_point(&snapshot);
16933                    let end = highlight.range.end.to_display_point(&snapshot);
16934                    let start_row = start.row().0;
16935                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16936                        && end.column() == 0
16937                    {
16938                        end.row().0.saturating_sub(1)
16939                    } else {
16940                        end.row().0
16941                    };
16942                    for row in start_row..=end_row {
16943                        let used_index =
16944                            used_highlight_orders.entry(row).or_insert(highlight.index);
16945                        if highlight.index >= *used_index {
16946                            *used_index = highlight.index;
16947                            unique_rows.insert(
16948                                DisplayRow(row),
16949                                LineHighlight {
16950                                    include_gutter: highlight.options.include_gutter,
16951                                    border: None,
16952                                    background: highlight.color.into(),
16953                                    type_id: Some(highlight.type_id),
16954                                },
16955                            );
16956                        }
16957                    }
16958                    unique_rows
16959                },
16960            )
16961    }
16962
16963    pub fn highlighted_display_row_for_autoscroll(
16964        &self,
16965        snapshot: &DisplaySnapshot,
16966    ) -> Option<DisplayRow> {
16967        self.highlighted_rows
16968            .values()
16969            .flat_map(|highlighted_rows| highlighted_rows.iter())
16970            .filter_map(|highlight| {
16971                if highlight.options.autoscroll {
16972                    Some(highlight.range.start.to_display_point(snapshot).row())
16973                } else {
16974                    None
16975                }
16976            })
16977            .min()
16978    }
16979
16980    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16981        self.highlight_background::<SearchWithinRange>(
16982            ranges,
16983            |colors| colors.editor_document_highlight_read_background,
16984            cx,
16985        )
16986    }
16987
16988    pub fn set_breadcrumb_header(&mut self, new_header: String) {
16989        self.breadcrumb_header = Some(new_header);
16990    }
16991
16992    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16993        self.clear_background_highlights::<SearchWithinRange>(cx);
16994    }
16995
16996    pub fn highlight_background<T: 'static>(
16997        &mut self,
16998        ranges: &[Range<Anchor>],
16999        color_fetcher: fn(&ThemeColors) -> Hsla,
17000        cx: &mut Context<Self>,
17001    ) {
17002        self.background_highlights
17003            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17004        self.scrollbar_marker_state.dirty = true;
17005        cx.notify();
17006    }
17007
17008    pub fn clear_background_highlights<T: 'static>(
17009        &mut self,
17010        cx: &mut Context<Self>,
17011    ) -> Option<BackgroundHighlight> {
17012        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
17013        if !text_highlights.1.is_empty() {
17014            self.scrollbar_marker_state.dirty = true;
17015            cx.notify();
17016        }
17017        Some(text_highlights)
17018    }
17019
17020    pub fn highlight_gutter<T: 'static>(
17021        &mut self,
17022        ranges: &[Range<Anchor>],
17023        color_fetcher: fn(&App) -> Hsla,
17024        cx: &mut Context<Self>,
17025    ) {
17026        self.gutter_highlights
17027            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17028        cx.notify();
17029    }
17030
17031    pub fn clear_gutter_highlights<T: 'static>(
17032        &mut self,
17033        cx: &mut Context<Self>,
17034    ) -> Option<GutterHighlight> {
17035        cx.notify();
17036        self.gutter_highlights.remove(&TypeId::of::<T>())
17037    }
17038
17039    #[cfg(feature = "test-support")]
17040    pub fn all_text_background_highlights(
17041        &self,
17042        window: &mut Window,
17043        cx: &mut Context<Self>,
17044    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17045        let snapshot = self.snapshot(window, cx);
17046        let buffer = &snapshot.buffer_snapshot;
17047        let start = buffer.anchor_before(0);
17048        let end = buffer.anchor_after(buffer.len());
17049        let theme = cx.theme().colors();
17050        self.background_highlights_in_range(start..end, &snapshot, theme)
17051    }
17052
17053    #[cfg(feature = "test-support")]
17054    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
17055        let snapshot = self.buffer().read(cx).snapshot(cx);
17056
17057        let highlights = self
17058            .background_highlights
17059            .get(&TypeId::of::<items::BufferSearchHighlights>());
17060
17061        if let Some((_color, ranges)) = highlights {
17062            ranges
17063                .iter()
17064                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
17065                .collect_vec()
17066        } else {
17067            vec![]
17068        }
17069    }
17070
17071    fn document_highlights_for_position<'a>(
17072        &'a self,
17073        position: Anchor,
17074        buffer: &'a MultiBufferSnapshot,
17075    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
17076        let read_highlights = self
17077            .background_highlights
17078            .get(&TypeId::of::<DocumentHighlightRead>())
17079            .map(|h| &h.1);
17080        let write_highlights = self
17081            .background_highlights
17082            .get(&TypeId::of::<DocumentHighlightWrite>())
17083            .map(|h| &h.1);
17084        let left_position = position.bias_left(buffer);
17085        let right_position = position.bias_right(buffer);
17086        read_highlights
17087            .into_iter()
17088            .chain(write_highlights)
17089            .flat_map(move |ranges| {
17090                let start_ix = match ranges.binary_search_by(|probe| {
17091                    let cmp = probe.end.cmp(&left_position, buffer);
17092                    if cmp.is_ge() {
17093                        Ordering::Greater
17094                    } else {
17095                        Ordering::Less
17096                    }
17097                }) {
17098                    Ok(i) | Err(i) => i,
17099                };
17100
17101                ranges[start_ix..]
17102                    .iter()
17103                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
17104            })
17105    }
17106
17107    pub fn has_background_highlights<T: 'static>(&self) -> bool {
17108        self.background_highlights
17109            .get(&TypeId::of::<T>())
17110            .map_or(false, |(_, highlights)| !highlights.is_empty())
17111    }
17112
17113    pub fn background_highlights_in_range(
17114        &self,
17115        search_range: Range<Anchor>,
17116        display_snapshot: &DisplaySnapshot,
17117        theme: &ThemeColors,
17118    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17119        let mut results = Vec::new();
17120        for (color_fetcher, ranges) in self.background_highlights.values() {
17121            let color = color_fetcher(theme);
17122            let start_ix = match ranges.binary_search_by(|probe| {
17123                let cmp = probe
17124                    .end
17125                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17126                if cmp.is_gt() {
17127                    Ordering::Greater
17128                } else {
17129                    Ordering::Less
17130                }
17131            }) {
17132                Ok(i) | Err(i) => i,
17133            };
17134            for range in &ranges[start_ix..] {
17135                if range
17136                    .start
17137                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17138                    .is_ge()
17139                {
17140                    break;
17141                }
17142
17143                let start = range.start.to_display_point(display_snapshot);
17144                let end = range.end.to_display_point(display_snapshot);
17145                results.push((start..end, color))
17146            }
17147        }
17148        results
17149    }
17150
17151    pub fn background_highlight_row_ranges<T: 'static>(
17152        &self,
17153        search_range: Range<Anchor>,
17154        display_snapshot: &DisplaySnapshot,
17155        count: usize,
17156    ) -> Vec<RangeInclusive<DisplayPoint>> {
17157        let mut results = Vec::new();
17158        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
17159            return vec![];
17160        };
17161
17162        let start_ix = match ranges.binary_search_by(|probe| {
17163            let cmp = probe
17164                .end
17165                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17166            if cmp.is_gt() {
17167                Ordering::Greater
17168            } else {
17169                Ordering::Less
17170            }
17171        }) {
17172            Ok(i) | Err(i) => i,
17173        };
17174        let mut push_region = |start: Option<Point>, end: Option<Point>| {
17175            if let (Some(start_display), Some(end_display)) = (start, end) {
17176                results.push(
17177                    start_display.to_display_point(display_snapshot)
17178                        ..=end_display.to_display_point(display_snapshot),
17179                );
17180            }
17181        };
17182        let mut start_row: Option<Point> = None;
17183        let mut end_row: Option<Point> = None;
17184        if ranges.len() > count {
17185            return Vec::new();
17186        }
17187        for range in &ranges[start_ix..] {
17188            if range
17189                .start
17190                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17191                .is_ge()
17192            {
17193                break;
17194            }
17195            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
17196            if let Some(current_row) = &end_row {
17197                if end.row == current_row.row {
17198                    continue;
17199                }
17200            }
17201            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17202            if start_row.is_none() {
17203                assert_eq!(end_row, None);
17204                start_row = Some(start);
17205                end_row = Some(end);
17206                continue;
17207            }
17208            if let Some(current_end) = end_row.as_mut() {
17209                if start.row > current_end.row + 1 {
17210                    push_region(start_row, end_row);
17211                    start_row = Some(start);
17212                    end_row = Some(end);
17213                } else {
17214                    // Merge two hunks.
17215                    *current_end = end;
17216                }
17217            } else {
17218                unreachable!();
17219            }
17220        }
17221        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17222        push_region(start_row, end_row);
17223        results
17224    }
17225
17226    pub fn gutter_highlights_in_range(
17227        &self,
17228        search_range: Range<Anchor>,
17229        display_snapshot: &DisplaySnapshot,
17230        cx: &App,
17231    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17232        let mut results = Vec::new();
17233        for (color_fetcher, ranges) in self.gutter_highlights.values() {
17234            let color = color_fetcher(cx);
17235            let start_ix = match ranges.binary_search_by(|probe| {
17236                let cmp = probe
17237                    .end
17238                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17239                if cmp.is_gt() {
17240                    Ordering::Greater
17241                } else {
17242                    Ordering::Less
17243                }
17244            }) {
17245                Ok(i) | Err(i) => i,
17246            };
17247            for range in &ranges[start_ix..] {
17248                if range
17249                    .start
17250                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17251                    .is_ge()
17252                {
17253                    break;
17254                }
17255
17256                let start = range.start.to_display_point(display_snapshot);
17257                let end = range.end.to_display_point(display_snapshot);
17258                results.push((start..end, color))
17259            }
17260        }
17261        results
17262    }
17263
17264    /// Get the text ranges corresponding to the redaction query
17265    pub fn redacted_ranges(
17266        &self,
17267        search_range: Range<Anchor>,
17268        display_snapshot: &DisplaySnapshot,
17269        cx: &App,
17270    ) -> Vec<Range<DisplayPoint>> {
17271        display_snapshot
17272            .buffer_snapshot
17273            .redacted_ranges(search_range, |file| {
17274                if let Some(file) = file {
17275                    file.is_private()
17276                        && EditorSettings::get(
17277                            Some(SettingsLocation {
17278                                worktree_id: file.worktree_id(cx),
17279                                path: file.path().as_ref(),
17280                            }),
17281                            cx,
17282                        )
17283                        .redact_private_values
17284                } else {
17285                    false
17286                }
17287            })
17288            .map(|range| {
17289                range.start.to_display_point(display_snapshot)
17290                    ..range.end.to_display_point(display_snapshot)
17291            })
17292            .collect()
17293    }
17294
17295    pub fn highlight_text<T: 'static>(
17296        &mut self,
17297        ranges: Vec<Range<Anchor>>,
17298        style: HighlightStyle,
17299        cx: &mut Context<Self>,
17300    ) {
17301        self.display_map.update(cx, |map, _| {
17302            map.highlight_text(TypeId::of::<T>(), ranges, style)
17303        });
17304        cx.notify();
17305    }
17306
17307    pub(crate) fn highlight_inlays<T: 'static>(
17308        &mut self,
17309        highlights: Vec<InlayHighlight>,
17310        style: HighlightStyle,
17311        cx: &mut Context<Self>,
17312    ) {
17313        self.display_map.update(cx, |map, _| {
17314            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17315        });
17316        cx.notify();
17317    }
17318
17319    pub fn text_highlights<'a, T: 'static>(
17320        &'a self,
17321        cx: &'a App,
17322    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17323        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17324    }
17325
17326    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17327        let cleared = self
17328            .display_map
17329            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17330        if cleared {
17331            cx.notify();
17332        }
17333    }
17334
17335    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17336        (self.read_only(cx) || self.blink_manager.read(cx).visible())
17337            && self.focus_handle.is_focused(window)
17338    }
17339
17340    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17341        self.show_cursor_when_unfocused = is_enabled;
17342        cx.notify();
17343    }
17344
17345    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17346        cx.notify();
17347    }
17348
17349    fn on_buffer_event(
17350        &mut self,
17351        multibuffer: &Entity<MultiBuffer>,
17352        event: &multi_buffer::Event,
17353        window: &mut Window,
17354        cx: &mut Context<Self>,
17355    ) {
17356        match event {
17357            multi_buffer::Event::Edited {
17358                singleton_buffer_edited,
17359                edited_buffer: buffer_edited,
17360            } => {
17361                self.scrollbar_marker_state.dirty = true;
17362                self.active_indent_guides_state.dirty = true;
17363                self.refresh_active_diagnostics(cx);
17364                self.refresh_code_actions(window, cx);
17365                if self.has_active_inline_completion() {
17366                    self.update_visible_inline_completion(window, cx);
17367                }
17368                if let Some(buffer) = buffer_edited {
17369                    let buffer_id = buffer.read(cx).remote_id();
17370                    if !self.registered_buffers.contains_key(&buffer_id) {
17371                        if let Some(project) = self.project.as_ref() {
17372                            project.update(cx, |project, cx| {
17373                                self.registered_buffers.insert(
17374                                    buffer_id,
17375                                    project.register_buffer_with_language_servers(&buffer, cx),
17376                                );
17377                            })
17378                        }
17379                    }
17380                }
17381                cx.emit(EditorEvent::BufferEdited);
17382                cx.emit(SearchEvent::MatchesInvalidated);
17383                if *singleton_buffer_edited {
17384                    if let Some(project) = &self.project {
17385                        #[allow(clippy::mutable_key_type)]
17386                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17387                            multibuffer
17388                                .all_buffers()
17389                                .into_iter()
17390                                .filter_map(|buffer| {
17391                                    buffer.update(cx, |buffer, cx| {
17392                                        let language = buffer.language()?;
17393                                        let should_discard = project.update(cx, |project, cx| {
17394                                            project.is_local()
17395                                                && !project.has_language_servers_for(buffer, cx)
17396                                        });
17397                                        should_discard.not().then_some(language.clone())
17398                                    })
17399                                })
17400                                .collect::<HashSet<_>>()
17401                        });
17402                        if !languages_affected.is_empty() {
17403                            self.refresh_inlay_hints(
17404                                InlayHintRefreshReason::BufferEdited(languages_affected),
17405                                cx,
17406                            );
17407                        }
17408                    }
17409                }
17410
17411                let Some(project) = &self.project else { return };
17412                let (telemetry, is_via_ssh) = {
17413                    let project = project.read(cx);
17414                    let telemetry = project.client().telemetry().clone();
17415                    let is_via_ssh = project.is_via_ssh();
17416                    (telemetry, is_via_ssh)
17417                };
17418                refresh_linked_ranges(self, window, cx);
17419                telemetry.log_edit_event("editor", is_via_ssh);
17420            }
17421            multi_buffer::Event::ExcerptsAdded {
17422                buffer,
17423                predecessor,
17424                excerpts,
17425            } => {
17426                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17427                let buffer_id = buffer.read(cx).remote_id();
17428                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17429                    if let Some(project) = &self.project {
17430                        get_uncommitted_diff_for_buffer(
17431                            project,
17432                            [buffer.clone()],
17433                            self.buffer.clone(),
17434                            cx,
17435                        )
17436                        .detach();
17437                    }
17438                }
17439                cx.emit(EditorEvent::ExcerptsAdded {
17440                    buffer: buffer.clone(),
17441                    predecessor: *predecessor,
17442                    excerpts: excerpts.clone(),
17443                });
17444                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17445            }
17446            multi_buffer::Event::ExcerptsRemoved {
17447                ids,
17448                removed_buffer_ids,
17449            } => {
17450                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17451                let buffer = self.buffer.read(cx);
17452                self.registered_buffers
17453                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17454                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17455                cx.emit(EditorEvent::ExcerptsRemoved {
17456                    ids: ids.clone(),
17457                    removed_buffer_ids: removed_buffer_ids.clone(),
17458                })
17459            }
17460            multi_buffer::Event::ExcerptsEdited {
17461                excerpt_ids,
17462                buffer_ids,
17463            } => {
17464                self.display_map.update(cx, |map, cx| {
17465                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
17466                });
17467                cx.emit(EditorEvent::ExcerptsEdited {
17468                    ids: excerpt_ids.clone(),
17469                })
17470            }
17471            multi_buffer::Event::ExcerptsExpanded { ids } => {
17472                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17473                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17474            }
17475            multi_buffer::Event::Reparsed(buffer_id) => {
17476                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17477                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17478
17479                cx.emit(EditorEvent::Reparsed(*buffer_id));
17480            }
17481            multi_buffer::Event::DiffHunksToggled => {
17482                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17483            }
17484            multi_buffer::Event::LanguageChanged(buffer_id) => {
17485                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17486                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17487                cx.emit(EditorEvent::Reparsed(*buffer_id));
17488                cx.notify();
17489            }
17490            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17491            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17492            multi_buffer::Event::FileHandleChanged
17493            | multi_buffer::Event::Reloaded
17494            | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17495            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17496            multi_buffer::Event::DiagnosticsUpdated => {
17497                self.refresh_active_diagnostics(cx);
17498                self.refresh_inline_diagnostics(true, window, cx);
17499                self.scrollbar_marker_state.dirty = true;
17500                cx.notify();
17501            }
17502            _ => {}
17503        };
17504    }
17505
17506    fn on_display_map_changed(
17507        &mut self,
17508        _: Entity<DisplayMap>,
17509        _: &mut Window,
17510        cx: &mut Context<Self>,
17511    ) {
17512        cx.notify();
17513    }
17514
17515    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17516        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17517        self.update_edit_prediction_settings(cx);
17518        self.refresh_inline_completion(true, false, window, cx);
17519        self.refresh_inlay_hints(
17520            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17521                self.selections.newest_anchor().head(),
17522                &self.buffer.read(cx).snapshot(cx),
17523                cx,
17524            )),
17525            cx,
17526        );
17527
17528        let old_cursor_shape = self.cursor_shape;
17529
17530        {
17531            let editor_settings = EditorSettings::get_global(cx);
17532            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17533            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17534            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17535            self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17536        }
17537
17538        if old_cursor_shape != self.cursor_shape {
17539            cx.emit(EditorEvent::CursorShapeChanged);
17540        }
17541
17542        let project_settings = ProjectSettings::get_global(cx);
17543        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17544
17545        if self.mode.is_full() {
17546            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17547            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17548            if self.show_inline_diagnostics != show_inline_diagnostics {
17549                self.show_inline_diagnostics = show_inline_diagnostics;
17550                self.refresh_inline_diagnostics(false, window, cx);
17551            }
17552
17553            if self.git_blame_inline_enabled != inline_blame_enabled {
17554                self.toggle_git_blame_inline_internal(false, window, cx);
17555            }
17556        }
17557
17558        cx.notify();
17559    }
17560
17561    pub fn set_searchable(&mut self, searchable: bool) {
17562        self.searchable = searchable;
17563    }
17564
17565    pub fn searchable(&self) -> bool {
17566        self.searchable
17567    }
17568
17569    fn open_proposed_changes_editor(
17570        &mut self,
17571        _: &OpenProposedChangesEditor,
17572        window: &mut Window,
17573        cx: &mut Context<Self>,
17574    ) {
17575        let Some(workspace) = self.workspace() else {
17576            cx.propagate();
17577            return;
17578        };
17579
17580        let selections = self.selections.all::<usize>(cx);
17581        let multi_buffer = self.buffer.read(cx);
17582        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17583        let mut new_selections_by_buffer = HashMap::default();
17584        for selection in selections {
17585            for (buffer, range, _) in
17586                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17587            {
17588                let mut range = range.to_point(buffer);
17589                range.start.column = 0;
17590                range.end.column = buffer.line_len(range.end.row);
17591                new_selections_by_buffer
17592                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17593                    .or_insert(Vec::new())
17594                    .push(range)
17595            }
17596        }
17597
17598        let proposed_changes_buffers = new_selections_by_buffer
17599            .into_iter()
17600            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17601            .collect::<Vec<_>>();
17602        let proposed_changes_editor = cx.new(|cx| {
17603            ProposedChangesEditor::new(
17604                "Proposed changes",
17605                proposed_changes_buffers,
17606                self.project.clone(),
17607                window,
17608                cx,
17609            )
17610        });
17611
17612        window.defer(cx, move |window, cx| {
17613            workspace.update(cx, |workspace, cx| {
17614                workspace.active_pane().update(cx, |pane, cx| {
17615                    pane.add_item(
17616                        Box::new(proposed_changes_editor),
17617                        true,
17618                        true,
17619                        None,
17620                        window,
17621                        cx,
17622                    );
17623                });
17624            });
17625        });
17626    }
17627
17628    pub fn open_excerpts_in_split(
17629        &mut self,
17630        _: &OpenExcerptsSplit,
17631        window: &mut Window,
17632        cx: &mut Context<Self>,
17633    ) {
17634        self.open_excerpts_common(None, true, window, cx)
17635    }
17636
17637    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
17638        self.open_excerpts_common(None, false, window, cx)
17639    }
17640
17641    fn open_excerpts_common(
17642        &mut self,
17643        jump_data: Option<JumpData>,
17644        split: bool,
17645        window: &mut Window,
17646        cx: &mut Context<Self>,
17647    ) {
17648        let Some(workspace) = self.workspace() else {
17649            cx.propagate();
17650            return;
17651        };
17652
17653        if self.buffer.read(cx).is_singleton() {
17654            cx.propagate();
17655            return;
17656        }
17657
17658        let mut new_selections_by_buffer = HashMap::default();
17659        match &jump_data {
17660            Some(JumpData::MultiBufferPoint {
17661                excerpt_id,
17662                position,
17663                anchor,
17664                line_offset_from_top,
17665            }) => {
17666                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
17667                if let Some(buffer) = multi_buffer_snapshot
17668                    .buffer_id_for_excerpt(*excerpt_id)
17669                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
17670                {
17671                    let buffer_snapshot = buffer.read(cx).snapshot();
17672                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
17673                        language::ToPoint::to_point(anchor, &buffer_snapshot)
17674                    } else {
17675                        buffer_snapshot.clip_point(*position, Bias::Left)
17676                    };
17677                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
17678                    new_selections_by_buffer.insert(
17679                        buffer,
17680                        (
17681                            vec![jump_to_offset..jump_to_offset],
17682                            Some(*line_offset_from_top),
17683                        ),
17684                    );
17685                }
17686            }
17687            Some(JumpData::MultiBufferRow {
17688                row,
17689                line_offset_from_top,
17690            }) => {
17691                let point = MultiBufferPoint::new(row.0, 0);
17692                if let Some((buffer, buffer_point, _)) =
17693                    self.buffer.read(cx).point_to_buffer_point(point, cx)
17694                {
17695                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
17696                    new_selections_by_buffer
17697                        .entry(buffer)
17698                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
17699                        .0
17700                        .push(buffer_offset..buffer_offset)
17701                }
17702            }
17703            None => {
17704                let selections = self.selections.all::<usize>(cx);
17705                let multi_buffer = self.buffer.read(cx);
17706                for selection in selections {
17707                    for (snapshot, range, _, anchor) in multi_buffer
17708                        .snapshot(cx)
17709                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
17710                    {
17711                        if let Some(anchor) = anchor {
17712                            // selection is in a deleted hunk
17713                            let Some(buffer_id) = anchor.buffer_id else {
17714                                continue;
17715                            };
17716                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
17717                                continue;
17718                            };
17719                            let offset = text::ToOffset::to_offset(
17720                                &anchor.text_anchor,
17721                                &buffer_handle.read(cx).snapshot(),
17722                            );
17723                            let range = offset..offset;
17724                            new_selections_by_buffer
17725                                .entry(buffer_handle)
17726                                .or_insert((Vec::new(), None))
17727                                .0
17728                                .push(range)
17729                        } else {
17730                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
17731                            else {
17732                                continue;
17733                            };
17734                            new_selections_by_buffer
17735                                .entry(buffer_handle)
17736                                .or_insert((Vec::new(), None))
17737                                .0
17738                                .push(range)
17739                        }
17740                    }
17741                }
17742            }
17743        }
17744
17745        new_selections_by_buffer
17746            .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
17747
17748        if new_selections_by_buffer.is_empty() {
17749            return;
17750        }
17751
17752        // We defer the pane interaction because we ourselves are a workspace item
17753        // and activating a new item causes the pane to call a method on us reentrantly,
17754        // which panics if we're on the stack.
17755        window.defer(cx, move |window, cx| {
17756            workspace.update(cx, |workspace, cx| {
17757                let pane = if split {
17758                    workspace.adjacent_pane(window, cx)
17759                } else {
17760                    workspace.active_pane().clone()
17761                };
17762
17763                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
17764                    let editor = buffer
17765                        .read(cx)
17766                        .file()
17767                        .is_none()
17768                        .then(|| {
17769                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
17770                            // so `workspace.open_project_item` will never find them, always opening a new editor.
17771                            // Instead, we try to activate the existing editor in the pane first.
17772                            let (editor, pane_item_index) =
17773                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
17774                                    let editor = item.downcast::<Editor>()?;
17775                                    let singleton_buffer =
17776                                        editor.read(cx).buffer().read(cx).as_singleton()?;
17777                                    if singleton_buffer == buffer {
17778                                        Some((editor, i))
17779                                    } else {
17780                                        None
17781                                    }
17782                                })?;
17783                            pane.update(cx, |pane, cx| {
17784                                pane.activate_item(pane_item_index, true, true, window, cx)
17785                            });
17786                            Some(editor)
17787                        })
17788                        .flatten()
17789                        .unwrap_or_else(|| {
17790                            workspace.open_project_item::<Self>(
17791                                pane.clone(),
17792                                buffer,
17793                                true,
17794                                true,
17795                                window,
17796                                cx,
17797                            )
17798                        });
17799
17800                    editor.update(cx, |editor, cx| {
17801                        let autoscroll = match scroll_offset {
17802                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
17803                            None => Autoscroll::newest(),
17804                        };
17805                        let nav_history = editor.nav_history.take();
17806                        editor.change_selections(Some(autoscroll), window, cx, |s| {
17807                            s.select_ranges(ranges);
17808                        });
17809                        editor.nav_history = nav_history;
17810                    });
17811                }
17812            })
17813        });
17814    }
17815
17816    // For now, don't allow opening excerpts in buffers that aren't backed by
17817    // regular project files.
17818    fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
17819        file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
17820    }
17821
17822    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
17823        let snapshot = self.buffer.read(cx).read(cx);
17824        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
17825        Some(
17826            ranges
17827                .iter()
17828                .map(move |range| {
17829                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
17830                })
17831                .collect(),
17832        )
17833    }
17834
17835    fn selection_replacement_ranges(
17836        &self,
17837        range: Range<OffsetUtf16>,
17838        cx: &mut App,
17839    ) -> Vec<Range<OffsetUtf16>> {
17840        let selections = self.selections.all::<OffsetUtf16>(cx);
17841        let newest_selection = selections
17842            .iter()
17843            .max_by_key(|selection| selection.id)
17844            .unwrap();
17845        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
17846        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
17847        let snapshot = self.buffer.read(cx).read(cx);
17848        selections
17849            .into_iter()
17850            .map(|mut selection| {
17851                selection.start.0 =
17852                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
17853                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
17854                snapshot.clip_offset_utf16(selection.start, Bias::Left)
17855                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
17856            })
17857            .collect()
17858    }
17859
17860    fn report_editor_event(
17861        &self,
17862        event_type: &'static str,
17863        file_extension: Option<String>,
17864        cx: &App,
17865    ) {
17866        if cfg!(any(test, feature = "test-support")) {
17867            return;
17868        }
17869
17870        let Some(project) = &self.project else { return };
17871
17872        // If None, we are in a file without an extension
17873        let file = self
17874            .buffer
17875            .read(cx)
17876            .as_singleton()
17877            .and_then(|b| b.read(cx).file());
17878        let file_extension = file_extension.or(file
17879            .as_ref()
17880            .and_then(|file| Path::new(file.file_name(cx)).extension())
17881            .and_then(|e| e.to_str())
17882            .map(|a| a.to_string()));
17883
17884        let vim_mode = vim_enabled(cx);
17885
17886        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
17887        let copilot_enabled = edit_predictions_provider
17888            == language::language_settings::EditPredictionProvider::Copilot;
17889        let copilot_enabled_for_language = self
17890            .buffer
17891            .read(cx)
17892            .language_settings(cx)
17893            .show_edit_predictions;
17894
17895        let project = project.read(cx);
17896        telemetry::event!(
17897            event_type,
17898            file_extension,
17899            vim_mode,
17900            copilot_enabled,
17901            copilot_enabled_for_language,
17902            edit_predictions_provider,
17903            is_via_ssh = project.is_via_ssh(),
17904        );
17905    }
17906
17907    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
17908    /// with each line being an array of {text, highlight} objects.
17909    fn copy_highlight_json(
17910        &mut self,
17911        _: &CopyHighlightJson,
17912        window: &mut Window,
17913        cx: &mut Context<Self>,
17914    ) {
17915        #[derive(Serialize)]
17916        struct Chunk<'a> {
17917            text: String,
17918            highlight: Option<&'a str>,
17919        }
17920
17921        let snapshot = self.buffer.read(cx).snapshot(cx);
17922        let range = self
17923            .selected_text_range(false, window, cx)
17924            .and_then(|selection| {
17925                if selection.range.is_empty() {
17926                    None
17927                } else {
17928                    Some(selection.range)
17929                }
17930            })
17931            .unwrap_or_else(|| 0..snapshot.len());
17932
17933        let chunks = snapshot.chunks(range, true);
17934        let mut lines = Vec::new();
17935        let mut line: VecDeque<Chunk> = VecDeque::new();
17936
17937        let Some(style) = self.style.as_ref() else {
17938            return;
17939        };
17940
17941        for chunk in chunks {
17942            let highlight = chunk
17943                .syntax_highlight_id
17944                .and_then(|id| id.name(&style.syntax));
17945            let mut chunk_lines = chunk.text.split('\n').peekable();
17946            while let Some(text) = chunk_lines.next() {
17947                let mut merged_with_last_token = false;
17948                if let Some(last_token) = line.back_mut() {
17949                    if last_token.highlight == highlight {
17950                        last_token.text.push_str(text);
17951                        merged_with_last_token = true;
17952                    }
17953                }
17954
17955                if !merged_with_last_token {
17956                    line.push_back(Chunk {
17957                        text: text.into(),
17958                        highlight,
17959                    });
17960                }
17961
17962                if chunk_lines.peek().is_some() {
17963                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
17964                        line.pop_front();
17965                    }
17966                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
17967                        line.pop_back();
17968                    }
17969
17970                    lines.push(mem::take(&mut line));
17971                }
17972            }
17973        }
17974
17975        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17976            return;
17977        };
17978        cx.write_to_clipboard(ClipboardItem::new_string(lines));
17979    }
17980
17981    pub fn open_context_menu(
17982        &mut self,
17983        _: &OpenContextMenu,
17984        window: &mut Window,
17985        cx: &mut Context<Self>,
17986    ) {
17987        self.request_autoscroll(Autoscroll::newest(), cx);
17988        let position = self.selections.newest_display(cx).start;
17989        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17990    }
17991
17992    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17993        &self.inlay_hint_cache
17994    }
17995
17996    pub fn replay_insert_event(
17997        &mut self,
17998        text: &str,
17999        relative_utf16_range: Option<Range<isize>>,
18000        window: &mut Window,
18001        cx: &mut Context<Self>,
18002    ) {
18003        if !self.input_enabled {
18004            cx.emit(EditorEvent::InputIgnored { text: text.into() });
18005            return;
18006        }
18007        if let Some(relative_utf16_range) = relative_utf16_range {
18008            let selections = self.selections.all::<OffsetUtf16>(cx);
18009            self.change_selections(None, window, cx, |s| {
18010                let new_ranges = selections.into_iter().map(|range| {
18011                    let start = OffsetUtf16(
18012                        range
18013                            .head()
18014                            .0
18015                            .saturating_add_signed(relative_utf16_range.start),
18016                    );
18017                    let end = OffsetUtf16(
18018                        range
18019                            .head()
18020                            .0
18021                            .saturating_add_signed(relative_utf16_range.end),
18022                    );
18023                    start..end
18024                });
18025                s.select_ranges(new_ranges);
18026            });
18027        }
18028
18029        self.handle_input(text, window, cx);
18030    }
18031
18032    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
18033        let Some(provider) = self.semantics_provider.as_ref() else {
18034            return false;
18035        };
18036
18037        let mut supports = false;
18038        self.buffer().update(cx, |this, cx| {
18039            this.for_each_buffer(|buffer| {
18040                supports |= provider.supports_inlay_hints(buffer, cx);
18041            });
18042        });
18043
18044        supports
18045    }
18046
18047    pub fn is_focused(&self, window: &Window) -> bool {
18048        self.focus_handle.is_focused(window)
18049    }
18050
18051    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18052        cx.emit(EditorEvent::Focused);
18053
18054        if let Some(descendant) = self
18055            .last_focused_descendant
18056            .take()
18057            .and_then(|descendant| descendant.upgrade())
18058        {
18059            window.focus(&descendant);
18060        } else {
18061            if let Some(blame) = self.blame.as_ref() {
18062                blame.update(cx, GitBlame::focus)
18063            }
18064
18065            self.blink_manager.update(cx, BlinkManager::enable);
18066            self.show_cursor_names(window, cx);
18067            self.buffer.update(cx, |buffer, cx| {
18068                buffer.finalize_last_transaction(cx);
18069                if self.leader_peer_id.is_none() {
18070                    buffer.set_active_selections(
18071                        &self.selections.disjoint_anchors(),
18072                        self.selections.line_mode,
18073                        self.cursor_shape,
18074                        cx,
18075                    );
18076                }
18077            });
18078        }
18079    }
18080
18081    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
18082        cx.emit(EditorEvent::FocusedIn)
18083    }
18084
18085    fn handle_focus_out(
18086        &mut self,
18087        event: FocusOutEvent,
18088        _window: &mut Window,
18089        cx: &mut Context<Self>,
18090    ) {
18091        if event.blurred != self.focus_handle {
18092            self.last_focused_descendant = Some(event.blurred);
18093        }
18094        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
18095    }
18096
18097    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18098        self.blink_manager.update(cx, BlinkManager::disable);
18099        self.buffer
18100            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
18101
18102        if let Some(blame) = self.blame.as_ref() {
18103            blame.update(cx, GitBlame::blur)
18104        }
18105        if !self.hover_state.focused(window, cx) {
18106            hide_hover(self, cx);
18107        }
18108        if !self
18109            .context_menu
18110            .borrow()
18111            .as_ref()
18112            .is_some_and(|context_menu| context_menu.focused(window, cx))
18113        {
18114            self.hide_context_menu(window, cx);
18115        }
18116        self.discard_inline_completion(false, cx);
18117        cx.emit(EditorEvent::Blurred);
18118        cx.notify();
18119    }
18120
18121    pub fn register_action<A: Action>(
18122        &mut self,
18123        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
18124    ) -> Subscription {
18125        let id = self.next_editor_action_id.post_inc();
18126        let listener = Arc::new(listener);
18127        self.editor_actions.borrow_mut().insert(
18128            id,
18129            Box::new(move |window, _| {
18130                let listener = listener.clone();
18131                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
18132                    let action = action.downcast_ref().unwrap();
18133                    if phase == DispatchPhase::Bubble {
18134                        listener(action, window, cx)
18135                    }
18136                })
18137            }),
18138        );
18139
18140        let editor_actions = self.editor_actions.clone();
18141        Subscription::new(move || {
18142            editor_actions.borrow_mut().remove(&id);
18143        })
18144    }
18145
18146    pub fn file_header_size(&self) -> u32 {
18147        FILE_HEADER_HEIGHT
18148    }
18149
18150    pub fn restore(
18151        &mut self,
18152        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
18153        window: &mut Window,
18154        cx: &mut Context<Self>,
18155    ) {
18156        let workspace = self.workspace();
18157        let project = self.project.as_ref();
18158        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
18159            let mut tasks = Vec::new();
18160            for (buffer_id, changes) in revert_changes {
18161                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
18162                    buffer.update(cx, |buffer, cx| {
18163                        buffer.edit(
18164                            changes
18165                                .into_iter()
18166                                .map(|(range, text)| (range, text.to_string())),
18167                            None,
18168                            cx,
18169                        );
18170                    });
18171
18172                    if let Some(project) =
18173                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
18174                    {
18175                        project.update(cx, |project, cx| {
18176                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
18177                        })
18178                    }
18179                }
18180            }
18181            tasks
18182        });
18183        cx.spawn_in(window, async move |_, cx| {
18184            for (buffer, task) in save_tasks {
18185                let result = task.await;
18186                if result.is_err() {
18187                    let Some(path) = buffer
18188                        .read_with(cx, |buffer, cx| buffer.project_path(cx))
18189                        .ok()
18190                    else {
18191                        continue;
18192                    };
18193                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
18194                        let Some(task) = cx
18195                            .update_window_entity(&workspace, |workspace, window, cx| {
18196                                workspace
18197                                    .open_path_preview(path, None, false, false, false, window, cx)
18198                            })
18199                            .ok()
18200                        else {
18201                            continue;
18202                        };
18203                        task.await.log_err();
18204                    }
18205                }
18206            }
18207        })
18208        .detach();
18209        self.change_selections(None, window, cx, |selections| selections.refresh());
18210    }
18211
18212    pub fn to_pixel_point(
18213        &self,
18214        source: multi_buffer::Anchor,
18215        editor_snapshot: &EditorSnapshot,
18216        window: &mut Window,
18217    ) -> Option<gpui::Point<Pixels>> {
18218        let source_point = source.to_display_point(editor_snapshot);
18219        self.display_to_pixel_point(source_point, editor_snapshot, window)
18220    }
18221
18222    pub fn display_to_pixel_point(
18223        &self,
18224        source: DisplayPoint,
18225        editor_snapshot: &EditorSnapshot,
18226        window: &mut Window,
18227    ) -> Option<gpui::Point<Pixels>> {
18228        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18229        let text_layout_details = self.text_layout_details(window);
18230        let scroll_top = text_layout_details
18231            .scroll_anchor
18232            .scroll_position(editor_snapshot)
18233            .y;
18234
18235        if source.row().as_f32() < scroll_top.floor() {
18236            return None;
18237        }
18238        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18239        let source_y = line_height * (source.row().as_f32() - scroll_top);
18240        Some(gpui::Point::new(source_x, source_y))
18241    }
18242
18243    pub fn has_visible_completions_menu(&self) -> bool {
18244        !self.edit_prediction_preview_is_active()
18245            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18246                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18247            })
18248    }
18249
18250    pub fn register_addon<T: Addon>(&mut self, instance: T) {
18251        self.addons
18252            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18253    }
18254
18255    pub fn unregister_addon<T: Addon>(&mut self) {
18256        self.addons.remove(&std::any::TypeId::of::<T>());
18257    }
18258
18259    pub fn addon<T: Addon>(&self) -> Option<&T> {
18260        let type_id = std::any::TypeId::of::<T>();
18261        self.addons
18262            .get(&type_id)
18263            .and_then(|item| item.to_any().downcast_ref::<T>())
18264    }
18265
18266    pub fn addon_mut<T: Addon>(&mut self) -> Option<&mut T> {
18267        let type_id = std::any::TypeId::of::<T>();
18268        self.addons
18269            .get_mut(&type_id)
18270            .and_then(|item| item.to_any_mut()?.downcast_mut::<T>())
18271    }
18272
18273    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18274        let text_layout_details = self.text_layout_details(window);
18275        let style = &text_layout_details.editor_style;
18276        let font_id = window.text_system().resolve_font(&style.text.font());
18277        let font_size = style.text.font_size.to_pixels(window.rem_size());
18278        let line_height = style.text.line_height_in_pixels(window.rem_size());
18279        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18280
18281        gpui::Size::new(em_width, line_height)
18282    }
18283
18284    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18285        self.load_diff_task.clone()
18286    }
18287
18288    fn read_metadata_from_db(
18289        &mut self,
18290        item_id: u64,
18291        workspace_id: WorkspaceId,
18292        window: &mut Window,
18293        cx: &mut Context<Editor>,
18294    ) {
18295        if self.is_singleton(cx)
18296            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18297        {
18298            let buffer_snapshot = OnceCell::new();
18299
18300            if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18301                if !folds.is_empty() {
18302                    let snapshot =
18303                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18304                    self.fold_ranges(
18305                        folds
18306                            .into_iter()
18307                            .map(|(start, end)| {
18308                                snapshot.clip_offset(start, Bias::Left)
18309                                    ..snapshot.clip_offset(end, Bias::Right)
18310                            })
18311                            .collect(),
18312                        false,
18313                        window,
18314                        cx,
18315                    );
18316                }
18317            }
18318
18319            if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18320                if !selections.is_empty() {
18321                    let snapshot =
18322                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18323                    self.change_selections(None, window, cx, |s| {
18324                        s.select_ranges(selections.into_iter().map(|(start, end)| {
18325                            snapshot.clip_offset(start, Bias::Left)
18326                                ..snapshot.clip_offset(end, Bias::Right)
18327                        }));
18328                    });
18329                }
18330            };
18331        }
18332
18333        self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18334    }
18335}
18336
18337fn vim_enabled(cx: &App) -> bool {
18338    cx.global::<SettingsStore>()
18339        .raw_user_settings()
18340        .get("vim_mode")
18341        == Some(&serde_json::Value::Bool(true))
18342}
18343
18344// Consider user intent and default settings
18345fn choose_completion_range(
18346    completion: &Completion,
18347    intent: CompletionIntent,
18348    buffer: &Entity<Buffer>,
18349    cx: &mut Context<Editor>,
18350) -> Range<usize> {
18351    fn should_replace(
18352        completion: &Completion,
18353        insert_range: &Range<text::Anchor>,
18354        intent: CompletionIntent,
18355        completion_mode_setting: LspInsertMode,
18356        buffer: &Buffer,
18357    ) -> bool {
18358        // specific actions take precedence over settings
18359        match intent {
18360            CompletionIntent::CompleteWithInsert => return false,
18361            CompletionIntent::CompleteWithReplace => return true,
18362            CompletionIntent::Complete | CompletionIntent::Compose => {}
18363        }
18364
18365        match completion_mode_setting {
18366            LspInsertMode::Insert => false,
18367            LspInsertMode::Replace => true,
18368            LspInsertMode::ReplaceSubsequence => {
18369                let mut text_to_replace = buffer.chars_for_range(
18370                    buffer.anchor_before(completion.replace_range.start)
18371                        ..buffer.anchor_after(completion.replace_range.end),
18372                );
18373                let mut completion_text = completion.new_text.chars();
18374
18375                // is `text_to_replace` a subsequence of `completion_text`
18376                text_to_replace
18377                    .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18378            }
18379            LspInsertMode::ReplaceSuffix => {
18380                let range_after_cursor = insert_range.end..completion.replace_range.end;
18381
18382                let text_after_cursor = buffer
18383                    .text_for_range(
18384                        buffer.anchor_before(range_after_cursor.start)
18385                            ..buffer.anchor_after(range_after_cursor.end),
18386                    )
18387                    .collect::<String>();
18388                completion.new_text.ends_with(&text_after_cursor)
18389            }
18390        }
18391    }
18392
18393    let buffer = buffer.read(cx);
18394
18395    if let CompletionSource::Lsp {
18396        insert_range: Some(insert_range),
18397        ..
18398    } = &completion.source
18399    {
18400        let completion_mode_setting =
18401            language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18402                .completions
18403                .lsp_insert_mode;
18404
18405        if !should_replace(
18406            completion,
18407            &insert_range,
18408            intent,
18409            completion_mode_setting,
18410            buffer,
18411        ) {
18412            return insert_range.to_offset(buffer);
18413        }
18414    }
18415
18416    completion.replace_range.to_offset(buffer)
18417}
18418
18419fn insert_extra_newline_brackets(
18420    buffer: &MultiBufferSnapshot,
18421    range: Range<usize>,
18422    language: &language::LanguageScope,
18423) -> bool {
18424    let leading_whitespace_len = buffer
18425        .reversed_chars_at(range.start)
18426        .take_while(|c| c.is_whitespace() && *c != '\n')
18427        .map(|c| c.len_utf8())
18428        .sum::<usize>();
18429    let trailing_whitespace_len = buffer
18430        .chars_at(range.end)
18431        .take_while(|c| c.is_whitespace() && *c != '\n')
18432        .map(|c| c.len_utf8())
18433        .sum::<usize>();
18434    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18435
18436    language.brackets().any(|(pair, enabled)| {
18437        let pair_start = pair.start.trim_end();
18438        let pair_end = pair.end.trim_start();
18439
18440        enabled
18441            && pair.newline
18442            && buffer.contains_str_at(range.end, pair_end)
18443            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18444    })
18445}
18446
18447fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18448    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18449        [(buffer, range, _)] => (*buffer, range.clone()),
18450        _ => return false,
18451    };
18452    let pair = {
18453        let mut result: Option<BracketMatch> = None;
18454
18455        for pair in buffer
18456            .all_bracket_ranges(range.clone())
18457            .filter(move |pair| {
18458                pair.open_range.start <= range.start && pair.close_range.end >= range.end
18459            })
18460        {
18461            let len = pair.close_range.end - pair.open_range.start;
18462
18463            if let Some(existing) = &result {
18464                let existing_len = existing.close_range.end - existing.open_range.start;
18465                if len > existing_len {
18466                    continue;
18467                }
18468            }
18469
18470            result = Some(pair);
18471        }
18472
18473        result
18474    };
18475    let Some(pair) = pair else {
18476        return false;
18477    };
18478    pair.newline_only
18479        && buffer
18480            .chars_for_range(pair.open_range.end..range.start)
18481            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18482            .all(|c| c.is_whitespace() && c != '\n')
18483}
18484
18485fn get_uncommitted_diff_for_buffer(
18486    project: &Entity<Project>,
18487    buffers: impl IntoIterator<Item = Entity<Buffer>>,
18488    buffer: Entity<MultiBuffer>,
18489    cx: &mut App,
18490) -> Task<()> {
18491    let mut tasks = Vec::new();
18492    project.update(cx, |project, cx| {
18493        for buffer in buffers {
18494            if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18495                tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18496            }
18497        }
18498    });
18499    cx.spawn(async move |cx| {
18500        let diffs = future::join_all(tasks).await;
18501        buffer
18502            .update(cx, |buffer, cx| {
18503                for diff in diffs.into_iter().flatten() {
18504                    buffer.add_diff(diff, cx);
18505                }
18506            })
18507            .ok();
18508    })
18509}
18510
18511fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18512    let tab_size = tab_size.get() as usize;
18513    let mut width = offset;
18514
18515    for ch in text.chars() {
18516        width += if ch == '\t' {
18517            tab_size - (width % tab_size)
18518        } else {
18519            1
18520        };
18521    }
18522
18523    width - offset
18524}
18525
18526#[cfg(test)]
18527mod tests {
18528    use super::*;
18529
18530    #[test]
18531    fn test_string_size_with_expanded_tabs() {
18532        let nz = |val| NonZeroU32::new(val).unwrap();
18533        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18534        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18535        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18536        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18537        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18538        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18539        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18540        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18541    }
18542}
18543
18544/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18545struct WordBreakingTokenizer<'a> {
18546    input: &'a str,
18547}
18548
18549impl<'a> WordBreakingTokenizer<'a> {
18550    fn new(input: &'a str) -> Self {
18551        Self { input }
18552    }
18553}
18554
18555fn is_char_ideographic(ch: char) -> bool {
18556    use unicode_script::Script::*;
18557    use unicode_script::UnicodeScript;
18558    matches!(ch.script(), Han | Tangut | Yi)
18559}
18560
18561fn is_grapheme_ideographic(text: &str) -> bool {
18562    text.chars().any(is_char_ideographic)
18563}
18564
18565fn is_grapheme_whitespace(text: &str) -> bool {
18566    text.chars().any(|x| x.is_whitespace())
18567}
18568
18569fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18570    text.chars().next().map_or(false, |ch| {
18571        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18572    })
18573}
18574
18575#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18576enum WordBreakToken<'a> {
18577    Word { token: &'a str, grapheme_len: usize },
18578    InlineWhitespace { token: &'a str, grapheme_len: usize },
18579    Newline,
18580}
18581
18582impl<'a> Iterator for WordBreakingTokenizer<'a> {
18583    /// Yields a span, the count of graphemes in the token, and whether it was
18584    /// whitespace. Note that it also breaks at word boundaries.
18585    type Item = WordBreakToken<'a>;
18586
18587    fn next(&mut self) -> Option<Self::Item> {
18588        use unicode_segmentation::UnicodeSegmentation;
18589        if self.input.is_empty() {
18590            return None;
18591        }
18592
18593        let mut iter = self.input.graphemes(true).peekable();
18594        let mut offset = 0;
18595        let mut grapheme_len = 0;
18596        if let Some(first_grapheme) = iter.next() {
18597            let is_newline = first_grapheme == "\n";
18598            let is_whitespace = is_grapheme_whitespace(first_grapheme);
18599            offset += first_grapheme.len();
18600            grapheme_len += 1;
18601            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
18602                if let Some(grapheme) = iter.peek().copied() {
18603                    if should_stay_with_preceding_ideograph(grapheme) {
18604                        offset += grapheme.len();
18605                        grapheme_len += 1;
18606                    }
18607                }
18608            } else {
18609                let mut words = self.input[offset..].split_word_bound_indices().peekable();
18610                let mut next_word_bound = words.peek().copied();
18611                if next_word_bound.map_or(false, |(i, _)| i == 0) {
18612                    next_word_bound = words.next();
18613                }
18614                while let Some(grapheme) = iter.peek().copied() {
18615                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
18616                        break;
18617                    };
18618                    if is_grapheme_whitespace(grapheme) != is_whitespace
18619                        || (grapheme == "\n") != is_newline
18620                    {
18621                        break;
18622                    };
18623                    offset += grapheme.len();
18624                    grapheme_len += 1;
18625                    iter.next();
18626                }
18627            }
18628            let token = &self.input[..offset];
18629            self.input = &self.input[offset..];
18630            if token == "\n" {
18631                Some(WordBreakToken::Newline)
18632            } else if is_whitespace {
18633                Some(WordBreakToken::InlineWhitespace {
18634                    token,
18635                    grapheme_len,
18636                })
18637            } else {
18638                Some(WordBreakToken::Word {
18639                    token,
18640                    grapheme_len,
18641                })
18642            }
18643        } else {
18644            None
18645        }
18646    }
18647}
18648
18649#[test]
18650fn test_word_breaking_tokenizer() {
18651    let tests: &[(&str, &[WordBreakToken<'static>])] = &[
18652        ("", &[]),
18653        ("  ", &[whitespace("  ", 2)]),
18654        ("Ʒ", &[word("Ʒ", 1)]),
18655        ("Ǽ", &[word("Ǽ", 1)]),
18656        ("", &[word("", 1)]),
18657        ("⋑⋑", &[word("⋑⋑", 2)]),
18658        (
18659            "原理,进而",
18660            &[word("", 1), word("理,", 2), word("", 1), word("", 1)],
18661        ),
18662        (
18663            "hello world",
18664            &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
18665        ),
18666        (
18667            "hello, world",
18668            &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
18669        ),
18670        (
18671            "  hello world",
18672            &[
18673                whitespace("  ", 2),
18674                word("hello", 5),
18675                whitespace(" ", 1),
18676                word("world", 5),
18677            ],
18678        ),
18679        (
18680            "这是什么 \n 钢笔",
18681            &[
18682                word("", 1),
18683                word("", 1),
18684                word("", 1),
18685                word("", 1),
18686                whitespace(" ", 1),
18687                newline(),
18688                whitespace(" ", 1),
18689                word("", 1),
18690                word("", 1),
18691            ],
18692        ),
18693        (" mutton", &[whitespace("", 1), word("mutton", 6)]),
18694    ];
18695
18696    fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18697        WordBreakToken::Word {
18698            token,
18699            grapheme_len,
18700        }
18701    }
18702
18703    fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18704        WordBreakToken::InlineWhitespace {
18705            token,
18706            grapheme_len,
18707        }
18708    }
18709
18710    fn newline() -> WordBreakToken<'static> {
18711        WordBreakToken::Newline
18712    }
18713
18714    for (input, result) in tests {
18715        assert_eq!(
18716            WordBreakingTokenizer::new(input)
18717                .collect::<Vec<_>>()
18718                .as_slice(),
18719            *result,
18720        );
18721    }
18722}
18723
18724fn wrap_with_prefix(
18725    line_prefix: String,
18726    unwrapped_text: String,
18727    wrap_column: usize,
18728    tab_size: NonZeroU32,
18729    preserve_existing_whitespace: bool,
18730) -> String {
18731    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
18732    let mut wrapped_text = String::new();
18733    let mut current_line = line_prefix.clone();
18734
18735    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
18736    let mut current_line_len = line_prefix_len;
18737    let mut in_whitespace = false;
18738    for token in tokenizer {
18739        let have_preceding_whitespace = in_whitespace;
18740        match token {
18741            WordBreakToken::Word {
18742                token,
18743                grapheme_len,
18744            } => {
18745                in_whitespace = false;
18746                if current_line_len + grapheme_len > wrap_column
18747                    && current_line_len != line_prefix_len
18748                {
18749                    wrapped_text.push_str(current_line.trim_end());
18750                    wrapped_text.push('\n');
18751                    current_line.truncate(line_prefix.len());
18752                    current_line_len = line_prefix_len;
18753                }
18754                current_line.push_str(token);
18755                current_line_len += grapheme_len;
18756            }
18757            WordBreakToken::InlineWhitespace {
18758                mut token,
18759                mut grapheme_len,
18760            } => {
18761                in_whitespace = true;
18762                if have_preceding_whitespace && !preserve_existing_whitespace {
18763                    continue;
18764                }
18765                if !preserve_existing_whitespace {
18766                    token = " ";
18767                    grapheme_len = 1;
18768                }
18769                if current_line_len + grapheme_len > wrap_column {
18770                    wrapped_text.push_str(current_line.trim_end());
18771                    wrapped_text.push('\n');
18772                    current_line.truncate(line_prefix.len());
18773                    current_line_len = line_prefix_len;
18774                } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
18775                    current_line.push_str(token);
18776                    current_line_len += grapheme_len;
18777                }
18778            }
18779            WordBreakToken::Newline => {
18780                in_whitespace = true;
18781                if preserve_existing_whitespace {
18782                    wrapped_text.push_str(current_line.trim_end());
18783                    wrapped_text.push('\n');
18784                    current_line.truncate(line_prefix.len());
18785                    current_line_len = line_prefix_len;
18786                } else if have_preceding_whitespace {
18787                    continue;
18788                } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
18789                {
18790                    wrapped_text.push_str(current_line.trim_end());
18791                    wrapped_text.push('\n');
18792                    current_line.truncate(line_prefix.len());
18793                    current_line_len = line_prefix_len;
18794                } else if current_line_len != line_prefix_len {
18795                    current_line.push(' ');
18796                    current_line_len += 1;
18797                }
18798            }
18799        }
18800    }
18801
18802    if !current_line.is_empty() {
18803        wrapped_text.push_str(&current_line);
18804    }
18805    wrapped_text
18806}
18807
18808#[test]
18809fn test_wrap_with_prefix() {
18810    assert_eq!(
18811        wrap_with_prefix(
18812            "# ".to_string(),
18813            "abcdefg".to_string(),
18814            4,
18815            NonZeroU32::new(4).unwrap(),
18816            false,
18817        ),
18818        "# abcdefg"
18819    );
18820    assert_eq!(
18821        wrap_with_prefix(
18822            "".to_string(),
18823            "\thello world".to_string(),
18824            8,
18825            NonZeroU32::new(4).unwrap(),
18826            false,
18827        ),
18828        "hello\nworld"
18829    );
18830    assert_eq!(
18831        wrap_with_prefix(
18832            "// ".to_string(),
18833            "xx \nyy zz aa bb cc".to_string(),
18834            12,
18835            NonZeroU32::new(4).unwrap(),
18836            false,
18837        ),
18838        "// xx yy zz\n// aa bb cc"
18839    );
18840    assert_eq!(
18841        wrap_with_prefix(
18842            String::new(),
18843            "这是什么 \n 钢笔".to_string(),
18844            3,
18845            NonZeroU32::new(4).unwrap(),
18846            false,
18847        ),
18848        "这是什\n么 钢\n"
18849    );
18850}
18851
18852pub trait CollaborationHub {
18853    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
18854    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
18855    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
18856}
18857
18858impl CollaborationHub for Entity<Project> {
18859    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
18860        self.read(cx).collaborators()
18861    }
18862
18863    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
18864        self.read(cx).user_store().read(cx).participant_indices()
18865    }
18866
18867    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
18868        let this = self.read(cx);
18869        let user_ids = this.collaborators().values().map(|c| c.user_id);
18870        this.user_store().read_with(cx, |user_store, cx| {
18871            user_store.participant_names(user_ids, cx)
18872        })
18873    }
18874}
18875
18876pub trait SemanticsProvider {
18877    fn hover(
18878        &self,
18879        buffer: &Entity<Buffer>,
18880        position: text::Anchor,
18881        cx: &mut App,
18882    ) -> Option<Task<Vec<project::Hover>>>;
18883
18884    fn inlay_hints(
18885        &self,
18886        buffer_handle: Entity<Buffer>,
18887        range: Range<text::Anchor>,
18888        cx: &mut App,
18889    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
18890
18891    fn resolve_inlay_hint(
18892        &self,
18893        hint: InlayHint,
18894        buffer_handle: Entity<Buffer>,
18895        server_id: LanguageServerId,
18896        cx: &mut App,
18897    ) -> Option<Task<anyhow::Result<InlayHint>>>;
18898
18899    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
18900
18901    fn document_highlights(
18902        &self,
18903        buffer: &Entity<Buffer>,
18904        position: text::Anchor,
18905        cx: &mut App,
18906    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
18907
18908    fn definitions(
18909        &self,
18910        buffer: &Entity<Buffer>,
18911        position: text::Anchor,
18912        kind: GotoDefinitionKind,
18913        cx: &mut App,
18914    ) -> Option<Task<Result<Vec<LocationLink>>>>;
18915
18916    fn range_for_rename(
18917        &self,
18918        buffer: &Entity<Buffer>,
18919        position: text::Anchor,
18920        cx: &mut App,
18921    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
18922
18923    fn perform_rename(
18924        &self,
18925        buffer: &Entity<Buffer>,
18926        position: text::Anchor,
18927        new_name: String,
18928        cx: &mut App,
18929    ) -> Option<Task<Result<ProjectTransaction>>>;
18930}
18931
18932pub trait CompletionProvider {
18933    fn completions(
18934        &self,
18935        excerpt_id: ExcerptId,
18936        buffer: &Entity<Buffer>,
18937        buffer_position: text::Anchor,
18938        trigger: CompletionContext,
18939        window: &mut Window,
18940        cx: &mut Context<Editor>,
18941    ) -> Task<Result<Option<Vec<Completion>>>>;
18942
18943    fn resolve_completions(
18944        &self,
18945        buffer: Entity<Buffer>,
18946        completion_indices: Vec<usize>,
18947        completions: Rc<RefCell<Box<[Completion]>>>,
18948        cx: &mut Context<Editor>,
18949    ) -> Task<Result<bool>>;
18950
18951    fn apply_additional_edits_for_completion(
18952        &self,
18953        _buffer: Entity<Buffer>,
18954        _completions: Rc<RefCell<Box<[Completion]>>>,
18955        _completion_index: usize,
18956        _push_to_history: bool,
18957        _cx: &mut Context<Editor>,
18958    ) -> Task<Result<Option<language::Transaction>>> {
18959        Task::ready(Ok(None))
18960    }
18961
18962    fn is_completion_trigger(
18963        &self,
18964        buffer: &Entity<Buffer>,
18965        position: language::Anchor,
18966        text: &str,
18967        trigger_in_words: bool,
18968        cx: &mut Context<Editor>,
18969    ) -> bool;
18970
18971    fn sort_completions(&self) -> bool {
18972        true
18973    }
18974
18975    fn filter_completions(&self) -> bool {
18976        true
18977    }
18978}
18979
18980pub trait CodeActionProvider {
18981    fn id(&self) -> Arc<str>;
18982
18983    fn code_actions(
18984        &self,
18985        buffer: &Entity<Buffer>,
18986        range: Range<text::Anchor>,
18987        window: &mut Window,
18988        cx: &mut App,
18989    ) -> Task<Result<Vec<CodeAction>>>;
18990
18991    fn apply_code_action(
18992        &self,
18993        buffer_handle: Entity<Buffer>,
18994        action: CodeAction,
18995        excerpt_id: ExcerptId,
18996        push_to_history: bool,
18997        window: &mut Window,
18998        cx: &mut App,
18999    ) -> Task<Result<ProjectTransaction>>;
19000}
19001
19002impl CodeActionProvider for Entity<Project> {
19003    fn id(&self) -> Arc<str> {
19004        "project".into()
19005    }
19006
19007    fn code_actions(
19008        &self,
19009        buffer: &Entity<Buffer>,
19010        range: Range<text::Anchor>,
19011        _window: &mut Window,
19012        cx: &mut App,
19013    ) -> Task<Result<Vec<CodeAction>>> {
19014        self.update(cx, |project, cx| {
19015            let code_lens = project.code_lens(buffer, range.clone(), cx);
19016            let code_actions = project.code_actions(buffer, range, None, cx);
19017            cx.background_spawn(async move {
19018                let (code_lens, code_actions) = join(code_lens, code_actions).await;
19019                Ok(code_lens
19020                    .context("code lens fetch")?
19021                    .into_iter()
19022                    .chain(code_actions.context("code action fetch")?)
19023                    .collect())
19024            })
19025        })
19026    }
19027
19028    fn apply_code_action(
19029        &self,
19030        buffer_handle: Entity<Buffer>,
19031        action: CodeAction,
19032        _excerpt_id: ExcerptId,
19033        push_to_history: bool,
19034        _window: &mut Window,
19035        cx: &mut App,
19036    ) -> Task<Result<ProjectTransaction>> {
19037        self.update(cx, |project, cx| {
19038            project.apply_code_action(buffer_handle, action, push_to_history, cx)
19039        })
19040    }
19041}
19042
19043fn snippet_completions(
19044    project: &Project,
19045    buffer: &Entity<Buffer>,
19046    buffer_position: text::Anchor,
19047    cx: &mut App,
19048) -> Task<Result<Vec<Completion>>> {
19049    let languages = buffer.read(cx).languages_at(buffer_position);
19050    let snippet_store = project.snippets().read(cx);
19051
19052    let scopes: Vec<_> = languages
19053        .iter()
19054        .filter_map(|language| {
19055            let language_name = language.lsp_id();
19056            let snippets = snippet_store.snippets_for(Some(language_name), cx);
19057
19058            if snippets.is_empty() {
19059                None
19060            } else {
19061                Some((language.default_scope(), snippets))
19062            }
19063        })
19064        .collect();
19065
19066    if scopes.is_empty() {
19067        return Task::ready(Ok(vec![]));
19068    }
19069
19070    let snapshot = buffer.read(cx).text_snapshot();
19071    let chars: String = snapshot
19072        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
19073        .collect();
19074    let executor = cx.background_executor().clone();
19075
19076    cx.background_spawn(async move {
19077        let mut all_results: Vec<Completion> = Vec::new();
19078        for (scope, snippets) in scopes.into_iter() {
19079            let classifier = CharClassifier::new(Some(scope)).for_completion(true);
19080            let mut last_word = chars
19081                .chars()
19082                .take_while(|c| classifier.is_word(*c))
19083                .collect::<String>();
19084            last_word = last_word.chars().rev().collect();
19085
19086            if last_word.is_empty() {
19087                return Ok(vec![]);
19088            }
19089
19090            let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
19091            let to_lsp = |point: &text::Anchor| {
19092                let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
19093                point_to_lsp(end)
19094            };
19095            let lsp_end = to_lsp(&buffer_position);
19096
19097            let candidates = snippets
19098                .iter()
19099                .enumerate()
19100                .flat_map(|(ix, snippet)| {
19101                    snippet
19102                        .prefix
19103                        .iter()
19104                        .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
19105                })
19106                .collect::<Vec<StringMatchCandidate>>();
19107
19108            let mut matches = fuzzy::match_strings(
19109                &candidates,
19110                &last_word,
19111                last_word.chars().any(|c| c.is_uppercase()),
19112                100,
19113                &Default::default(),
19114                executor.clone(),
19115            )
19116            .await;
19117
19118            // Remove all candidates where the query's start does not match the start of any word in the candidate
19119            if let Some(query_start) = last_word.chars().next() {
19120                matches.retain(|string_match| {
19121                    split_words(&string_match.string).any(|word| {
19122                        // Check that the first codepoint of the word as lowercase matches the first
19123                        // codepoint of the query as lowercase
19124                        word.chars()
19125                            .flat_map(|codepoint| codepoint.to_lowercase())
19126                            .zip(query_start.to_lowercase())
19127                            .all(|(word_cp, query_cp)| word_cp == query_cp)
19128                    })
19129                });
19130            }
19131
19132            let matched_strings = matches
19133                .into_iter()
19134                .map(|m| m.string)
19135                .collect::<HashSet<_>>();
19136
19137            let mut result: Vec<Completion> = snippets
19138                .iter()
19139                .filter_map(|snippet| {
19140                    let matching_prefix = snippet
19141                        .prefix
19142                        .iter()
19143                        .find(|prefix| matched_strings.contains(*prefix))?;
19144                    let start = as_offset - last_word.len();
19145                    let start = snapshot.anchor_before(start);
19146                    let range = start..buffer_position;
19147                    let lsp_start = to_lsp(&start);
19148                    let lsp_range = lsp::Range {
19149                        start: lsp_start,
19150                        end: lsp_end,
19151                    };
19152                    Some(Completion {
19153                        replace_range: range,
19154                        new_text: snippet.body.clone(),
19155                        source: CompletionSource::Lsp {
19156                            insert_range: None,
19157                            server_id: LanguageServerId(usize::MAX),
19158                            resolved: true,
19159                            lsp_completion: Box::new(lsp::CompletionItem {
19160                                label: snippet.prefix.first().unwrap().clone(),
19161                                kind: Some(CompletionItemKind::SNIPPET),
19162                                label_details: snippet.description.as_ref().map(|description| {
19163                                    lsp::CompletionItemLabelDetails {
19164                                        detail: Some(description.clone()),
19165                                        description: None,
19166                                    }
19167                                }),
19168                                insert_text_format: Some(InsertTextFormat::SNIPPET),
19169                                text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
19170                                    lsp::InsertReplaceEdit {
19171                                        new_text: snippet.body.clone(),
19172                                        insert: lsp_range,
19173                                        replace: lsp_range,
19174                                    },
19175                                )),
19176                                filter_text: Some(snippet.body.clone()),
19177                                sort_text: Some(char::MAX.to_string()),
19178                                ..lsp::CompletionItem::default()
19179                            }),
19180                            lsp_defaults: None,
19181                        },
19182                        label: CodeLabel {
19183                            text: matching_prefix.clone(),
19184                            runs: Vec::new(),
19185                            filter_range: 0..matching_prefix.len(),
19186                        },
19187                        icon_path: None,
19188                        documentation: snippet.description.clone().map(|description| {
19189                            CompletionDocumentation::SingleLine(description.into())
19190                        }),
19191                        insert_text_mode: None,
19192                        confirm: None,
19193                    })
19194                })
19195                .collect();
19196
19197            all_results.append(&mut result);
19198        }
19199
19200        Ok(all_results)
19201    })
19202}
19203
19204impl CompletionProvider for Entity<Project> {
19205    fn completions(
19206        &self,
19207        _excerpt_id: ExcerptId,
19208        buffer: &Entity<Buffer>,
19209        buffer_position: text::Anchor,
19210        options: CompletionContext,
19211        _window: &mut Window,
19212        cx: &mut Context<Editor>,
19213    ) -> Task<Result<Option<Vec<Completion>>>> {
19214        self.update(cx, |project, cx| {
19215            let snippets = snippet_completions(project, buffer, buffer_position, cx);
19216            let project_completions = project.completions(buffer, buffer_position, options, cx);
19217            cx.background_spawn(async move {
19218                let snippets_completions = snippets.await?;
19219                match project_completions.await? {
19220                    Some(mut completions) => {
19221                        completions.extend(snippets_completions);
19222                        Ok(Some(completions))
19223                    }
19224                    None => {
19225                        if snippets_completions.is_empty() {
19226                            Ok(None)
19227                        } else {
19228                            Ok(Some(snippets_completions))
19229                        }
19230                    }
19231                }
19232            })
19233        })
19234    }
19235
19236    fn resolve_completions(
19237        &self,
19238        buffer: Entity<Buffer>,
19239        completion_indices: Vec<usize>,
19240        completions: Rc<RefCell<Box<[Completion]>>>,
19241        cx: &mut Context<Editor>,
19242    ) -> Task<Result<bool>> {
19243        self.update(cx, |project, cx| {
19244            project.lsp_store().update(cx, |lsp_store, cx| {
19245                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19246            })
19247        })
19248    }
19249
19250    fn apply_additional_edits_for_completion(
19251        &self,
19252        buffer: Entity<Buffer>,
19253        completions: Rc<RefCell<Box<[Completion]>>>,
19254        completion_index: usize,
19255        push_to_history: bool,
19256        cx: &mut Context<Editor>,
19257    ) -> Task<Result<Option<language::Transaction>>> {
19258        self.update(cx, |project, cx| {
19259            project.lsp_store().update(cx, |lsp_store, cx| {
19260                lsp_store.apply_additional_edits_for_completion(
19261                    buffer,
19262                    completions,
19263                    completion_index,
19264                    push_to_history,
19265                    cx,
19266                )
19267            })
19268        })
19269    }
19270
19271    fn is_completion_trigger(
19272        &self,
19273        buffer: &Entity<Buffer>,
19274        position: language::Anchor,
19275        text: &str,
19276        trigger_in_words: bool,
19277        cx: &mut Context<Editor>,
19278    ) -> bool {
19279        let mut chars = text.chars();
19280        let char = if let Some(char) = chars.next() {
19281            char
19282        } else {
19283            return false;
19284        };
19285        if chars.next().is_some() {
19286            return false;
19287        }
19288
19289        let buffer = buffer.read(cx);
19290        let snapshot = buffer.snapshot();
19291        if !snapshot.settings_at(position, cx).show_completions_on_input {
19292            return false;
19293        }
19294        let classifier = snapshot.char_classifier_at(position).for_completion(true);
19295        if trigger_in_words && classifier.is_word(char) {
19296            return true;
19297        }
19298
19299        buffer.completion_triggers().contains(text)
19300    }
19301}
19302
19303impl SemanticsProvider for Entity<Project> {
19304    fn hover(
19305        &self,
19306        buffer: &Entity<Buffer>,
19307        position: text::Anchor,
19308        cx: &mut App,
19309    ) -> Option<Task<Vec<project::Hover>>> {
19310        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19311    }
19312
19313    fn document_highlights(
19314        &self,
19315        buffer: &Entity<Buffer>,
19316        position: text::Anchor,
19317        cx: &mut App,
19318    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19319        Some(self.update(cx, |project, cx| {
19320            project.document_highlights(buffer, position, cx)
19321        }))
19322    }
19323
19324    fn definitions(
19325        &self,
19326        buffer: &Entity<Buffer>,
19327        position: text::Anchor,
19328        kind: GotoDefinitionKind,
19329        cx: &mut App,
19330    ) -> Option<Task<Result<Vec<LocationLink>>>> {
19331        Some(self.update(cx, |project, cx| match kind {
19332            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19333            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19334            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19335            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19336        }))
19337    }
19338
19339    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19340        // TODO: make this work for remote projects
19341        self.update(cx, |this, cx| {
19342            buffer.update(cx, |buffer, cx| {
19343                this.any_language_server_supports_inlay_hints(buffer, cx)
19344            })
19345        })
19346    }
19347
19348    fn inlay_hints(
19349        &self,
19350        buffer_handle: Entity<Buffer>,
19351        range: Range<text::Anchor>,
19352        cx: &mut App,
19353    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19354        Some(self.update(cx, |project, cx| {
19355            project.inlay_hints(buffer_handle, range, cx)
19356        }))
19357    }
19358
19359    fn resolve_inlay_hint(
19360        &self,
19361        hint: InlayHint,
19362        buffer_handle: Entity<Buffer>,
19363        server_id: LanguageServerId,
19364        cx: &mut App,
19365    ) -> Option<Task<anyhow::Result<InlayHint>>> {
19366        Some(self.update(cx, |project, cx| {
19367            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19368        }))
19369    }
19370
19371    fn range_for_rename(
19372        &self,
19373        buffer: &Entity<Buffer>,
19374        position: text::Anchor,
19375        cx: &mut App,
19376    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19377        Some(self.update(cx, |project, cx| {
19378            let buffer = buffer.clone();
19379            let task = project.prepare_rename(buffer.clone(), position, cx);
19380            cx.spawn(async move |_, cx| {
19381                Ok(match task.await? {
19382                    PrepareRenameResponse::Success(range) => Some(range),
19383                    PrepareRenameResponse::InvalidPosition => None,
19384                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19385                        // Fallback on using TreeSitter info to determine identifier range
19386                        buffer.update(cx, |buffer, _| {
19387                            let snapshot = buffer.snapshot();
19388                            let (range, kind) = snapshot.surrounding_word(position);
19389                            if kind != Some(CharKind::Word) {
19390                                return None;
19391                            }
19392                            Some(
19393                                snapshot.anchor_before(range.start)
19394                                    ..snapshot.anchor_after(range.end),
19395                            )
19396                        })?
19397                    }
19398                })
19399            })
19400        }))
19401    }
19402
19403    fn perform_rename(
19404        &self,
19405        buffer: &Entity<Buffer>,
19406        position: text::Anchor,
19407        new_name: String,
19408        cx: &mut App,
19409    ) -> Option<Task<Result<ProjectTransaction>>> {
19410        Some(self.update(cx, |project, cx| {
19411            project.perform_rename(buffer.clone(), position, new_name, cx)
19412        }))
19413    }
19414}
19415
19416fn inlay_hint_settings(
19417    location: Anchor,
19418    snapshot: &MultiBufferSnapshot,
19419    cx: &mut Context<Editor>,
19420) -> InlayHintSettings {
19421    let file = snapshot.file_at(location);
19422    let language = snapshot.language_at(location).map(|l| l.name());
19423    language_settings(language, file, cx).inlay_hints
19424}
19425
19426fn consume_contiguous_rows(
19427    contiguous_row_selections: &mut Vec<Selection<Point>>,
19428    selection: &Selection<Point>,
19429    display_map: &DisplaySnapshot,
19430    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19431) -> (MultiBufferRow, MultiBufferRow) {
19432    contiguous_row_selections.push(selection.clone());
19433    let start_row = MultiBufferRow(selection.start.row);
19434    let mut end_row = ending_row(selection, display_map);
19435
19436    while let Some(next_selection) = selections.peek() {
19437        if next_selection.start.row <= end_row.0 {
19438            end_row = ending_row(next_selection, display_map);
19439            contiguous_row_selections.push(selections.next().unwrap().clone());
19440        } else {
19441            break;
19442        }
19443    }
19444    (start_row, end_row)
19445}
19446
19447fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19448    if next_selection.end.column > 0 || next_selection.is_empty() {
19449        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19450    } else {
19451        MultiBufferRow(next_selection.end.row)
19452    }
19453}
19454
19455impl EditorSnapshot {
19456    pub fn remote_selections_in_range<'a>(
19457        &'a self,
19458        range: &'a Range<Anchor>,
19459        collaboration_hub: &dyn CollaborationHub,
19460        cx: &'a App,
19461    ) -> impl 'a + Iterator<Item = RemoteSelection> {
19462        let participant_names = collaboration_hub.user_names(cx);
19463        let participant_indices = collaboration_hub.user_participant_indices(cx);
19464        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19465        let collaborators_by_replica_id = collaborators_by_peer_id
19466            .iter()
19467            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19468            .collect::<HashMap<_, _>>();
19469        self.buffer_snapshot
19470            .selections_in_range(range, false)
19471            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19472                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19473                let participant_index = participant_indices.get(&collaborator.user_id).copied();
19474                let user_name = participant_names.get(&collaborator.user_id).cloned();
19475                Some(RemoteSelection {
19476                    replica_id,
19477                    selection,
19478                    cursor_shape,
19479                    line_mode,
19480                    participant_index,
19481                    peer_id: collaborator.peer_id,
19482                    user_name,
19483                })
19484            })
19485    }
19486
19487    pub fn hunks_for_ranges(
19488        &self,
19489        ranges: impl IntoIterator<Item = Range<Point>>,
19490    ) -> Vec<MultiBufferDiffHunk> {
19491        let mut hunks = Vec::new();
19492        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19493            HashMap::default();
19494        for query_range in ranges {
19495            let query_rows =
19496                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19497            for hunk in self.buffer_snapshot.diff_hunks_in_range(
19498                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19499            ) {
19500                // Include deleted hunks that are adjacent to the query range, because
19501                // otherwise they would be missed.
19502                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19503                if hunk.status().is_deleted() {
19504                    intersects_range |= hunk.row_range.start == query_rows.end;
19505                    intersects_range |= hunk.row_range.end == query_rows.start;
19506                }
19507                if intersects_range {
19508                    if !processed_buffer_rows
19509                        .entry(hunk.buffer_id)
19510                        .or_default()
19511                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19512                    {
19513                        continue;
19514                    }
19515                    hunks.push(hunk);
19516                }
19517            }
19518        }
19519
19520        hunks
19521    }
19522
19523    fn display_diff_hunks_for_rows<'a>(
19524        &'a self,
19525        display_rows: Range<DisplayRow>,
19526        folded_buffers: &'a HashSet<BufferId>,
19527    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19528        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19529        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19530
19531        self.buffer_snapshot
19532            .diff_hunks_in_range(buffer_start..buffer_end)
19533            .filter_map(|hunk| {
19534                if folded_buffers.contains(&hunk.buffer_id) {
19535                    return None;
19536                }
19537
19538                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
19539                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
19540
19541                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
19542                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
19543
19544                let display_hunk = if hunk_display_start.column() != 0 {
19545                    DisplayDiffHunk::Folded {
19546                        display_row: hunk_display_start.row(),
19547                    }
19548                } else {
19549                    let mut end_row = hunk_display_end.row();
19550                    if hunk_display_end.column() > 0 {
19551                        end_row.0 += 1;
19552                    }
19553                    let is_created_file = hunk.is_created_file();
19554                    DisplayDiffHunk::Unfolded {
19555                        status: hunk.status(),
19556                        diff_base_byte_range: hunk.diff_base_byte_range,
19557                        display_row_range: hunk_display_start.row()..end_row,
19558                        multi_buffer_range: Anchor::range_in_buffer(
19559                            hunk.excerpt_id,
19560                            hunk.buffer_id,
19561                            hunk.buffer_range,
19562                        ),
19563                        is_created_file,
19564                    }
19565                };
19566
19567                Some(display_hunk)
19568            })
19569    }
19570
19571    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
19572        self.display_snapshot.buffer_snapshot.language_at(position)
19573    }
19574
19575    pub fn is_focused(&self) -> bool {
19576        self.is_focused
19577    }
19578
19579    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
19580        self.placeholder_text.as_ref()
19581    }
19582
19583    pub fn scroll_position(&self) -> gpui::Point<f32> {
19584        self.scroll_anchor.scroll_position(&self.display_snapshot)
19585    }
19586
19587    fn gutter_dimensions(
19588        &self,
19589        font_id: FontId,
19590        font_size: Pixels,
19591        max_line_number_width: Pixels,
19592        cx: &App,
19593    ) -> Option<GutterDimensions> {
19594        if !self.show_gutter {
19595            return None;
19596        }
19597
19598        let descent = cx.text_system().descent(font_id, font_size);
19599        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
19600        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
19601
19602        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
19603            matches!(
19604                ProjectSettings::get_global(cx).git.git_gutter,
19605                Some(GitGutterSetting::TrackedFiles)
19606            )
19607        });
19608        let gutter_settings = EditorSettings::get_global(cx).gutter;
19609        let show_line_numbers = self
19610            .show_line_numbers
19611            .unwrap_or(gutter_settings.line_numbers);
19612        let line_gutter_width = if show_line_numbers {
19613            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
19614            let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
19615            max_line_number_width.max(min_width_for_number_on_gutter)
19616        } else {
19617            0.0.into()
19618        };
19619
19620        let show_code_actions = self
19621            .show_code_actions
19622            .unwrap_or(gutter_settings.code_actions);
19623
19624        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
19625        let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
19626
19627        let git_blame_entries_width =
19628            self.git_blame_gutter_max_author_length
19629                .map(|max_author_length| {
19630                    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
19631                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
19632
19633                    /// The number of characters to dedicate to gaps and margins.
19634                    const SPACING_WIDTH: usize = 4;
19635
19636                    let max_char_count = max_author_length.min(renderer.max_author_length())
19637                        + ::git::SHORT_SHA_LENGTH
19638                        + MAX_RELATIVE_TIMESTAMP.len()
19639                        + SPACING_WIDTH;
19640
19641                    em_advance * max_char_count
19642                });
19643
19644        let is_singleton = self.buffer_snapshot.is_singleton();
19645
19646        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
19647        left_padding += if !is_singleton {
19648            em_width * 4.0
19649        } else if show_code_actions || show_runnables || show_breakpoints {
19650            em_width * 3.0
19651        } else if show_git_gutter && show_line_numbers {
19652            em_width * 2.0
19653        } else if show_git_gutter || show_line_numbers {
19654            em_width
19655        } else {
19656            px(0.)
19657        };
19658
19659        let shows_folds = is_singleton && gutter_settings.folds;
19660
19661        let right_padding = if shows_folds && show_line_numbers {
19662            em_width * 4.0
19663        } else if shows_folds || (!is_singleton && show_line_numbers) {
19664            em_width * 3.0
19665        } else if show_line_numbers {
19666            em_width
19667        } else {
19668            px(0.)
19669        };
19670
19671        Some(GutterDimensions {
19672            left_padding,
19673            right_padding,
19674            width: line_gutter_width + left_padding + right_padding,
19675            margin: -descent,
19676            git_blame_entries_width,
19677        })
19678    }
19679
19680    pub fn render_crease_toggle(
19681        &self,
19682        buffer_row: MultiBufferRow,
19683        row_contains_cursor: bool,
19684        editor: Entity<Editor>,
19685        window: &mut Window,
19686        cx: &mut App,
19687    ) -> Option<AnyElement> {
19688        let folded = self.is_line_folded(buffer_row);
19689        let mut is_foldable = false;
19690
19691        if let Some(crease) = self
19692            .crease_snapshot
19693            .query_row(buffer_row, &self.buffer_snapshot)
19694        {
19695            is_foldable = true;
19696            match crease {
19697                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
19698                    if let Some(render_toggle) = render_toggle {
19699                        let toggle_callback =
19700                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
19701                                if folded {
19702                                    editor.update(cx, |editor, cx| {
19703                                        editor.fold_at(buffer_row, window, cx)
19704                                    });
19705                                } else {
19706                                    editor.update(cx, |editor, cx| {
19707                                        editor.unfold_at(buffer_row, window, cx)
19708                                    });
19709                                }
19710                            });
19711                        return Some((render_toggle)(
19712                            buffer_row,
19713                            folded,
19714                            toggle_callback,
19715                            window,
19716                            cx,
19717                        ));
19718                    }
19719                }
19720            }
19721        }
19722
19723        is_foldable |= self.starts_indent(buffer_row);
19724
19725        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
19726            Some(
19727                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
19728                    .toggle_state(folded)
19729                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
19730                        if folded {
19731                            this.unfold_at(buffer_row, window, cx);
19732                        } else {
19733                            this.fold_at(buffer_row, window, cx);
19734                        }
19735                    }))
19736                    .into_any_element(),
19737            )
19738        } else {
19739            None
19740        }
19741    }
19742
19743    pub fn render_crease_trailer(
19744        &self,
19745        buffer_row: MultiBufferRow,
19746        window: &mut Window,
19747        cx: &mut App,
19748    ) -> Option<AnyElement> {
19749        let folded = self.is_line_folded(buffer_row);
19750        if let Crease::Inline { render_trailer, .. } = self
19751            .crease_snapshot
19752            .query_row(buffer_row, &self.buffer_snapshot)?
19753        {
19754            let render_trailer = render_trailer.as_ref()?;
19755            Some(render_trailer(buffer_row, folded, window, cx))
19756        } else {
19757            None
19758        }
19759    }
19760}
19761
19762impl Deref for EditorSnapshot {
19763    type Target = DisplaySnapshot;
19764
19765    fn deref(&self) -> &Self::Target {
19766        &self.display_snapshot
19767    }
19768}
19769
19770#[derive(Clone, Debug, PartialEq, Eq)]
19771pub enum EditorEvent {
19772    InputIgnored {
19773        text: Arc<str>,
19774    },
19775    InputHandled {
19776        utf16_range_to_replace: Option<Range<isize>>,
19777        text: Arc<str>,
19778    },
19779    ExcerptsAdded {
19780        buffer: Entity<Buffer>,
19781        predecessor: ExcerptId,
19782        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
19783    },
19784    ExcerptsRemoved {
19785        ids: Vec<ExcerptId>,
19786        removed_buffer_ids: Vec<BufferId>,
19787    },
19788    BufferFoldToggled {
19789        ids: Vec<ExcerptId>,
19790        folded: bool,
19791    },
19792    ExcerptsEdited {
19793        ids: Vec<ExcerptId>,
19794    },
19795    ExcerptsExpanded {
19796        ids: Vec<ExcerptId>,
19797    },
19798    BufferEdited,
19799    Edited {
19800        transaction_id: clock::Lamport,
19801    },
19802    Reparsed(BufferId),
19803    Focused,
19804    FocusedIn,
19805    Blurred,
19806    DirtyChanged,
19807    Saved,
19808    TitleChanged,
19809    DiffBaseChanged,
19810    SelectionsChanged {
19811        local: bool,
19812    },
19813    ScrollPositionChanged {
19814        local: bool,
19815        autoscroll: bool,
19816    },
19817    Closed,
19818    TransactionUndone {
19819        transaction_id: clock::Lamport,
19820    },
19821    TransactionBegun {
19822        transaction_id: clock::Lamport,
19823    },
19824    Reloaded,
19825    CursorShapeChanged,
19826    PushedToNavHistory {
19827        anchor: Anchor,
19828        is_deactivate: bool,
19829    },
19830}
19831
19832impl EventEmitter<EditorEvent> for Editor {}
19833
19834impl Focusable for Editor {
19835    fn focus_handle(&self, _cx: &App) -> FocusHandle {
19836        self.focus_handle.clone()
19837    }
19838}
19839
19840impl Render for Editor {
19841    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19842        let settings = ThemeSettings::get_global(cx);
19843
19844        let mut text_style = match self.mode {
19845            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
19846                color: cx.theme().colors().editor_foreground,
19847                font_family: settings.ui_font.family.clone(),
19848                font_features: settings.ui_font.features.clone(),
19849                font_fallbacks: settings.ui_font.fallbacks.clone(),
19850                font_size: rems(0.875).into(),
19851                font_weight: settings.ui_font.weight,
19852                line_height: relative(settings.buffer_line_height.value()),
19853                ..Default::default()
19854            },
19855            EditorMode::Full { .. } => TextStyle {
19856                color: cx.theme().colors().editor_foreground,
19857                font_family: settings.buffer_font.family.clone(),
19858                font_features: settings.buffer_font.features.clone(),
19859                font_fallbacks: settings.buffer_font.fallbacks.clone(),
19860                font_size: settings.buffer_font_size(cx).into(),
19861                font_weight: settings.buffer_font.weight,
19862                line_height: relative(settings.buffer_line_height.value()),
19863                ..Default::default()
19864            },
19865        };
19866        if let Some(text_style_refinement) = &self.text_style_refinement {
19867            text_style.refine(text_style_refinement)
19868        }
19869
19870        let background = match self.mode {
19871            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
19872            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
19873            EditorMode::Full { .. } => cx.theme().colors().editor_background,
19874        };
19875
19876        EditorElement::new(
19877            &cx.entity(),
19878            EditorStyle {
19879                background,
19880                local_player: cx.theme().players().local(),
19881                text: text_style,
19882                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
19883                syntax: cx.theme().syntax().clone(),
19884                status: cx.theme().status().clone(),
19885                inlay_hints_style: make_inlay_hints_style(cx),
19886                inline_completion_styles: make_suggestion_styles(cx),
19887                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
19888            },
19889        )
19890    }
19891}
19892
19893impl EntityInputHandler for Editor {
19894    fn text_for_range(
19895        &mut self,
19896        range_utf16: Range<usize>,
19897        adjusted_range: &mut Option<Range<usize>>,
19898        _: &mut Window,
19899        cx: &mut Context<Self>,
19900    ) -> Option<String> {
19901        let snapshot = self.buffer.read(cx).read(cx);
19902        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
19903        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
19904        if (start.0..end.0) != range_utf16 {
19905            adjusted_range.replace(start.0..end.0);
19906        }
19907        Some(snapshot.text_for_range(start..end).collect())
19908    }
19909
19910    fn selected_text_range(
19911        &mut self,
19912        ignore_disabled_input: bool,
19913        _: &mut Window,
19914        cx: &mut Context<Self>,
19915    ) -> Option<UTF16Selection> {
19916        // Prevent the IME menu from appearing when holding down an alphabetic key
19917        // while input is disabled.
19918        if !ignore_disabled_input && !self.input_enabled {
19919            return None;
19920        }
19921
19922        let selection = self.selections.newest::<OffsetUtf16>(cx);
19923        let range = selection.range();
19924
19925        Some(UTF16Selection {
19926            range: range.start.0..range.end.0,
19927            reversed: selection.reversed,
19928        })
19929    }
19930
19931    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
19932        let snapshot = self.buffer.read(cx).read(cx);
19933        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
19934        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
19935    }
19936
19937    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
19938        self.clear_highlights::<InputComposition>(cx);
19939        self.ime_transaction.take();
19940    }
19941
19942    fn replace_text_in_range(
19943        &mut self,
19944        range_utf16: Option<Range<usize>>,
19945        text: &str,
19946        window: &mut Window,
19947        cx: &mut Context<Self>,
19948    ) {
19949        if !self.input_enabled {
19950            cx.emit(EditorEvent::InputIgnored { text: text.into() });
19951            return;
19952        }
19953
19954        self.transact(window, cx, |this, window, cx| {
19955            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
19956                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19957                Some(this.selection_replacement_ranges(range_utf16, cx))
19958            } else {
19959                this.marked_text_ranges(cx)
19960            };
19961
19962            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
19963                let newest_selection_id = this.selections.newest_anchor().id;
19964                this.selections
19965                    .all::<OffsetUtf16>(cx)
19966                    .iter()
19967                    .zip(ranges_to_replace.iter())
19968                    .find_map(|(selection, range)| {
19969                        if selection.id == newest_selection_id {
19970                            Some(
19971                                (range.start.0 as isize - selection.head().0 as isize)
19972                                    ..(range.end.0 as isize - selection.head().0 as isize),
19973                            )
19974                        } else {
19975                            None
19976                        }
19977                    })
19978            });
19979
19980            cx.emit(EditorEvent::InputHandled {
19981                utf16_range_to_replace: range_to_replace,
19982                text: text.into(),
19983            });
19984
19985            if let Some(new_selected_ranges) = new_selected_ranges {
19986                this.change_selections(None, window, cx, |selections| {
19987                    selections.select_ranges(new_selected_ranges)
19988                });
19989                this.backspace(&Default::default(), window, cx);
19990            }
19991
19992            this.handle_input(text, window, cx);
19993        });
19994
19995        if let Some(transaction) = self.ime_transaction {
19996            self.buffer.update(cx, |buffer, cx| {
19997                buffer.group_until_transaction(transaction, cx);
19998            });
19999        }
20000
20001        self.unmark_text(window, cx);
20002    }
20003
20004    fn replace_and_mark_text_in_range(
20005        &mut self,
20006        range_utf16: Option<Range<usize>>,
20007        text: &str,
20008        new_selected_range_utf16: Option<Range<usize>>,
20009        window: &mut Window,
20010        cx: &mut Context<Self>,
20011    ) {
20012        if !self.input_enabled {
20013            return;
20014        }
20015
20016        let transaction = self.transact(window, cx, |this, window, cx| {
20017            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
20018                let snapshot = this.buffer.read(cx).read(cx);
20019                if let Some(relative_range_utf16) = range_utf16.as_ref() {
20020                    for marked_range in &mut marked_ranges {
20021                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
20022                        marked_range.start.0 += relative_range_utf16.start;
20023                        marked_range.start =
20024                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
20025                        marked_range.end =
20026                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
20027                    }
20028                }
20029                Some(marked_ranges)
20030            } else if let Some(range_utf16) = range_utf16 {
20031                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20032                Some(this.selection_replacement_ranges(range_utf16, cx))
20033            } else {
20034                None
20035            };
20036
20037            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
20038                let newest_selection_id = this.selections.newest_anchor().id;
20039                this.selections
20040                    .all::<OffsetUtf16>(cx)
20041                    .iter()
20042                    .zip(ranges_to_replace.iter())
20043                    .find_map(|(selection, range)| {
20044                        if selection.id == newest_selection_id {
20045                            Some(
20046                                (range.start.0 as isize - selection.head().0 as isize)
20047                                    ..(range.end.0 as isize - selection.head().0 as isize),
20048                            )
20049                        } else {
20050                            None
20051                        }
20052                    })
20053            });
20054
20055            cx.emit(EditorEvent::InputHandled {
20056                utf16_range_to_replace: range_to_replace,
20057                text: text.into(),
20058            });
20059
20060            if let Some(ranges) = ranges_to_replace {
20061                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
20062            }
20063
20064            let marked_ranges = {
20065                let snapshot = this.buffer.read(cx).read(cx);
20066                this.selections
20067                    .disjoint_anchors()
20068                    .iter()
20069                    .map(|selection| {
20070                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
20071                    })
20072                    .collect::<Vec<_>>()
20073            };
20074
20075            if text.is_empty() {
20076                this.unmark_text(window, cx);
20077            } else {
20078                this.highlight_text::<InputComposition>(
20079                    marked_ranges.clone(),
20080                    HighlightStyle {
20081                        underline: Some(UnderlineStyle {
20082                            thickness: px(1.),
20083                            color: None,
20084                            wavy: false,
20085                        }),
20086                        ..Default::default()
20087                    },
20088                    cx,
20089                );
20090            }
20091
20092            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
20093            let use_autoclose = this.use_autoclose;
20094            let use_auto_surround = this.use_auto_surround;
20095            this.set_use_autoclose(false);
20096            this.set_use_auto_surround(false);
20097            this.handle_input(text, window, cx);
20098            this.set_use_autoclose(use_autoclose);
20099            this.set_use_auto_surround(use_auto_surround);
20100
20101            if let Some(new_selected_range) = new_selected_range_utf16 {
20102                let snapshot = this.buffer.read(cx).read(cx);
20103                let new_selected_ranges = marked_ranges
20104                    .into_iter()
20105                    .map(|marked_range| {
20106                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
20107                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
20108                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
20109                        snapshot.clip_offset_utf16(new_start, Bias::Left)
20110                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
20111                    })
20112                    .collect::<Vec<_>>();
20113
20114                drop(snapshot);
20115                this.change_selections(None, window, cx, |selections| {
20116                    selections.select_ranges(new_selected_ranges)
20117                });
20118            }
20119        });
20120
20121        self.ime_transaction = self.ime_transaction.or(transaction);
20122        if let Some(transaction) = self.ime_transaction {
20123            self.buffer.update(cx, |buffer, cx| {
20124                buffer.group_until_transaction(transaction, cx);
20125            });
20126        }
20127
20128        if self.text_highlights::<InputComposition>(cx).is_none() {
20129            self.ime_transaction.take();
20130        }
20131    }
20132
20133    fn bounds_for_range(
20134        &mut self,
20135        range_utf16: Range<usize>,
20136        element_bounds: gpui::Bounds<Pixels>,
20137        window: &mut Window,
20138        cx: &mut Context<Self>,
20139    ) -> Option<gpui::Bounds<Pixels>> {
20140        let text_layout_details = self.text_layout_details(window);
20141        let gpui::Size {
20142            width: em_width,
20143            height: line_height,
20144        } = self.character_size(window);
20145
20146        let snapshot = self.snapshot(window, cx);
20147        let scroll_position = snapshot.scroll_position();
20148        let scroll_left = scroll_position.x * em_width;
20149
20150        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
20151        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
20152            + self.gutter_dimensions.width
20153            + self.gutter_dimensions.margin;
20154        let y = line_height * (start.row().as_f32() - scroll_position.y);
20155
20156        Some(Bounds {
20157            origin: element_bounds.origin + point(x, y),
20158            size: size(em_width, line_height),
20159        })
20160    }
20161
20162    fn character_index_for_point(
20163        &mut self,
20164        point: gpui::Point<Pixels>,
20165        _window: &mut Window,
20166        _cx: &mut Context<Self>,
20167    ) -> Option<usize> {
20168        let position_map = self.last_position_map.as_ref()?;
20169        if !position_map.text_hitbox.contains(&point) {
20170            return None;
20171        }
20172        let display_point = position_map.point_for_position(point).previous_valid;
20173        let anchor = position_map
20174            .snapshot
20175            .display_point_to_anchor(display_point, Bias::Left);
20176        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
20177        Some(utf16_offset.0)
20178    }
20179}
20180
20181trait SelectionExt {
20182    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
20183    fn spanned_rows(
20184        &self,
20185        include_end_if_at_line_start: bool,
20186        map: &DisplaySnapshot,
20187    ) -> Range<MultiBufferRow>;
20188}
20189
20190impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
20191    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
20192        let start = self
20193            .start
20194            .to_point(&map.buffer_snapshot)
20195            .to_display_point(map);
20196        let end = self
20197            .end
20198            .to_point(&map.buffer_snapshot)
20199            .to_display_point(map);
20200        if self.reversed {
20201            end..start
20202        } else {
20203            start..end
20204        }
20205    }
20206
20207    fn spanned_rows(
20208        &self,
20209        include_end_if_at_line_start: bool,
20210        map: &DisplaySnapshot,
20211    ) -> Range<MultiBufferRow> {
20212        let start = self.start.to_point(&map.buffer_snapshot);
20213        let mut end = self.end.to_point(&map.buffer_snapshot);
20214        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
20215            end.row -= 1;
20216        }
20217
20218        let buffer_start = map.prev_line_boundary(start).0;
20219        let buffer_end = map.next_line_boundary(end).0;
20220        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20221    }
20222}
20223
20224impl<T: InvalidationRegion> InvalidationStack<T> {
20225    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20226    where
20227        S: Clone + ToOffset,
20228    {
20229        while let Some(region) = self.last() {
20230            let all_selections_inside_invalidation_ranges =
20231                if selections.len() == region.ranges().len() {
20232                    selections
20233                        .iter()
20234                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20235                        .all(|(selection, invalidation_range)| {
20236                            let head = selection.head().to_offset(buffer);
20237                            invalidation_range.start <= head && invalidation_range.end >= head
20238                        })
20239                } else {
20240                    false
20241                };
20242
20243            if all_selections_inside_invalidation_ranges {
20244                break;
20245            } else {
20246                self.pop();
20247            }
20248        }
20249    }
20250}
20251
20252impl<T> Default for InvalidationStack<T> {
20253    fn default() -> Self {
20254        Self(Default::default())
20255    }
20256}
20257
20258impl<T> Deref for InvalidationStack<T> {
20259    type Target = Vec<T>;
20260
20261    fn deref(&self) -> &Self::Target {
20262        &self.0
20263    }
20264}
20265
20266impl<T> DerefMut for InvalidationStack<T> {
20267    fn deref_mut(&mut self) -> &mut Self::Target {
20268        &mut self.0
20269    }
20270}
20271
20272impl InvalidationRegion for SnippetState {
20273    fn ranges(&self) -> &[Range<Anchor>] {
20274        &self.ranges[self.active_index]
20275    }
20276}
20277
20278fn inline_completion_edit_text(
20279    current_snapshot: &BufferSnapshot,
20280    edits: &[(Range<Anchor>, String)],
20281    edit_preview: &EditPreview,
20282    include_deletions: bool,
20283    cx: &App,
20284) -> HighlightedText {
20285    let edits = edits
20286        .iter()
20287        .map(|(anchor, text)| {
20288            (
20289                anchor.start.text_anchor..anchor.end.text_anchor,
20290                text.clone(),
20291            )
20292        })
20293        .collect::<Vec<_>>();
20294
20295    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20296}
20297
20298pub fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20299    match severity {
20300        DiagnosticSeverity::ERROR => colors.error,
20301        DiagnosticSeverity::WARNING => colors.warning,
20302        DiagnosticSeverity::INFORMATION => colors.info,
20303        DiagnosticSeverity::HINT => colors.info,
20304        _ => colors.ignored,
20305    }
20306}
20307
20308pub fn styled_runs_for_code_label<'a>(
20309    label: &'a CodeLabel,
20310    syntax_theme: &'a theme::SyntaxTheme,
20311) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20312    let fade_out = HighlightStyle {
20313        fade_out: Some(0.35),
20314        ..Default::default()
20315    };
20316
20317    let mut prev_end = label.filter_range.end;
20318    label
20319        .runs
20320        .iter()
20321        .enumerate()
20322        .flat_map(move |(ix, (range, highlight_id))| {
20323            let style = if let Some(style) = highlight_id.style(syntax_theme) {
20324                style
20325            } else {
20326                return Default::default();
20327            };
20328            let mut muted_style = style;
20329            muted_style.highlight(fade_out);
20330
20331            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20332            if range.start >= label.filter_range.end {
20333                if range.start > prev_end {
20334                    runs.push((prev_end..range.start, fade_out));
20335                }
20336                runs.push((range.clone(), muted_style));
20337            } else if range.end <= label.filter_range.end {
20338                runs.push((range.clone(), style));
20339            } else {
20340                runs.push((range.start..label.filter_range.end, style));
20341                runs.push((label.filter_range.end..range.end, muted_style));
20342            }
20343            prev_end = cmp::max(prev_end, range.end);
20344
20345            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20346                runs.push((prev_end..label.text.len(), fade_out));
20347            }
20348
20349            runs
20350        })
20351}
20352
20353pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20354    let mut prev_index = 0;
20355    let mut prev_codepoint: Option<char> = None;
20356    text.char_indices()
20357        .chain([(text.len(), '\0')])
20358        .filter_map(move |(index, codepoint)| {
20359            let prev_codepoint = prev_codepoint.replace(codepoint)?;
20360            let is_boundary = index == text.len()
20361                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20362                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20363            if is_boundary {
20364                let chunk = &text[prev_index..index];
20365                prev_index = index;
20366                Some(chunk)
20367            } else {
20368                None
20369            }
20370        })
20371}
20372
20373pub trait RangeToAnchorExt: Sized {
20374    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20375
20376    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20377        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20378        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20379    }
20380}
20381
20382impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20383    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20384        let start_offset = self.start.to_offset(snapshot);
20385        let end_offset = self.end.to_offset(snapshot);
20386        if start_offset == end_offset {
20387            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20388        } else {
20389            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20390        }
20391    }
20392}
20393
20394pub trait RowExt {
20395    fn as_f32(&self) -> f32;
20396
20397    fn next_row(&self) -> Self;
20398
20399    fn previous_row(&self) -> Self;
20400
20401    fn minus(&self, other: Self) -> u32;
20402}
20403
20404impl RowExt for DisplayRow {
20405    fn as_f32(&self) -> f32 {
20406        self.0 as f32
20407    }
20408
20409    fn next_row(&self) -> Self {
20410        Self(self.0 + 1)
20411    }
20412
20413    fn previous_row(&self) -> Self {
20414        Self(self.0.saturating_sub(1))
20415    }
20416
20417    fn minus(&self, other: Self) -> u32 {
20418        self.0 - other.0
20419    }
20420}
20421
20422impl RowExt for MultiBufferRow {
20423    fn as_f32(&self) -> f32 {
20424        self.0 as f32
20425    }
20426
20427    fn next_row(&self) -> Self {
20428        Self(self.0 + 1)
20429    }
20430
20431    fn previous_row(&self) -> Self {
20432        Self(self.0.saturating_sub(1))
20433    }
20434
20435    fn minus(&self, other: Self) -> u32 {
20436        self.0 - other.0
20437    }
20438}
20439
20440trait RowRangeExt {
20441    type Row;
20442
20443    fn len(&self) -> usize;
20444
20445    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20446}
20447
20448impl RowRangeExt for Range<MultiBufferRow> {
20449    type Row = MultiBufferRow;
20450
20451    fn len(&self) -> usize {
20452        (self.end.0 - self.start.0) as usize
20453    }
20454
20455    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20456        (self.start.0..self.end.0).map(MultiBufferRow)
20457    }
20458}
20459
20460impl RowRangeExt for Range<DisplayRow> {
20461    type Row = DisplayRow;
20462
20463    fn len(&self) -> usize {
20464        (self.end.0 - self.start.0) as usize
20465    }
20466
20467    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20468        (self.start.0..self.end.0).map(DisplayRow)
20469    }
20470}
20471
20472/// If select range has more than one line, we
20473/// just point the cursor to range.start.
20474fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20475    if range.start.row == range.end.row {
20476        range
20477    } else {
20478        range.start..range.start
20479    }
20480}
20481pub struct KillRing(ClipboardItem);
20482impl Global for KillRing {}
20483
20484const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20485
20486enum BreakpointPromptEditAction {
20487    Log,
20488    Condition,
20489    HitCondition,
20490}
20491
20492struct BreakpointPromptEditor {
20493    pub(crate) prompt: Entity<Editor>,
20494    editor: WeakEntity<Editor>,
20495    breakpoint_anchor: Anchor,
20496    breakpoint: Breakpoint,
20497    edit_action: BreakpointPromptEditAction,
20498    block_ids: HashSet<CustomBlockId>,
20499    gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20500    _subscriptions: Vec<Subscription>,
20501}
20502
20503impl BreakpointPromptEditor {
20504    const MAX_LINES: u8 = 4;
20505
20506    fn new(
20507        editor: WeakEntity<Editor>,
20508        breakpoint_anchor: Anchor,
20509        breakpoint: Breakpoint,
20510        edit_action: BreakpointPromptEditAction,
20511        window: &mut Window,
20512        cx: &mut Context<Self>,
20513    ) -> Self {
20514        let base_text = match edit_action {
20515            BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20516            BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20517            BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20518        }
20519        .map(|msg| msg.to_string())
20520        .unwrap_or_default();
20521
20522        let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20523        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20524
20525        let prompt = cx.new(|cx| {
20526            let mut prompt = Editor::new(
20527                EditorMode::AutoHeight {
20528                    max_lines: Self::MAX_LINES as usize,
20529                },
20530                buffer,
20531                None,
20532                window,
20533                cx,
20534            );
20535            prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20536            prompt.set_show_cursor_when_unfocused(false, cx);
20537            prompt.set_placeholder_text(
20538                match edit_action {
20539                    BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20540                    BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20541                    BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20542                },
20543                cx,
20544            );
20545
20546            prompt
20547        });
20548
20549        Self {
20550            prompt,
20551            editor,
20552            breakpoint_anchor,
20553            breakpoint,
20554            edit_action,
20555            gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20556            block_ids: Default::default(),
20557            _subscriptions: vec![],
20558        }
20559    }
20560
20561    pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20562        self.block_ids.extend(block_ids)
20563    }
20564
20565    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20566        if let Some(editor) = self.editor.upgrade() {
20567            let message = self
20568                .prompt
20569                .read(cx)
20570                .buffer
20571                .read(cx)
20572                .as_singleton()
20573                .expect("A multi buffer in breakpoint prompt isn't possible")
20574                .read(cx)
20575                .as_rope()
20576                .to_string();
20577
20578            editor.update(cx, |editor, cx| {
20579                editor.edit_breakpoint_at_anchor(
20580                    self.breakpoint_anchor,
20581                    self.breakpoint.clone(),
20582                    match self.edit_action {
20583                        BreakpointPromptEditAction::Log => {
20584                            BreakpointEditAction::EditLogMessage(message.into())
20585                        }
20586                        BreakpointPromptEditAction::Condition => {
20587                            BreakpointEditAction::EditCondition(message.into())
20588                        }
20589                        BreakpointPromptEditAction::HitCondition => {
20590                            BreakpointEditAction::EditHitCondition(message.into())
20591                        }
20592                    },
20593                    cx,
20594                );
20595
20596                editor.remove_blocks(self.block_ids.clone(), None, cx);
20597                cx.focus_self(window);
20598            });
20599        }
20600    }
20601
20602    fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
20603        self.editor
20604            .update(cx, |editor, cx| {
20605                editor.remove_blocks(self.block_ids.clone(), None, cx);
20606                window.focus(&editor.focus_handle);
20607            })
20608            .log_err();
20609    }
20610
20611    fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
20612        let settings = ThemeSettings::get_global(cx);
20613        let text_style = TextStyle {
20614            color: if self.prompt.read(cx).read_only(cx) {
20615                cx.theme().colors().text_disabled
20616            } else {
20617                cx.theme().colors().text
20618            },
20619            font_family: settings.buffer_font.family.clone(),
20620            font_fallbacks: settings.buffer_font.fallbacks.clone(),
20621            font_size: settings.buffer_font_size(cx).into(),
20622            font_weight: settings.buffer_font.weight,
20623            line_height: relative(settings.buffer_line_height.value()),
20624            ..Default::default()
20625        };
20626        EditorElement::new(
20627            &self.prompt,
20628            EditorStyle {
20629                background: cx.theme().colors().editor_background,
20630                local_player: cx.theme().players().local(),
20631                text: text_style,
20632                ..Default::default()
20633            },
20634        )
20635    }
20636}
20637
20638impl Render for BreakpointPromptEditor {
20639    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20640        let gutter_dimensions = *self.gutter_dimensions.lock();
20641        h_flex()
20642            .key_context("Editor")
20643            .bg(cx.theme().colors().editor_background)
20644            .border_y_1()
20645            .border_color(cx.theme().status().info_border)
20646            .size_full()
20647            .py(window.line_height() / 2.5)
20648            .on_action(cx.listener(Self::confirm))
20649            .on_action(cx.listener(Self::cancel))
20650            .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
20651            .child(div().flex_1().child(self.render_prompt_editor(cx)))
20652    }
20653}
20654
20655impl Focusable for BreakpointPromptEditor {
20656    fn focus_handle(&self, cx: &App) -> FocusHandle {
20657        self.prompt.focus_handle(cx)
20658    }
20659}
20660
20661fn all_edits_insertions_or_deletions(
20662    edits: &Vec<(Range<Anchor>, String)>,
20663    snapshot: &MultiBufferSnapshot,
20664) -> bool {
20665    let mut all_insertions = true;
20666    let mut all_deletions = true;
20667
20668    for (range, new_text) in edits.iter() {
20669        let range_is_empty = range.to_offset(&snapshot).is_empty();
20670        let text_is_empty = new_text.is_empty();
20671
20672        if range_is_empty != text_is_empty {
20673            if range_is_empty {
20674                all_deletions = false;
20675            } else {
20676                all_insertions = false;
20677            }
20678        } else {
20679            return false;
20680        }
20681
20682        if !all_insertions && !all_deletions {
20683            return false;
20684        }
20685    }
20686    all_insertions || all_deletions
20687}
20688
20689struct MissingEditPredictionKeybindingTooltip;
20690
20691impl Render for MissingEditPredictionKeybindingTooltip {
20692    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20693        ui::tooltip_container(window, cx, |container, _, cx| {
20694            container
20695                .flex_shrink_0()
20696                .max_w_80()
20697                .min_h(rems_from_px(124.))
20698                .justify_between()
20699                .child(
20700                    v_flex()
20701                        .flex_1()
20702                        .text_ui_sm(cx)
20703                        .child(Label::new("Conflict with Accept Keybinding"))
20704                        .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
20705                )
20706                .child(
20707                    h_flex()
20708                        .pb_1()
20709                        .gap_1()
20710                        .items_end()
20711                        .w_full()
20712                        .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
20713                            window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
20714                        }))
20715                        .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
20716                            cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
20717                        })),
20718                )
20719        })
20720    }
20721}
20722
20723#[derive(Debug, Clone, Copy, PartialEq)]
20724pub struct LineHighlight {
20725    pub background: Background,
20726    pub border: Option<gpui::Hsla>,
20727    pub include_gutter: bool,
20728    pub type_id: Option<TypeId>,
20729}
20730
20731fn render_diff_hunk_controls(
20732    row: u32,
20733    status: &DiffHunkStatus,
20734    hunk_range: Range<Anchor>,
20735    is_created_file: bool,
20736    line_height: Pixels,
20737    editor: &Entity<Editor>,
20738    _window: &mut Window,
20739    cx: &mut App,
20740) -> AnyElement {
20741    h_flex()
20742        .h(line_height)
20743        .mr_1()
20744        .gap_1()
20745        .px_0p5()
20746        .pb_1()
20747        .border_x_1()
20748        .border_b_1()
20749        .border_color(cx.theme().colors().border_variant)
20750        .rounded_b_lg()
20751        .bg(cx.theme().colors().editor_background)
20752        .gap_1()
20753        .occlude()
20754        .shadow_md()
20755        .child(if status.has_secondary_hunk() {
20756            Button::new(("stage", row as u64), "Stage")
20757                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20758                .tooltip({
20759                    let focus_handle = editor.focus_handle(cx);
20760                    move |window, cx| {
20761                        Tooltip::for_action_in(
20762                            "Stage Hunk",
20763                            &::git::ToggleStaged,
20764                            &focus_handle,
20765                            window,
20766                            cx,
20767                        )
20768                    }
20769                })
20770                .on_click({
20771                    let editor = editor.clone();
20772                    move |_event, _window, cx| {
20773                        editor.update(cx, |editor, cx| {
20774                            editor.stage_or_unstage_diff_hunks(
20775                                true,
20776                                vec![hunk_range.start..hunk_range.start],
20777                                cx,
20778                            );
20779                        });
20780                    }
20781                })
20782        } else {
20783            Button::new(("unstage", row as u64), "Unstage")
20784                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20785                .tooltip({
20786                    let focus_handle = editor.focus_handle(cx);
20787                    move |window, cx| {
20788                        Tooltip::for_action_in(
20789                            "Unstage Hunk",
20790                            &::git::ToggleStaged,
20791                            &focus_handle,
20792                            window,
20793                            cx,
20794                        )
20795                    }
20796                })
20797                .on_click({
20798                    let editor = editor.clone();
20799                    move |_event, _window, cx| {
20800                        editor.update(cx, |editor, cx| {
20801                            editor.stage_or_unstage_diff_hunks(
20802                                false,
20803                                vec![hunk_range.start..hunk_range.start],
20804                                cx,
20805                            );
20806                        });
20807                    }
20808                })
20809        })
20810        .child(
20811            Button::new(("restore", row as u64), "Restore")
20812                .tooltip({
20813                    let focus_handle = editor.focus_handle(cx);
20814                    move |window, cx| {
20815                        Tooltip::for_action_in(
20816                            "Restore Hunk",
20817                            &::git::Restore,
20818                            &focus_handle,
20819                            window,
20820                            cx,
20821                        )
20822                    }
20823                })
20824                .on_click({
20825                    let editor = editor.clone();
20826                    move |_event, window, cx| {
20827                        editor.update(cx, |editor, cx| {
20828                            let snapshot = editor.snapshot(window, cx);
20829                            let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
20830                            editor.restore_hunks_in_ranges(vec![point..point], window, cx);
20831                        });
20832                    }
20833                })
20834                .disabled(is_created_file),
20835        )
20836        .when(
20837            !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
20838            |el| {
20839                el.child(
20840                    IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
20841                        .shape(IconButtonShape::Square)
20842                        .icon_size(IconSize::Small)
20843                        // .disabled(!has_multiple_hunks)
20844                        .tooltip({
20845                            let focus_handle = editor.focus_handle(cx);
20846                            move |window, cx| {
20847                                Tooltip::for_action_in(
20848                                    "Next Hunk",
20849                                    &GoToHunk,
20850                                    &focus_handle,
20851                                    window,
20852                                    cx,
20853                                )
20854                            }
20855                        })
20856                        .on_click({
20857                            let editor = editor.clone();
20858                            move |_event, window, cx| {
20859                                editor.update(cx, |editor, cx| {
20860                                    let snapshot = editor.snapshot(window, cx);
20861                                    let position =
20862                                        hunk_range.end.to_point(&snapshot.buffer_snapshot);
20863                                    editor.go_to_hunk_before_or_after_position(
20864                                        &snapshot,
20865                                        position,
20866                                        Direction::Next,
20867                                        window,
20868                                        cx,
20869                                    );
20870                                    editor.expand_selected_diff_hunks(cx);
20871                                });
20872                            }
20873                        }),
20874                )
20875                .child(
20876                    IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
20877                        .shape(IconButtonShape::Square)
20878                        .icon_size(IconSize::Small)
20879                        // .disabled(!has_multiple_hunks)
20880                        .tooltip({
20881                            let focus_handle = editor.focus_handle(cx);
20882                            move |window, cx| {
20883                                Tooltip::for_action_in(
20884                                    "Previous Hunk",
20885                                    &GoToPreviousHunk,
20886                                    &focus_handle,
20887                                    window,
20888                                    cx,
20889                                )
20890                            }
20891                        })
20892                        .on_click({
20893                            let editor = editor.clone();
20894                            move |_event, window, cx| {
20895                                editor.update(cx, |editor, cx| {
20896                                    let snapshot = editor.snapshot(window, cx);
20897                                    let point =
20898                                        hunk_range.start.to_point(&snapshot.buffer_snapshot);
20899                                    editor.go_to_hunk_before_or_after_position(
20900                                        &snapshot,
20901                                        point,
20902                                        Direction::Prev,
20903                                        window,
20904                                        cx,
20905                                    );
20906                                    editor.expand_selected_diff_hunks(cx);
20907                                });
20908                            }
20909                        }),
20910                )
20911            },
20912        )
20913        .into_any_element()
20914}