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 commit_tooltip;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod indent_guides;
   29mod inlay_hint_cache;
   30pub mod items;
   31mod jsx_tag_auto_close;
   32mod linked_editing_ranges;
   33mod lsp_ext;
   34mod mouse_context_menu;
   35pub mod movement;
   36mod persistence;
   37mod proposed_changes_editor;
   38mod rust_analyzer_ext;
   39pub mod scroll;
   40mod selections_collection;
   41pub mod tasks;
   42
   43#[cfg(test)]
   44mod editor_tests;
   45#[cfg(test)]
   46mod inline_completion_tests;
   47mod signature_help;
   48#[cfg(any(test, feature = "test-support"))]
   49pub mod test;
   50
   51pub(crate) use actions::*;
   52pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   53use aho_corasick::AhoCorasick;
   54use anyhow::{anyhow, Context as _, Result};
   55use blink_manager::BlinkManager;
   56use buffer_diff::DiffHunkStatus;
   57use client::{Collaborator, ParticipantIndex};
   58use clock::ReplicaId;
   59use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   60use convert_case::{Case, Casing};
   61use display_map::*;
   62pub use display_map::{DisplayPoint, FoldPlaceholder};
   63pub use editor_settings::{
   64    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   65};
   66pub use editor_settings_controls::*;
   67use element::{layout_line, AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
   68pub use element::{
   69    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   70};
   71use feature_flags::{Debugger, FeatureFlagAppExt};
   72use futures::{
   73    future::{self, join, Shared},
   74    FutureExt,
   75};
   76use fuzzy::StringMatchCandidate;
   77
   78use ::git::Restore;
   79use code_context_menus::{
   80    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   81    CompletionsMenu, ContextMenuOrigin,
   82};
   83use git::blame::GitBlame;
   84use gpui::{
   85    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
   86    AnimationExt, AnyElement, App, AppContext, AsyncWindowContext, AvailableSpace, Background,
   87    Bounds, ClickEvent, ClipboardEntry, ClipboardItem, Context, DispatchPhase, Edges, Entity,
   88    EntityInputHandler, EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight,
   89    Global, HighlightStyle, Hsla, KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad,
   90    ParentElement, Pixels, Render, SharedString, Size, Stateful, Styled, StyledText, Subscription,
   91    Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
   92    WeakEntity, WeakFocusHandle, Window,
   93};
   94use highlight_matching_bracket::refresh_matching_bracket_highlights;
   95use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
   96use hover_popover::{hide_hover, HoverState};
   97use indent_guides::ActiveIndentGuidesState;
   98use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   99pub use inline_completion::Direction;
  100use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
  101pub use items::MAX_TAB_TITLE_LEN;
  102use itertools::Itertools;
  103use language::{
  104    language_settings::{
  105        self, all_language_settings, language_settings, InlayHintSettings, RewrapBehavior,
  106        WordsCompletionMode,
  107    },
  108    point_from_lsp, text_diff_with_options, AutoindentMode, BracketMatch, BracketPair, Buffer,
  109    Capability, CharKind, CodeLabel, CursorShape, Diagnostic, DiffOptions, EditPredictionsMode,
  110    EditPreview, HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point,
  111    Selection, SelectionGoal, TextObject, TransactionId, TreeSitterOptions, WordsQuery,
  112};
  113use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  114use linked_editing_ranges::refresh_linked_ranges;
  115use mouse_context_menu::MouseContextMenu;
  116use persistence::DB;
  117use project::{
  118    debugger::breakpoint_store::{BreakpointEditAction, BreakpointStore, BreakpointStoreEvent},
  119    ProjectPath,
  120};
  121
  122pub use proposed_changes_editor::{
  123    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  124};
  125use smallvec::smallvec;
  126use std::{cell::OnceCell, iter::Peekable};
  127use task::{ResolvedTask, TaskTemplate, TaskVariables};
  128
  129pub use lsp::CompletionContext;
  130use lsp::{
  131    CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
  132    InsertTextFormat, LanguageServerId, LanguageServerName,
  133};
  134
  135use language::BufferSnapshot;
  136use movement::TextLayoutDetails;
  137pub use multi_buffer::{
  138    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  139    ToOffset, ToPoint,
  140};
  141use multi_buffer::{
  142    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  143    MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
  144};
  145use parking_lot::Mutex;
  146use project::{
  147    debugger::breakpoint_store::{Breakpoint, BreakpointKind},
  148    lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  149    project_settings::{GitGutterSetting, ProjectSettings},
  150    CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
  151    Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
  152    TaskSourceKind,
  153};
  154use rand::prelude::*;
  155use rpc::{proto::*, ErrorExt};
  156use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  157use selections_collection::{
  158    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  159};
  160use serde::{Deserialize, Serialize};
  161use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  162use smallvec::SmallVec;
  163use snippet::Snippet;
  164use std::sync::Arc;
  165use std::{
  166    any::TypeId,
  167    borrow::Cow,
  168    cell::RefCell,
  169    cmp::{self, Ordering, Reverse},
  170    mem,
  171    num::NonZeroU32,
  172    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  173    path::{Path, PathBuf},
  174    rc::Rc,
  175    time::{Duration, Instant},
  176};
  177pub use sum_tree::Bias;
  178use sum_tree::TreeMap;
  179use text::{BufferId, OffsetUtf16, Rope};
  180use theme::{
  181    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  182    ThemeColors, ThemeSettings,
  183};
  184use ui::{
  185    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
  186    Tooltip,
  187};
  188use util::{maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  189use workspace::{
  190    item::{ItemHandle, PreviewTabsSettings},
  191    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  192    searchable::SearchEvent,
  193    Item as WorkspaceItem, ItemId, ItemNavHistory, OpenInTerminal, OpenTerminal,
  194    RestoreOnStartupBehavior, SplitDirection, TabBarSettings, Toast, ViewId, Workspace,
  195    WorkspaceId, WorkspaceSettings, SERIALIZATION_THROTTLE_TIME,
  196};
  197
  198use crate::hover_links::{find_url, find_url_from_range};
  199use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  200
  201pub const FILE_HEADER_HEIGHT: u32 = 2;
  202pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  203pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  204const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  205const MAX_LINE_LEN: usize = 1024;
  206const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  207const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  208pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  209#[doc(hidden)]
  210pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  211
  212pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
  213pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
  214pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  215
  216pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  217pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  218pub(crate) const MIN_LINE_NUMBER_DIGITS: u32 = 4;
  219
  220const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  221    alt: true,
  222    shift: true,
  223    control: false,
  224    platform: false,
  225    function: false,
  226};
  227
  228#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  229pub enum InlayId {
  230    InlineCompletion(usize),
  231    Hint(usize),
  232}
  233
  234impl InlayId {
  235    fn id(&self) -> usize {
  236        match self {
  237            Self::InlineCompletion(id) => *id,
  238            Self::Hint(id) => *id,
  239        }
  240    }
  241}
  242
  243pub enum DebugCurrentRowHighlight {}
  244enum DocumentHighlightRead {}
  245enum DocumentHighlightWrite {}
  246enum InputComposition {}
  247enum SelectedTextHighlight {}
  248
  249#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  250pub enum Navigated {
  251    Yes,
  252    No,
  253}
  254
  255impl Navigated {
  256    pub fn from_bool(yes: bool) -> Navigated {
  257        if yes {
  258            Navigated::Yes
  259        } else {
  260            Navigated::No
  261        }
  262    }
  263}
  264
  265#[derive(Debug, Clone, PartialEq, Eq)]
  266enum DisplayDiffHunk {
  267    Folded {
  268        display_row: DisplayRow,
  269    },
  270    Unfolded {
  271        is_created_file: bool,
  272        diff_base_byte_range: Range<usize>,
  273        display_row_range: Range<DisplayRow>,
  274        multi_buffer_range: Range<Anchor>,
  275        status: DiffHunkStatus,
  276    },
  277}
  278
  279pub fn init_settings(cx: &mut App) {
  280    EditorSettings::register(cx);
  281}
  282
  283pub fn init(cx: &mut App) {
  284    init_settings(cx);
  285
  286    workspace::register_project_item::<Editor>(cx);
  287    workspace::FollowableViewRegistry::register::<Editor>(cx);
  288    workspace::register_serializable_item::<Editor>(cx);
  289
  290    cx.observe_new(
  291        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  292            workspace.register_action(Editor::new_file);
  293            workspace.register_action(Editor::new_file_vertical);
  294            workspace.register_action(Editor::new_file_horizontal);
  295            workspace.register_action(Editor::cancel_language_server_work);
  296        },
  297    )
  298    .detach();
  299
  300    cx.on_action(move |_: &workspace::NewFile, cx| {
  301        let app_state = workspace::AppState::global(cx);
  302        if let Some(app_state) = app_state.upgrade() {
  303            workspace::open_new(
  304                Default::default(),
  305                app_state,
  306                cx,
  307                |workspace, window, cx| {
  308                    Editor::new_file(workspace, &Default::default(), window, cx)
  309                },
  310            )
  311            .detach();
  312        }
  313    });
  314    cx.on_action(move |_: &workspace::NewWindow, cx| {
  315        let app_state = workspace::AppState::global(cx);
  316        if let Some(app_state) = app_state.upgrade() {
  317            workspace::open_new(
  318                Default::default(),
  319                app_state,
  320                cx,
  321                |workspace, window, cx| {
  322                    cx.activate(true);
  323                    Editor::new_file(workspace, &Default::default(), window, cx)
  324                },
  325            )
  326            .detach();
  327        }
  328    });
  329}
  330
  331pub struct SearchWithinRange;
  332
  333trait InvalidationRegion {
  334    fn ranges(&self) -> &[Range<Anchor>];
  335}
  336
  337#[derive(Clone, Debug, PartialEq)]
  338pub enum SelectPhase {
  339    Begin {
  340        position: DisplayPoint,
  341        add: bool,
  342        click_count: usize,
  343    },
  344    BeginColumnar {
  345        position: DisplayPoint,
  346        reset: bool,
  347        goal_column: u32,
  348    },
  349    Extend {
  350        position: DisplayPoint,
  351        click_count: usize,
  352    },
  353    Update {
  354        position: DisplayPoint,
  355        goal_column: u32,
  356        scroll_delta: gpui::Point<f32>,
  357    },
  358    End,
  359}
  360
  361#[derive(Clone, Debug)]
  362pub enum SelectMode {
  363    Character,
  364    Word(Range<Anchor>),
  365    Line(Range<Anchor>),
  366    All,
  367}
  368
  369#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  370pub enum EditorMode {
  371    SingleLine { auto_width: bool },
  372    AutoHeight { max_lines: usize },
  373    Full,
  374}
  375
  376#[derive(Copy, Clone, Debug)]
  377pub enum SoftWrap {
  378    /// Prefer not to wrap at all.
  379    ///
  380    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  381    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  382    GitDiff,
  383    /// Prefer a single line generally, unless an overly long line is encountered.
  384    None,
  385    /// Soft wrap lines that exceed the editor width.
  386    EditorWidth,
  387    /// Soft wrap lines at the preferred line length.
  388    Column(u32),
  389    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  390    Bounded(u32),
  391}
  392
  393#[derive(Clone)]
  394pub struct EditorStyle {
  395    pub background: Hsla,
  396    pub local_player: PlayerColor,
  397    pub text: TextStyle,
  398    pub scrollbar_width: Pixels,
  399    pub syntax: Arc<SyntaxTheme>,
  400    pub status: StatusColors,
  401    pub inlay_hints_style: HighlightStyle,
  402    pub inline_completion_styles: InlineCompletionStyles,
  403    pub unnecessary_code_fade: f32,
  404}
  405
  406impl Default for EditorStyle {
  407    fn default() -> Self {
  408        Self {
  409            background: Hsla::default(),
  410            local_player: PlayerColor::default(),
  411            text: TextStyle::default(),
  412            scrollbar_width: Pixels::default(),
  413            syntax: Default::default(),
  414            // HACK: Status colors don't have a real default.
  415            // We should look into removing the status colors from the editor
  416            // style and retrieve them directly from the theme.
  417            status: StatusColors::dark(),
  418            inlay_hints_style: HighlightStyle::default(),
  419            inline_completion_styles: InlineCompletionStyles {
  420                insertion: HighlightStyle::default(),
  421                whitespace: HighlightStyle::default(),
  422            },
  423            unnecessary_code_fade: Default::default(),
  424        }
  425    }
  426}
  427
  428pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  429    let show_background = language_settings::language_settings(None, None, cx)
  430        .inlay_hints
  431        .show_background;
  432
  433    HighlightStyle {
  434        color: Some(cx.theme().status().hint),
  435        background_color: show_background.then(|| cx.theme().status().hint_background),
  436        ..HighlightStyle::default()
  437    }
  438}
  439
  440pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  441    InlineCompletionStyles {
  442        insertion: HighlightStyle {
  443            color: Some(cx.theme().status().predictive),
  444            ..HighlightStyle::default()
  445        },
  446        whitespace: HighlightStyle {
  447            background_color: Some(cx.theme().status().created_background),
  448            ..HighlightStyle::default()
  449        },
  450    }
  451}
  452
  453type CompletionId = usize;
  454
  455pub(crate) enum EditDisplayMode {
  456    TabAccept,
  457    DiffPopover,
  458    Inline,
  459}
  460
  461enum InlineCompletion {
  462    Edit {
  463        edits: Vec<(Range<Anchor>, String)>,
  464        edit_preview: Option<EditPreview>,
  465        display_mode: EditDisplayMode,
  466        snapshot: BufferSnapshot,
  467    },
  468    Move {
  469        target: Anchor,
  470        snapshot: BufferSnapshot,
  471    },
  472}
  473
  474struct InlineCompletionState {
  475    inlay_ids: Vec<InlayId>,
  476    completion: InlineCompletion,
  477    completion_id: Option<SharedString>,
  478    invalidation_range: Range<Anchor>,
  479}
  480
  481enum EditPredictionSettings {
  482    Disabled,
  483    Enabled {
  484        show_in_menu: bool,
  485        preview_requires_modifier: bool,
  486    },
  487}
  488
  489enum InlineCompletionHighlight {}
  490
  491#[derive(Debug, Clone)]
  492struct InlineDiagnostic {
  493    message: SharedString,
  494    group_id: usize,
  495    is_primary: bool,
  496    start: Point,
  497    severity: DiagnosticSeverity,
  498}
  499
  500pub enum MenuInlineCompletionsPolicy {
  501    Never,
  502    ByProvider,
  503}
  504
  505pub enum EditPredictionPreview {
  506    /// Modifier is not pressed
  507    Inactive { released_too_fast: bool },
  508    /// Modifier pressed
  509    Active {
  510        since: Instant,
  511        previous_scroll_position: Option<ScrollAnchor>,
  512    },
  513}
  514
  515impl EditPredictionPreview {
  516    pub fn released_too_fast(&self) -> bool {
  517        match self {
  518            EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
  519            EditPredictionPreview::Active { .. } => false,
  520        }
  521    }
  522
  523    pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
  524        if let EditPredictionPreview::Active {
  525            previous_scroll_position,
  526            ..
  527        } = self
  528        {
  529            *previous_scroll_position = scroll_position;
  530        }
  531    }
  532}
  533
  534#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  535struct EditorActionId(usize);
  536
  537impl EditorActionId {
  538    pub fn post_inc(&mut self) -> Self {
  539        let answer = self.0;
  540
  541        *self = Self(answer + 1);
  542
  543        Self(answer)
  544    }
  545}
  546
  547// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  548// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  549
  550type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  551type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  552
  553#[derive(Default)]
  554struct ScrollbarMarkerState {
  555    scrollbar_size: Size<Pixels>,
  556    dirty: bool,
  557    markers: Arc<[PaintQuad]>,
  558    pending_refresh: Option<Task<Result<()>>>,
  559}
  560
  561impl ScrollbarMarkerState {
  562    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  563        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  564    }
  565}
  566
  567#[derive(Clone, Debug)]
  568struct RunnableTasks {
  569    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  570    offset: multi_buffer::Anchor,
  571    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  572    column: u32,
  573    // Values of all named captures, including those starting with '_'
  574    extra_variables: HashMap<String, String>,
  575    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  576    context_range: Range<BufferOffset>,
  577}
  578
  579impl RunnableTasks {
  580    fn resolve<'a>(
  581        &'a self,
  582        cx: &'a task::TaskContext,
  583    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  584        self.templates.iter().filter_map(|(kind, template)| {
  585            template
  586                .resolve_task(&kind.to_id_base(), cx)
  587                .map(|task| (kind.clone(), task))
  588        })
  589    }
  590}
  591
  592#[derive(Clone)]
  593struct ResolvedTasks {
  594    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  595    position: Anchor,
  596}
  597
  598#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  599struct BufferOffset(usize);
  600
  601// Addons allow storing per-editor state in other crates (e.g. Vim)
  602pub trait Addon: 'static {
  603    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  604
  605    fn render_buffer_header_controls(
  606        &self,
  607        _: &ExcerptInfo,
  608        _: &Window,
  609        _: &App,
  610    ) -> Option<AnyElement> {
  611        None
  612    }
  613
  614    fn to_any(&self) -> &dyn std::any::Any;
  615}
  616
  617/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  618///
  619/// See the [module level documentation](self) for more information.
  620pub struct Editor {
  621    focus_handle: FocusHandle,
  622    last_focused_descendant: Option<WeakFocusHandle>,
  623    /// The text buffer being edited
  624    buffer: Entity<MultiBuffer>,
  625    /// Map of how text in the buffer should be displayed.
  626    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  627    pub display_map: Entity<DisplayMap>,
  628    pub selections: SelectionsCollection,
  629    pub scroll_manager: ScrollManager,
  630    /// When inline assist editors are linked, they all render cursors because
  631    /// typing enters text into each of them, even the ones that aren't focused.
  632    pub(crate) show_cursor_when_unfocused: bool,
  633    columnar_selection_tail: Option<Anchor>,
  634    add_selections_state: Option<AddSelectionsState>,
  635    select_next_state: Option<SelectNextState>,
  636    select_prev_state: Option<SelectNextState>,
  637    selection_history: SelectionHistory,
  638    autoclose_regions: Vec<AutocloseRegion>,
  639    snippet_stack: InvalidationStack<SnippetState>,
  640    select_syntax_node_history: SelectSyntaxNodeHistory,
  641    ime_transaction: Option<TransactionId>,
  642    active_diagnostics: Option<ActiveDiagnosticGroup>,
  643    show_inline_diagnostics: bool,
  644    inline_diagnostics_update: Task<()>,
  645    inline_diagnostics_enabled: bool,
  646    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  647    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  648    hard_wrap: Option<usize>,
  649
  650    // TODO: make this a access method
  651    pub project: Option<Entity<Project>>,
  652    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  653    completion_provider: Option<Box<dyn CompletionProvider>>,
  654    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  655    blink_manager: Entity<BlinkManager>,
  656    show_cursor_names: bool,
  657    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  658    pub show_local_selections: bool,
  659    mode: EditorMode,
  660    show_breadcrumbs: bool,
  661    show_gutter: bool,
  662    show_scrollbars: bool,
  663    show_line_numbers: Option<bool>,
  664    use_relative_line_numbers: Option<bool>,
  665    show_git_diff_gutter: Option<bool>,
  666    show_code_actions: Option<bool>,
  667    show_runnables: Option<bool>,
  668    show_breakpoints: Option<bool>,
  669    show_wrap_guides: Option<bool>,
  670    show_indent_guides: Option<bool>,
  671    placeholder_text: Option<Arc<str>>,
  672    highlight_order: usize,
  673    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  674    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  675    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  676    scrollbar_marker_state: ScrollbarMarkerState,
  677    active_indent_guides_state: ActiveIndentGuidesState,
  678    nav_history: Option<ItemNavHistory>,
  679    context_menu: RefCell<Option<CodeContextMenu>>,
  680    mouse_context_menu: Option<MouseContextMenu>,
  681    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  682    signature_help_state: SignatureHelpState,
  683    auto_signature_help: Option<bool>,
  684    find_all_references_task_sources: Vec<Anchor>,
  685    next_completion_id: CompletionId,
  686    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  687    code_actions_task: Option<Task<Result<()>>>,
  688    selection_highlight_task: Option<Task<()>>,
  689    document_highlights_task: Option<Task<()>>,
  690    linked_editing_range_task: Option<Task<Option<()>>>,
  691    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  692    pending_rename: Option<RenameState>,
  693    searchable: bool,
  694    cursor_shape: CursorShape,
  695    current_line_highlight: Option<CurrentLineHighlight>,
  696    collapse_matches: bool,
  697    autoindent_mode: Option<AutoindentMode>,
  698    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  699    input_enabled: bool,
  700    use_modal_editing: bool,
  701    read_only: bool,
  702    leader_peer_id: Option<PeerId>,
  703    remote_id: Option<ViewId>,
  704    hover_state: HoverState,
  705    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  706    gutter_hovered: bool,
  707    hovered_link_state: Option<HoveredLinkState>,
  708    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  709    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  710    active_inline_completion: Option<InlineCompletionState>,
  711    /// Used to prevent flickering as the user types while the menu is open
  712    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  713    edit_prediction_settings: EditPredictionSettings,
  714    inline_completions_hidden_for_vim_mode: bool,
  715    show_inline_completions_override: Option<bool>,
  716    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  717    edit_prediction_preview: EditPredictionPreview,
  718    edit_prediction_indent_conflict: bool,
  719    edit_prediction_requires_modifier_in_indent_conflict: bool,
  720    inlay_hint_cache: InlayHintCache,
  721    next_inlay_id: usize,
  722    _subscriptions: Vec<Subscription>,
  723    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  724    gutter_dimensions: GutterDimensions,
  725    style: Option<EditorStyle>,
  726    text_style_refinement: Option<TextStyleRefinement>,
  727    next_editor_action_id: EditorActionId,
  728    editor_actions:
  729        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  730    use_autoclose: bool,
  731    use_auto_surround: bool,
  732    auto_replace_emoji_shortcode: bool,
  733    jsx_tag_auto_close_enabled_in_any_buffer: bool,
  734    show_git_blame_gutter: bool,
  735    show_git_blame_inline: bool,
  736    show_git_blame_inline_delay_task: Option<Task<()>>,
  737    git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
  738    git_blame_inline_enabled: bool,
  739    serialize_dirty_buffers: bool,
  740    show_selection_menu: Option<bool>,
  741    blame: Option<Entity<GitBlame>>,
  742    blame_subscription: Option<Subscription>,
  743    custom_context_menu: Option<
  744        Box<
  745            dyn 'static
  746                + Fn(
  747                    &mut Self,
  748                    DisplayPoint,
  749                    &mut Window,
  750                    &mut Context<Self>,
  751                ) -> Option<Entity<ui::ContextMenu>>,
  752        >,
  753    >,
  754    last_bounds: Option<Bounds<Pixels>>,
  755    last_position_map: Option<Rc<PositionMap>>,
  756    expect_bounds_change: Option<Bounds<Pixels>>,
  757    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  758    tasks_update_task: Option<Task<()>>,
  759    pub breakpoint_store: Option<Entity<BreakpointStore>>,
  760    /// Allow's a user to create a breakpoint by selecting this indicator
  761    /// It should be None while a user is not hovering over the gutter
  762    /// Otherwise it represents the point that the breakpoint will be shown
  763    pub gutter_breakpoint_indicator: Option<DisplayPoint>,
  764    in_project_search: bool,
  765    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  766    breadcrumb_header: Option<String>,
  767    focused_block: Option<FocusedBlock>,
  768    next_scroll_position: NextScrollCursorCenterTopBottom,
  769    addons: HashMap<TypeId, Box<dyn Addon>>,
  770    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  771    load_diff_task: Option<Shared<Task<()>>>,
  772    selection_mark_mode: bool,
  773    toggle_fold_multiple_buffers: Task<()>,
  774    _scroll_cursor_center_top_bottom_task: Task<()>,
  775    serialize_selections: Task<()>,
  776    serialize_folds: Task<()>,
  777}
  778
  779#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  780enum NextScrollCursorCenterTopBottom {
  781    #[default]
  782    Center,
  783    Top,
  784    Bottom,
  785}
  786
  787impl NextScrollCursorCenterTopBottom {
  788    fn next(&self) -> Self {
  789        match self {
  790            Self::Center => Self::Top,
  791            Self::Top => Self::Bottom,
  792            Self::Bottom => Self::Center,
  793        }
  794    }
  795}
  796
  797#[derive(Clone)]
  798pub struct EditorSnapshot {
  799    pub mode: EditorMode,
  800    show_gutter: bool,
  801    show_line_numbers: Option<bool>,
  802    show_git_diff_gutter: Option<bool>,
  803    show_code_actions: Option<bool>,
  804    show_runnables: Option<bool>,
  805    show_breakpoints: Option<bool>,
  806    git_blame_gutter_max_author_length: Option<usize>,
  807    pub display_snapshot: DisplaySnapshot,
  808    pub placeholder_text: Option<Arc<str>>,
  809    is_focused: bool,
  810    scroll_anchor: ScrollAnchor,
  811    ongoing_scroll: OngoingScroll,
  812    current_line_highlight: CurrentLineHighlight,
  813    gutter_hovered: bool,
  814}
  815
  816const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  817
  818#[derive(Default, Debug, Clone, Copy)]
  819pub struct GutterDimensions {
  820    pub left_padding: Pixels,
  821    pub right_padding: Pixels,
  822    pub width: Pixels,
  823    pub margin: Pixels,
  824    pub git_blame_entries_width: Option<Pixels>,
  825}
  826
  827impl GutterDimensions {
  828    /// The full width of the space taken up by the gutter.
  829    pub fn full_width(&self) -> Pixels {
  830        self.margin + self.width
  831    }
  832
  833    /// The width of the space reserved for the fold indicators,
  834    /// use alongside 'justify_end' and `gutter_width` to
  835    /// right align content with the line numbers
  836    pub fn fold_area_width(&self) -> Pixels {
  837        self.margin + self.right_padding
  838    }
  839}
  840
  841#[derive(Debug)]
  842pub struct RemoteSelection {
  843    pub replica_id: ReplicaId,
  844    pub selection: Selection<Anchor>,
  845    pub cursor_shape: CursorShape,
  846    pub peer_id: PeerId,
  847    pub line_mode: bool,
  848    pub participant_index: Option<ParticipantIndex>,
  849    pub user_name: Option<SharedString>,
  850}
  851
  852#[derive(Clone, Debug)]
  853struct SelectionHistoryEntry {
  854    selections: Arc<[Selection<Anchor>]>,
  855    select_next_state: Option<SelectNextState>,
  856    select_prev_state: Option<SelectNextState>,
  857    add_selections_state: Option<AddSelectionsState>,
  858}
  859
  860enum SelectionHistoryMode {
  861    Normal,
  862    Undoing,
  863    Redoing,
  864}
  865
  866#[derive(Clone, PartialEq, Eq, Hash)]
  867struct HoveredCursor {
  868    replica_id: u16,
  869    selection_id: usize,
  870}
  871
  872impl Default for SelectionHistoryMode {
  873    fn default() -> Self {
  874        Self::Normal
  875    }
  876}
  877
  878#[derive(Default)]
  879struct SelectionHistory {
  880    #[allow(clippy::type_complexity)]
  881    selections_by_transaction:
  882        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  883    mode: SelectionHistoryMode,
  884    undo_stack: VecDeque<SelectionHistoryEntry>,
  885    redo_stack: VecDeque<SelectionHistoryEntry>,
  886}
  887
  888impl SelectionHistory {
  889    fn insert_transaction(
  890        &mut self,
  891        transaction_id: TransactionId,
  892        selections: Arc<[Selection<Anchor>]>,
  893    ) {
  894        self.selections_by_transaction
  895            .insert(transaction_id, (selections, None));
  896    }
  897
  898    #[allow(clippy::type_complexity)]
  899    fn transaction(
  900        &self,
  901        transaction_id: TransactionId,
  902    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  903        self.selections_by_transaction.get(&transaction_id)
  904    }
  905
  906    #[allow(clippy::type_complexity)]
  907    fn transaction_mut(
  908        &mut self,
  909        transaction_id: TransactionId,
  910    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  911        self.selections_by_transaction.get_mut(&transaction_id)
  912    }
  913
  914    fn push(&mut self, entry: SelectionHistoryEntry) {
  915        if !entry.selections.is_empty() {
  916            match self.mode {
  917                SelectionHistoryMode::Normal => {
  918                    self.push_undo(entry);
  919                    self.redo_stack.clear();
  920                }
  921                SelectionHistoryMode::Undoing => self.push_redo(entry),
  922                SelectionHistoryMode::Redoing => self.push_undo(entry),
  923            }
  924        }
  925    }
  926
  927    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  928        if self
  929            .undo_stack
  930            .back()
  931            .map_or(true, |e| e.selections != entry.selections)
  932        {
  933            self.undo_stack.push_back(entry);
  934            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  935                self.undo_stack.pop_front();
  936            }
  937        }
  938    }
  939
  940    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  941        if self
  942            .redo_stack
  943            .back()
  944            .map_or(true, |e| e.selections != entry.selections)
  945        {
  946            self.redo_stack.push_back(entry);
  947            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  948                self.redo_stack.pop_front();
  949            }
  950        }
  951    }
  952}
  953
  954struct RowHighlight {
  955    index: usize,
  956    range: Range<Anchor>,
  957    color: Hsla,
  958    should_autoscroll: bool,
  959}
  960
  961#[derive(Clone, Debug)]
  962struct AddSelectionsState {
  963    above: bool,
  964    stack: Vec<usize>,
  965}
  966
  967#[derive(Clone)]
  968struct SelectNextState {
  969    query: AhoCorasick,
  970    wordwise: bool,
  971    done: bool,
  972}
  973
  974impl std::fmt::Debug for SelectNextState {
  975    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  976        f.debug_struct(std::any::type_name::<Self>())
  977            .field("wordwise", &self.wordwise)
  978            .field("done", &self.done)
  979            .finish()
  980    }
  981}
  982
  983#[derive(Debug)]
  984struct AutocloseRegion {
  985    selection_id: usize,
  986    range: Range<Anchor>,
  987    pair: BracketPair,
  988}
  989
  990#[derive(Debug)]
  991struct SnippetState {
  992    ranges: Vec<Vec<Range<Anchor>>>,
  993    active_index: usize,
  994    choices: Vec<Option<Vec<String>>>,
  995}
  996
  997#[doc(hidden)]
  998pub struct RenameState {
  999    pub range: Range<Anchor>,
 1000    pub old_name: Arc<str>,
 1001    pub editor: Entity<Editor>,
 1002    block_id: CustomBlockId,
 1003}
 1004
 1005struct InvalidationStack<T>(Vec<T>);
 1006
 1007struct RegisteredInlineCompletionProvider {
 1008    provider: Arc<dyn InlineCompletionProviderHandle>,
 1009    _subscription: Subscription,
 1010}
 1011
 1012#[derive(Debug, PartialEq, Eq)]
 1013struct ActiveDiagnosticGroup {
 1014    primary_range: Range<Anchor>,
 1015    primary_message: String,
 1016    group_id: usize,
 1017    blocks: HashMap<CustomBlockId, Diagnostic>,
 1018    is_valid: bool,
 1019}
 1020
 1021#[derive(Serialize, Deserialize, Clone, Debug)]
 1022pub struct ClipboardSelection {
 1023    /// The number of bytes in this selection.
 1024    pub len: usize,
 1025    /// Whether this was a full-line selection.
 1026    pub is_entire_line: bool,
 1027    /// The indentation of the first line when this content was originally copied.
 1028    pub first_line_indent: u32,
 1029}
 1030
 1031// selections, scroll behavior, was newest selection reversed
 1032type SelectSyntaxNodeHistoryState = (
 1033    Box<[Selection<usize>]>,
 1034    SelectSyntaxNodeScrollBehavior,
 1035    bool,
 1036);
 1037
 1038#[derive(Default)]
 1039struct SelectSyntaxNodeHistory {
 1040    stack: Vec<SelectSyntaxNodeHistoryState>,
 1041    // disable temporarily to allow changing selections without losing the stack
 1042    pub disable_clearing: bool,
 1043}
 1044
 1045impl SelectSyntaxNodeHistory {
 1046    pub fn try_clear(&mut self) {
 1047        if !self.disable_clearing {
 1048            self.stack.clear();
 1049        }
 1050    }
 1051
 1052    pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
 1053        self.stack.push(selection);
 1054    }
 1055
 1056    pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
 1057        self.stack.pop()
 1058    }
 1059}
 1060
 1061enum SelectSyntaxNodeScrollBehavior {
 1062    CursorTop,
 1063    CenterSelection,
 1064    CursorBottom,
 1065}
 1066
 1067#[derive(Debug)]
 1068pub(crate) struct NavigationData {
 1069    cursor_anchor: Anchor,
 1070    cursor_position: Point,
 1071    scroll_anchor: ScrollAnchor,
 1072    scroll_top_row: u32,
 1073}
 1074
 1075#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1076pub enum GotoDefinitionKind {
 1077    Symbol,
 1078    Declaration,
 1079    Type,
 1080    Implementation,
 1081}
 1082
 1083#[derive(Debug, Clone)]
 1084enum InlayHintRefreshReason {
 1085    ModifiersChanged(bool),
 1086    Toggle(bool),
 1087    SettingsChange(InlayHintSettings),
 1088    NewLinesShown,
 1089    BufferEdited(HashSet<Arc<Language>>),
 1090    RefreshRequested,
 1091    ExcerptsRemoved(Vec<ExcerptId>),
 1092}
 1093
 1094impl InlayHintRefreshReason {
 1095    fn description(&self) -> &'static str {
 1096        match self {
 1097            Self::ModifiersChanged(_) => "modifiers changed",
 1098            Self::Toggle(_) => "toggle",
 1099            Self::SettingsChange(_) => "settings change",
 1100            Self::NewLinesShown => "new lines shown",
 1101            Self::BufferEdited(_) => "buffer edited",
 1102            Self::RefreshRequested => "refresh requested",
 1103            Self::ExcerptsRemoved(_) => "excerpts removed",
 1104        }
 1105    }
 1106}
 1107
 1108pub enum FormatTarget {
 1109    Buffers,
 1110    Ranges(Vec<Range<MultiBufferPoint>>),
 1111}
 1112
 1113pub(crate) struct FocusedBlock {
 1114    id: BlockId,
 1115    focus_handle: WeakFocusHandle,
 1116}
 1117
 1118#[derive(Clone)]
 1119enum JumpData {
 1120    MultiBufferRow {
 1121        row: MultiBufferRow,
 1122        line_offset_from_top: u32,
 1123    },
 1124    MultiBufferPoint {
 1125        excerpt_id: ExcerptId,
 1126        position: Point,
 1127        anchor: text::Anchor,
 1128        line_offset_from_top: u32,
 1129    },
 1130}
 1131
 1132pub enum MultibufferSelectionMode {
 1133    First,
 1134    All,
 1135}
 1136
 1137#[derive(Clone, Copy, Debug, Default)]
 1138pub struct RewrapOptions {
 1139    pub override_language_settings: bool,
 1140    pub preserve_existing_whitespace: bool,
 1141}
 1142
 1143impl Editor {
 1144    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1145        let buffer = cx.new(|cx| Buffer::local("", cx));
 1146        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1147        Self::new(
 1148            EditorMode::SingleLine { auto_width: false },
 1149            buffer,
 1150            None,
 1151            window,
 1152            cx,
 1153        )
 1154    }
 1155
 1156    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1157        let buffer = cx.new(|cx| Buffer::local("", cx));
 1158        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1159        Self::new(EditorMode::Full, buffer, None, window, cx)
 1160    }
 1161
 1162    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1163        let buffer = cx.new(|cx| Buffer::local("", cx));
 1164        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1165        Self::new(
 1166            EditorMode::SingleLine { auto_width: true },
 1167            buffer,
 1168            None,
 1169            window,
 1170            cx,
 1171        )
 1172    }
 1173
 1174    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1175        let buffer = cx.new(|cx| Buffer::local("", cx));
 1176        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1177        Self::new(
 1178            EditorMode::AutoHeight { max_lines },
 1179            buffer,
 1180            None,
 1181            window,
 1182            cx,
 1183        )
 1184    }
 1185
 1186    pub fn for_buffer(
 1187        buffer: Entity<Buffer>,
 1188        project: Option<Entity<Project>>,
 1189        window: &mut Window,
 1190        cx: &mut Context<Self>,
 1191    ) -> Self {
 1192        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1193        Self::new(EditorMode::Full, buffer, project, window, cx)
 1194    }
 1195
 1196    pub fn for_multibuffer(
 1197        buffer: Entity<MultiBuffer>,
 1198        project: Option<Entity<Project>>,
 1199        window: &mut Window,
 1200        cx: &mut Context<Self>,
 1201    ) -> Self {
 1202        Self::new(EditorMode::Full, buffer, project, window, cx)
 1203    }
 1204
 1205    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1206        let mut clone = Self::new(
 1207            self.mode,
 1208            self.buffer.clone(),
 1209            self.project.clone(),
 1210            window,
 1211            cx,
 1212        );
 1213        self.display_map.update(cx, |display_map, cx| {
 1214            let snapshot = display_map.snapshot(cx);
 1215            clone.display_map.update(cx, |display_map, cx| {
 1216                display_map.set_state(&snapshot, cx);
 1217            });
 1218        });
 1219        clone.folds_did_change(cx);
 1220        clone.selections.clone_state(&self.selections);
 1221        clone.scroll_manager.clone_state(&self.scroll_manager);
 1222        clone.searchable = self.searchable;
 1223        clone
 1224    }
 1225
 1226    pub fn new(
 1227        mode: EditorMode,
 1228        buffer: Entity<MultiBuffer>,
 1229        project: Option<Entity<Project>>,
 1230        window: &mut Window,
 1231        cx: &mut Context<Self>,
 1232    ) -> Self {
 1233        let style = window.text_style();
 1234        let font_size = style.font_size.to_pixels(window.rem_size());
 1235        let editor = cx.entity().downgrade();
 1236        let fold_placeholder = FoldPlaceholder {
 1237            constrain_width: true,
 1238            render: Arc::new(move |fold_id, fold_range, cx| {
 1239                let editor = editor.clone();
 1240                div()
 1241                    .id(fold_id)
 1242                    .bg(cx.theme().colors().ghost_element_background)
 1243                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1244                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1245                    .rounded_xs()
 1246                    .size_full()
 1247                    .cursor_pointer()
 1248                    .child("")
 1249                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1250                    .on_click(move |_, _window, cx| {
 1251                        editor
 1252                            .update(cx, |editor, cx| {
 1253                                editor.unfold_ranges(
 1254                                    &[fold_range.start..fold_range.end],
 1255                                    true,
 1256                                    false,
 1257                                    cx,
 1258                                );
 1259                                cx.stop_propagation();
 1260                            })
 1261                            .ok();
 1262                    })
 1263                    .into_any()
 1264            }),
 1265            merge_adjacent: true,
 1266            ..Default::default()
 1267        };
 1268        let display_map = cx.new(|cx| {
 1269            DisplayMap::new(
 1270                buffer.clone(),
 1271                style.font(),
 1272                font_size,
 1273                None,
 1274                FILE_HEADER_HEIGHT,
 1275                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1276                fold_placeholder,
 1277                cx,
 1278            )
 1279        });
 1280
 1281        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1282
 1283        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1284
 1285        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1286            .then(|| language_settings::SoftWrap::None);
 1287
 1288        let mut project_subscriptions = Vec::new();
 1289        if mode == EditorMode::Full {
 1290            if let Some(project) = project.as_ref() {
 1291                project_subscriptions.push(cx.subscribe_in(
 1292                    project,
 1293                    window,
 1294                    |editor, _, event, window, cx| match event {
 1295                        project::Event::RefreshCodeLens => {
 1296                            // we always query lens with actions, without storing them, always refreshing them
 1297                        }
 1298                        project::Event::RefreshInlayHints => {
 1299                            editor
 1300                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1301                        }
 1302                        project::Event::SnippetEdit(id, snippet_edits) => {
 1303                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1304                                let focus_handle = editor.focus_handle(cx);
 1305                                if focus_handle.is_focused(window) {
 1306                                    let snapshot = buffer.read(cx).snapshot();
 1307                                    for (range, snippet) in snippet_edits {
 1308                                        let editor_range =
 1309                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1310                                        editor
 1311                                            .insert_snippet(
 1312                                                &[editor_range],
 1313                                                snippet.clone(),
 1314                                                window,
 1315                                                cx,
 1316                                            )
 1317                                            .ok();
 1318                                    }
 1319                                }
 1320                            }
 1321                        }
 1322                        _ => {}
 1323                    },
 1324                ));
 1325                if let Some(task_inventory) = project
 1326                    .read(cx)
 1327                    .task_store()
 1328                    .read(cx)
 1329                    .task_inventory()
 1330                    .cloned()
 1331                {
 1332                    project_subscriptions.push(cx.observe_in(
 1333                        &task_inventory,
 1334                        window,
 1335                        |editor, _, window, cx| {
 1336                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1337                        },
 1338                    ));
 1339                };
 1340
 1341                project_subscriptions.push(cx.subscribe_in(
 1342                    &project.read(cx).breakpoint_store(),
 1343                    window,
 1344                    |editor, _, event, window, cx| match event {
 1345                        BreakpointStoreEvent::ActiveDebugLineChanged => {
 1346                            editor.go_to_active_debug_line(window, cx);
 1347                        }
 1348                        _ => {}
 1349                    },
 1350                ));
 1351            }
 1352        }
 1353
 1354        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1355
 1356        let inlay_hint_settings =
 1357            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1358        let focus_handle = cx.focus_handle();
 1359        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1360            .detach();
 1361        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1362            .detach();
 1363        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1364            .detach();
 1365        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1366            .detach();
 1367
 1368        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1369            Some(false)
 1370        } else {
 1371            None
 1372        };
 1373
 1374        let breakpoint_store = match (mode, project.as_ref()) {
 1375            (EditorMode::Full, Some(project)) => Some(project.read(cx).breakpoint_store()),
 1376            _ => None,
 1377        };
 1378
 1379        let mut code_action_providers = Vec::new();
 1380        let mut load_uncommitted_diff = None;
 1381        if let Some(project) = project.clone() {
 1382            load_uncommitted_diff = Some(
 1383                get_uncommitted_diff_for_buffer(
 1384                    &project,
 1385                    buffer.read(cx).all_buffers(),
 1386                    buffer.clone(),
 1387                    cx,
 1388                )
 1389                .shared(),
 1390            );
 1391            code_action_providers.push(Rc::new(project) as Rc<_>);
 1392        }
 1393
 1394        let mut this = Self {
 1395            focus_handle,
 1396            show_cursor_when_unfocused: false,
 1397            last_focused_descendant: None,
 1398            buffer: buffer.clone(),
 1399            display_map: display_map.clone(),
 1400            selections,
 1401            scroll_manager: ScrollManager::new(cx),
 1402            columnar_selection_tail: None,
 1403            add_selections_state: None,
 1404            select_next_state: None,
 1405            select_prev_state: None,
 1406            selection_history: Default::default(),
 1407            autoclose_regions: Default::default(),
 1408            snippet_stack: Default::default(),
 1409            select_syntax_node_history: SelectSyntaxNodeHistory::default(),
 1410            ime_transaction: Default::default(),
 1411            active_diagnostics: None,
 1412            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1413            inline_diagnostics_update: Task::ready(()),
 1414            inline_diagnostics: Vec::new(),
 1415            soft_wrap_mode_override,
 1416            hard_wrap: None,
 1417            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1418            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1419            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1420            project,
 1421            blink_manager: blink_manager.clone(),
 1422            show_local_selections: true,
 1423            show_scrollbars: true,
 1424            mode,
 1425            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1426            show_gutter: mode == EditorMode::Full,
 1427            show_line_numbers: None,
 1428            use_relative_line_numbers: None,
 1429            show_git_diff_gutter: None,
 1430            show_code_actions: None,
 1431            show_runnables: None,
 1432            show_breakpoints: None,
 1433            show_wrap_guides: None,
 1434            show_indent_guides,
 1435            placeholder_text: None,
 1436            highlight_order: 0,
 1437            highlighted_rows: HashMap::default(),
 1438            background_highlights: Default::default(),
 1439            gutter_highlights: TreeMap::default(),
 1440            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1441            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1442            nav_history: None,
 1443            context_menu: RefCell::new(None),
 1444            mouse_context_menu: None,
 1445            completion_tasks: Default::default(),
 1446            signature_help_state: SignatureHelpState::default(),
 1447            auto_signature_help: None,
 1448            find_all_references_task_sources: Vec::new(),
 1449            next_completion_id: 0,
 1450            next_inlay_id: 0,
 1451            code_action_providers,
 1452            available_code_actions: Default::default(),
 1453            code_actions_task: Default::default(),
 1454            selection_highlight_task: Default::default(),
 1455            document_highlights_task: Default::default(),
 1456            linked_editing_range_task: Default::default(),
 1457            pending_rename: Default::default(),
 1458            searchable: true,
 1459            cursor_shape: EditorSettings::get_global(cx)
 1460                .cursor_shape
 1461                .unwrap_or_default(),
 1462            current_line_highlight: None,
 1463            autoindent_mode: Some(AutoindentMode::EachLine),
 1464            collapse_matches: false,
 1465            workspace: None,
 1466            input_enabled: true,
 1467            use_modal_editing: mode == EditorMode::Full,
 1468            read_only: false,
 1469            use_autoclose: true,
 1470            use_auto_surround: true,
 1471            auto_replace_emoji_shortcode: false,
 1472            jsx_tag_auto_close_enabled_in_any_buffer: false,
 1473            leader_peer_id: None,
 1474            remote_id: None,
 1475            hover_state: Default::default(),
 1476            pending_mouse_down: None,
 1477            hovered_link_state: Default::default(),
 1478            edit_prediction_provider: None,
 1479            active_inline_completion: None,
 1480            stale_inline_completion_in_menu: None,
 1481            edit_prediction_preview: EditPredictionPreview::Inactive {
 1482                released_too_fast: false,
 1483            },
 1484            inline_diagnostics_enabled: mode == EditorMode::Full,
 1485            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1486
 1487            gutter_hovered: false,
 1488            pixel_position_of_newest_cursor: None,
 1489            last_bounds: None,
 1490            last_position_map: None,
 1491            expect_bounds_change: None,
 1492            gutter_dimensions: GutterDimensions::default(),
 1493            style: None,
 1494            show_cursor_names: false,
 1495            hovered_cursors: Default::default(),
 1496            next_editor_action_id: EditorActionId::default(),
 1497            editor_actions: Rc::default(),
 1498            inline_completions_hidden_for_vim_mode: false,
 1499            show_inline_completions_override: None,
 1500            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1501            edit_prediction_settings: EditPredictionSettings::Disabled,
 1502            edit_prediction_indent_conflict: false,
 1503            edit_prediction_requires_modifier_in_indent_conflict: true,
 1504            custom_context_menu: None,
 1505            show_git_blame_gutter: false,
 1506            show_git_blame_inline: false,
 1507            show_selection_menu: None,
 1508            show_git_blame_inline_delay_task: None,
 1509            git_blame_inline_tooltip: None,
 1510            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1511            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1512                .session
 1513                .restore_unsaved_buffers,
 1514            blame: None,
 1515            blame_subscription: None,
 1516            tasks: Default::default(),
 1517
 1518            breakpoint_store,
 1519            gutter_breakpoint_indicator: None,
 1520            _subscriptions: vec![
 1521                cx.observe(&buffer, Self::on_buffer_changed),
 1522                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1523                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1524                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1525                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1526                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1527                cx.observe_window_activation(window, |editor, window, cx| {
 1528                    let active = window.is_window_active();
 1529                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1530                        if active {
 1531                            blink_manager.enable(cx);
 1532                        } else {
 1533                            blink_manager.disable(cx);
 1534                        }
 1535                    });
 1536                }),
 1537            ],
 1538            tasks_update_task: None,
 1539            linked_edit_ranges: Default::default(),
 1540            in_project_search: false,
 1541            previous_search_ranges: None,
 1542            breadcrumb_header: None,
 1543            focused_block: None,
 1544            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1545            addons: HashMap::default(),
 1546            registered_buffers: HashMap::default(),
 1547            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1548            selection_mark_mode: false,
 1549            toggle_fold_multiple_buffers: Task::ready(()),
 1550            serialize_selections: Task::ready(()),
 1551            serialize_folds: Task::ready(()),
 1552            text_style_refinement: None,
 1553            load_diff_task: load_uncommitted_diff,
 1554        };
 1555        if let Some(breakpoints) = this.breakpoint_store.as_ref() {
 1556            this._subscriptions
 1557                .push(cx.observe(breakpoints, |_, _, cx| {
 1558                    cx.notify();
 1559                }));
 1560        }
 1561        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1562        this._subscriptions.extend(project_subscriptions);
 1563
 1564        this.end_selection(window, cx);
 1565        this.scroll_manager.show_scrollbar(window, cx);
 1566        jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
 1567
 1568        if mode == EditorMode::Full {
 1569            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1570            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1571
 1572            if this.git_blame_inline_enabled {
 1573                this.git_blame_inline_enabled = true;
 1574                this.start_git_blame_inline(false, window, cx);
 1575            }
 1576
 1577            this.go_to_active_debug_line(window, cx);
 1578
 1579            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1580                if let Some(project) = this.project.as_ref() {
 1581                    let handle = project.update(cx, |project, cx| {
 1582                        project.register_buffer_with_language_servers(&buffer, cx)
 1583                    });
 1584                    this.registered_buffers
 1585                        .insert(buffer.read(cx).remote_id(), handle);
 1586                }
 1587            }
 1588        }
 1589
 1590        this.report_editor_event("Editor Opened", None, cx);
 1591        this
 1592    }
 1593
 1594    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1595        self.mouse_context_menu
 1596            .as_ref()
 1597            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1598    }
 1599
 1600    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1601        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1602    }
 1603
 1604    fn key_context_internal(
 1605        &self,
 1606        has_active_edit_prediction: bool,
 1607        window: &Window,
 1608        cx: &App,
 1609    ) -> KeyContext {
 1610        let mut key_context = KeyContext::new_with_defaults();
 1611        key_context.add("Editor");
 1612        let mode = match self.mode {
 1613            EditorMode::SingleLine { .. } => "single_line",
 1614            EditorMode::AutoHeight { .. } => "auto_height",
 1615            EditorMode::Full => "full",
 1616        };
 1617
 1618        if EditorSettings::jupyter_enabled(cx) {
 1619            key_context.add("jupyter");
 1620        }
 1621
 1622        key_context.set("mode", mode);
 1623        if self.pending_rename.is_some() {
 1624            key_context.add("renaming");
 1625        }
 1626
 1627        match self.context_menu.borrow().as_ref() {
 1628            Some(CodeContextMenu::Completions(_)) => {
 1629                key_context.add("menu");
 1630                key_context.add("showing_completions");
 1631            }
 1632            Some(CodeContextMenu::CodeActions(_)) => {
 1633                key_context.add("menu");
 1634                key_context.add("showing_code_actions")
 1635            }
 1636            None => {}
 1637        }
 1638
 1639        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1640        if !self.focus_handle(cx).contains_focused(window, cx)
 1641            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1642        {
 1643            for addon in self.addons.values() {
 1644                addon.extend_key_context(&mut key_context, cx)
 1645            }
 1646        }
 1647
 1648        if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
 1649            if let Some(extension) = singleton_buffer
 1650                .read(cx)
 1651                .file()
 1652                .and_then(|file| file.path().extension()?.to_str())
 1653            {
 1654                key_context.set("extension", extension.to_string());
 1655            }
 1656        } else {
 1657            key_context.add("multibuffer");
 1658        }
 1659
 1660        if has_active_edit_prediction {
 1661            if self.edit_prediction_in_conflict() {
 1662                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1663            } else {
 1664                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1665                key_context.add("copilot_suggestion");
 1666            }
 1667        }
 1668
 1669        if self.selection_mark_mode {
 1670            key_context.add("selection_mode");
 1671        }
 1672
 1673        key_context
 1674    }
 1675
 1676    pub fn edit_prediction_in_conflict(&self) -> bool {
 1677        if !self.show_edit_predictions_in_menu() {
 1678            return false;
 1679        }
 1680
 1681        let showing_completions = self
 1682            .context_menu
 1683            .borrow()
 1684            .as_ref()
 1685            .map_or(false, |context| {
 1686                matches!(context, CodeContextMenu::Completions(_))
 1687            });
 1688
 1689        showing_completions
 1690            || self.edit_prediction_requires_modifier()
 1691            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1692            // bindings to insert tab characters.
 1693            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 1694    }
 1695
 1696    pub fn accept_edit_prediction_keybind(
 1697        &self,
 1698        window: &Window,
 1699        cx: &App,
 1700    ) -> AcceptEditPredictionBinding {
 1701        let key_context = self.key_context_internal(true, window, cx);
 1702        let in_conflict = self.edit_prediction_in_conflict();
 1703
 1704        AcceptEditPredictionBinding(
 1705            window
 1706                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1707                .into_iter()
 1708                .filter(|binding| {
 1709                    !in_conflict
 1710                        || binding
 1711                            .keystrokes()
 1712                            .first()
 1713                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1714                })
 1715                .rev()
 1716                .min_by_key(|binding| {
 1717                    binding
 1718                        .keystrokes()
 1719                        .first()
 1720                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1721                }),
 1722        )
 1723    }
 1724
 1725    pub fn new_file(
 1726        workspace: &mut Workspace,
 1727        _: &workspace::NewFile,
 1728        window: &mut Window,
 1729        cx: &mut Context<Workspace>,
 1730    ) {
 1731        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1732            "Failed to create buffer",
 1733            window,
 1734            cx,
 1735            |e, _, _| match e.error_code() {
 1736                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1737                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1738                e.error_tag("required").unwrap_or("the latest version")
 1739            )),
 1740                _ => None,
 1741            },
 1742        );
 1743    }
 1744
 1745    pub fn new_in_workspace(
 1746        workspace: &mut Workspace,
 1747        window: &mut Window,
 1748        cx: &mut Context<Workspace>,
 1749    ) -> Task<Result<Entity<Editor>>> {
 1750        let project = workspace.project().clone();
 1751        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1752
 1753        cx.spawn_in(window, async move |workspace, cx| {
 1754            let buffer = create.await?;
 1755            workspace.update_in(cx, |workspace, window, cx| {
 1756                let editor =
 1757                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1758                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1759                editor
 1760            })
 1761        })
 1762    }
 1763
 1764    fn new_file_vertical(
 1765        workspace: &mut Workspace,
 1766        _: &workspace::NewFileSplitVertical,
 1767        window: &mut Window,
 1768        cx: &mut Context<Workspace>,
 1769    ) {
 1770        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1771    }
 1772
 1773    fn new_file_horizontal(
 1774        workspace: &mut Workspace,
 1775        _: &workspace::NewFileSplitHorizontal,
 1776        window: &mut Window,
 1777        cx: &mut Context<Workspace>,
 1778    ) {
 1779        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1780    }
 1781
 1782    fn new_file_in_direction(
 1783        workspace: &mut Workspace,
 1784        direction: SplitDirection,
 1785        window: &mut Window,
 1786        cx: &mut Context<Workspace>,
 1787    ) {
 1788        let project = workspace.project().clone();
 1789        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1790
 1791        cx.spawn_in(window, async move |workspace, cx| {
 1792            let buffer = create.await?;
 1793            workspace.update_in(cx, move |workspace, window, cx| {
 1794                workspace.split_item(
 1795                    direction,
 1796                    Box::new(
 1797                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1798                    ),
 1799                    window,
 1800                    cx,
 1801                )
 1802            })?;
 1803            anyhow::Ok(())
 1804        })
 1805        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1806            match e.error_code() {
 1807                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1808                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1809                e.error_tag("required").unwrap_or("the latest version")
 1810            )),
 1811                _ => None,
 1812            }
 1813        });
 1814    }
 1815
 1816    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1817        self.leader_peer_id
 1818    }
 1819
 1820    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1821        &self.buffer
 1822    }
 1823
 1824    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1825        self.workspace.as_ref()?.0.upgrade()
 1826    }
 1827
 1828    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1829        self.buffer().read(cx).title(cx)
 1830    }
 1831
 1832    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1833        let git_blame_gutter_max_author_length = self
 1834            .render_git_blame_gutter(cx)
 1835            .then(|| {
 1836                if let Some(blame) = self.blame.as_ref() {
 1837                    let max_author_length =
 1838                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1839                    Some(max_author_length)
 1840                } else {
 1841                    None
 1842                }
 1843            })
 1844            .flatten();
 1845
 1846        EditorSnapshot {
 1847            mode: self.mode,
 1848            show_gutter: self.show_gutter,
 1849            show_line_numbers: self.show_line_numbers,
 1850            show_git_diff_gutter: self.show_git_diff_gutter,
 1851            show_code_actions: self.show_code_actions,
 1852            show_runnables: self.show_runnables,
 1853            show_breakpoints: self.show_breakpoints,
 1854            git_blame_gutter_max_author_length,
 1855            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1856            scroll_anchor: self.scroll_manager.anchor(),
 1857            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1858            placeholder_text: self.placeholder_text.clone(),
 1859            is_focused: self.focus_handle.is_focused(window),
 1860            current_line_highlight: self
 1861                .current_line_highlight
 1862                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1863            gutter_hovered: self.gutter_hovered,
 1864        }
 1865    }
 1866
 1867    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1868        self.buffer.read(cx).language_at(point, cx)
 1869    }
 1870
 1871    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1872        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1873    }
 1874
 1875    pub fn active_excerpt(
 1876        &self,
 1877        cx: &App,
 1878    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1879        self.buffer
 1880            .read(cx)
 1881            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1882    }
 1883
 1884    pub fn mode(&self) -> EditorMode {
 1885        self.mode
 1886    }
 1887
 1888    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1889        self.collaboration_hub.as_deref()
 1890    }
 1891
 1892    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1893        self.collaboration_hub = Some(hub);
 1894    }
 1895
 1896    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1897        self.in_project_search = in_project_search;
 1898    }
 1899
 1900    pub fn set_custom_context_menu(
 1901        &mut self,
 1902        f: impl 'static
 1903            + Fn(
 1904                &mut Self,
 1905                DisplayPoint,
 1906                &mut Window,
 1907                &mut Context<Self>,
 1908            ) -> Option<Entity<ui::ContextMenu>>,
 1909    ) {
 1910        self.custom_context_menu = Some(Box::new(f))
 1911    }
 1912
 1913    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1914        self.completion_provider = provider;
 1915    }
 1916
 1917    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1918        self.semantics_provider.clone()
 1919    }
 1920
 1921    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1922        self.semantics_provider = provider;
 1923    }
 1924
 1925    pub fn set_edit_prediction_provider<T>(
 1926        &mut self,
 1927        provider: Option<Entity<T>>,
 1928        window: &mut Window,
 1929        cx: &mut Context<Self>,
 1930    ) where
 1931        T: EditPredictionProvider,
 1932    {
 1933        self.edit_prediction_provider =
 1934            provider.map(|provider| RegisteredInlineCompletionProvider {
 1935                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1936                    if this.focus_handle.is_focused(window) {
 1937                        this.update_visible_inline_completion(window, cx);
 1938                    }
 1939                }),
 1940                provider: Arc::new(provider),
 1941            });
 1942        self.update_edit_prediction_settings(cx);
 1943        self.refresh_inline_completion(false, false, window, cx);
 1944    }
 1945
 1946    pub fn placeholder_text(&self) -> Option<&str> {
 1947        self.placeholder_text.as_deref()
 1948    }
 1949
 1950    pub fn set_placeholder_text(
 1951        &mut self,
 1952        placeholder_text: impl Into<Arc<str>>,
 1953        cx: &mut Context<Self>,
 1954    ) {
 1955        let placeholder_text = Some(placeholder_text.into());
 1956        if self.placeholder_text != placeholder_text {
 1957            self.placeholder_text = placeholder_text;
 1958            cx.notify();
 1959        }
 1960    }
 1961
 1962    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1963        self.cursor_shape = cursor_shape;
 1964
 1965        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1966        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1967
 1968        cx.notify();
 1969    }
 1970
 1971    pub fn set_current_line_highlight(
 1972        &mut self,
 1973        current_line_highlight: Option<CurrentLineHighlight>,
 1974    ) {
 1975        self.current_line_highlight = current_line_highlight;
 1976    }
 1977
 1978    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1979        self.collapse_matches = collapse_matches;
 1980    }
 1981
 1982    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1983        let buffers = self.buffer.read(cx).all_buffers();
 1984        let Some(project) = self.project.as_ref() else {
 1985            return;
 1986        };
 1987        project.update(cx, |project, cx| {
 1988            for buffer in buffers {
 1989                self.registered_buffers
 1990                    .entry(buffer.read(cx).remote_id())
 1991                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 1992            }
 1993        })
 1994    }
 1995
 1996    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1997        if self.collapse_matches {
 1998            return range.start..range.start;
 1999        }
 2000        range.clone()
 2001    }
 2002
 2003    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 2004        if self.display_map.read(cx).clip_at_line_ends != clip {
 2005            self.display_map
 2006                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2007        }
 2008    }
 2009
 2010    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2011        self.input_enabled = input_enabled;
 2012    }
 2013
 2014    pub fn set_inline_completions_hidden_for_vim_mode(
 2015        &mut self,
 2016        hidden: bool,
 2017        window: &mut Window,
 2018        cx: &mut Context<Self>,
 2019    ) {
 2020        if hidden != self.inline_completions_hidden_for_vim_mode {
 2021            self.inline_completions_hidden_for_vim_mode = hidden;
 2022            if hidden {
 2023                self.update_visible_inline_completion(window, cx);
 2024            } else {
 2025                self.refresh_inline_completion(true, false, window, cx);
 2026            }
 2027        }
 2028    }
 2029
 2030    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 2031        self.menu_inline_completions_policy = value;
 2032    }
 2033
 2034    pub fn set_autoindent(&mut self, autoindent: bool) {
 2035        if autoindent {
 2036            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2037        } else {
 2038            self.autoindent_mode = None;
 2039        }
 2040    }
 2041
 2042    pub fn read_only(&self, cx: &App) -> bool {
 2043        self.read_only || self.buffer.read(cx).read_only()
 2044    }
 2045
 2046    pub fn set_read_only(&mut self, read_only: bool) {
 2047        self.read_only = read_only;
 2048    }
 2049
 2050    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2051        self.use_autoclose = autoclose;
 2052    }
 2053
 2054    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2055        self.use_auto_surround = auto_surround;
 2056    }
 2057
 2058    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2059        self.auto_replace_emoji_shortcode = auto_replace;
 2060    }
 2061
 2062    pub fn toggle_edit_predictions(
 2063        &mut self,
 2064        _: &ToggleEditPrediction,
 2065        window: &mut Window,
 2066        cx: &mut Context<Self>,
 2067    ) {
 2068        if self.show_inline_completions_override.is_some() {
 2069            self.set_show_edit_predictions(None, window, cx);
 2070        } else {
 2071            let show_edit_predictions = !self.edit_predictions_enabled();
 2072            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 2073        }
 2074    }
 2075
 2076    pub fn set_show_edit_predictions(
 2077        &mut self,
 2078        show_edit_predictions: Option<bool>,
 2079        window: &mut Window,
 2080        cx: &mut Context<Self>,
 2081    ) {
 2082        self.show_inline_completions_override = show_edit_predictions;
 2083        self.update_edit_prediction_settings(cx);
 2084
 2085        if let Some(false) = show_edit_predictions {
 2086            self.discard_inline_completion(false, cx);
 2087        } else {
 2088            self.refresh_inline_completion(false, true, window, cx);
 2089        }
 2090    }
 2091
 2092    fn inline_completions_disabled_in_scope(
 2093        &self,
 2094        buffer: &Entity<Buffer>,
 2095        buffer_position: language::Anchor,
 2096        cx: &App,
 2097    ) -> bool {
 2098        let snapshot = buffer.read(cx).snapshot();
 2099        let settings = snapshot.settings_at(buffer_position, cx);
 2100
 2101        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2102            return false;
 2103        };
 2104
 2105        scope.override_name().map_or(false, |scope_name| {
 2106            settings
 2107                .edit_predictions_disabled_in
 2108                .iter()
 2109                .any(|s| s == scope_name)
 2110        })
 2111    }
 2112
 2113    pub fn set_use_modal_editing(&mut self, to: bool) {
 2114        self.use_modal_editing = to;
 2115    }
 2116
 2117    pub fn use_modal_editing(&self) -> bool {
 2118        self.use_modal_editing
 2119    }
 2120
 2121    fn selections_did_change(
 2122        &mut self,
 2123        local: bool,
 2124        old_cursor_position: &Anchor,
 2125        show_completions: bool,
 2126        window: &mut Window,
 2127        cx: &mut Context<Self>,
 2128    ) {
 2129        window.invalidate_character_coordinates();
 2130
 2131        // Copy selections to primary selection buffer
 2132        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2133        if local {
 2134            let selections = self.selections.all::<usize>(cx);
 2135            let buffer_handle = self.buffer.read(cx).read(cx);
 2136
 2137            let mut text = String::new();
 2138            for (index, selection) in selections.iter().enumerate() {
 2139                let text_for_selection = buffer_handle
 2140                    .text_for_range(selection.start..selection.end)
 2141                    .collect::<String>();
 2142
 2143                text.push_str(&text_for_selection);
 2144                if index != selections.len() - 1 {
 2145                    text.push('\n');
 2146                }
 2147            }
 2148
 2149            if !text.is_empty() {
 2150                cx.write_to_primary(ClipboardItem::new_string(text));
 2151            }
 2152        }
 2153
 2154        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2155            self.buffer.update(cx, |buffer, cx| {
 2156                buffer.set_active_selections(
 2157                    &self.selections.disjoint_anchors(),
 2158                    self.selections.line_mode,
 2159                    self.cursor_shape,
 2160                    cx,
 2161                )
 2162            });
 2163        }
 2164        let display_map = self
 2165            .display_map
 2166            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2167        let buffer = &display_map.buffer_snapshot;
 2168        self.add_selections_state = None;
 2169        self.select_next_state = None;
 2170        self.select_prev_state = None;
 2171        self.select_syntax_node_history.try_clear();
 2172        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2173        self.snippet_stack
 2174            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2175        self.take_rename(false, window, cx);
 2176
 2177        let new_cursor_position = self.selections.newest_anchor().head();
 2178
 2179        self.push_to_nav_history(
 2180            *old_cursor_position,
 2181            Some(new_cursor_position.to_point(buffer)),
 2182            false,
 2183            cx,
 2184        );
 2185
 2186        if local {
 2187            let new_cursor_position = self.selections.newest_anchor().head();
 2188            let mut context_menu = self.context_menu.borrow_mut();
 2189            let completion_menu = match context_menu.as_ref() {
 2190                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2191                _ => {
 2192                    *context_menu = None;
 2193                    None
 2194                }
 2195            };
 2196            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2197                if !self.registered_buffers.contains_key(&buffer_id) {
 2198                    if let Some(project) = self.project.as_ref() {
 2199                        project.update(cx, |project, cx| {
 2200                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2201                                return;
 2202                            };
 2203                            self.registered_buffers.insert(
 2204                                buffer_id,
 2205                                project.register_buffer_with_language_servers(&buffer, cx),
 2206                            );
 2207                        })
 2208                    }
 2209                }
 2210            }
 2211
 2212            if let Some(completion_menu) = completion_menu {
 2213                let cursor_position = new_cursor_position.to_offset(buffer);
 2214                let (word_range, kind) =
 2215                    buffer.surrounding_word(completion_menu.initial_position, true);
 2216                if kind == Some(CharKind::Word)
 2217                    && word_range.to_inclusive().contains(&cursor_position)
 2218                {
 2219                    let mut completion_menu = completion_menu.clone();
 2220                    drop(context_menu);
 2221
 2222                    let query = Self::completion_query(buffer, cursor_position);
 2223                    cx.spawn(async move |this, cx| {
 2224                        completion_menu
 2225                            .filter(query.as_deref(), cx.background_executor().clone())
 2226                            .await;
 2227
 2228                        this.update(cx, |this, cx| {
 2229                            let mut context_menu = this.context_menu.borrow_mut();
 2230                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2231                            else {
 2232                                return;
 2233                            };
 2234
 2235                            if menu.id > completion_menu.id {
 2236                                return;
 2237                            }
 2238
 2239                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2240                            drop(context_menu);
 2241                            cx.notify();
 2242                        })
 2243                    })
 2244                    .detach();
 2245
 2246                    if show_completions {
 2247                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2248                    }
 2249                } else {
 2250                    drop(context_menu);
 2251                    self.hide_context_menu(window, cx);
 2252                }
 2253            } else {
 2254                drop(context_menu);
 2255            }
 2256
 2257            hide_hover(self, cx);
 2258
 2259            if old_cursor_position.to_display_point(&display_map).row()
 2260                != new_cursor_position.to_display_point(&display_map).row()
 2261            {
 2262                self.available_code_actions.take();
 2263            }
 2264            self.refresh_code_actions(window, cx);
 2265            self.refresh_document_highlights(cx);
 2266            self.refresh_selected_text_highlights(window, cx);
 2267            refresh_matching_bracket_highlights(self, window, cx);
 2268            self.update_visible_inline_completion(window, cx);
 2269            self.edit_prediction_requires_modifier_in_indent_conflict = true;
 2270            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2271            if self.git_blame_inline_enabled {
 2272                self.start_inline_blame_timer(window, cx);
 2273            }
 2274        }
 2275
 2276        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2277        cx.emit(EditorEvent::SelectionsChanged { local });
 2278
 2279        let selections = &self.selections.disjoint;
 2280        if selections.len() == 1 {
 2281            cx.emit(SearchEvent::ActiveMatchChanged)
 2282        }
 2283        if local
 2284            && self.is_singleton(cx)
 2285            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
 2286        {
 2287            if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
 2288                let background_executor = cx.background_executor().clone();
 2289                let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2290                let snapshot = self.buffer().read(cx).snapshot(cx);
 2291                let selections = selections.clone();
 2292                self.serialize_selections = cx.background_spawn(async move {
 2293                    background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2294                    let selections = selections
 2295                        .iter()
 2296                        .map(|selection| {
 2297                            (
 2298                                selection.start.to_offset(&snapshot),
 2299                                selection.end.to_offset(&snapshot),
 2300                            )
 2301                        })
 2302                        .collect();
 2303
 2304                    DB.save_editor_selections(editor_id, workspace_id, selections)
 2305                        .await
 2306                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2307                        .log_err();
 2308                });
 2309            }
 2310        }
 2311
 2312        cx.notify();
 2313    }
 2314
 2315    fn folds_did_change(&mut self, cx: &mut Context<Self>) {
 2316        if !self.is_singleton(cx)
 2317            || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
 2318        {
 2319            return;
 2320        }
 2321
 2322        let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
 2323            return;
 2324        };
 2325        let background_executor = cx.background_executor().clone();
 2326        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2327        let snapshot = self.buffer().read(cx).snapshot(cx);
 2328        let folds = self.display_map.update(cx, |display_map, cx| {
 2329            display_map
 2330                .snapshot(cx)
 2331                .folds_in_range(0..snapshot.len())
 2332                .map(|fold| {
 2333                    (
 2334                        fold.range.start.to_offset(&snapshot),
 2335                        fold.range.end.to_offset(&snapshot),
 2336                    )
 2337                })
 2338                .collect()
 2339        });
 2340        self.serialize_folds = cx.background_spawn(async move {
 2341            background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2342            DB.save_editor_folds(editor_id, workspace_id, folds)
 2343                .await
 2344                .with_context(|| format!("persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"))
 2345                .log_err();
 2346        });
 2347    }
 2348
 2349    pub fn sync_selections(
 2350        &mut self,
 2351        other: Entity<Editor>,
 2352        cx: &mut Context<Self>,
 2353    ) -> gpui::Subscription {
 2354        let other_selections = other.read(cx).selections.disjoint.to_vec();
 2355        self.selections.change_with(cx, |selections| {
 2356            selections.select_anchors(other_selections);
 2357        });
 2358
 2359        let other_subscription =
 2360            cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
 2361                EditorEvent::SelectionsChanged { local: true } => {
 2362                    let other_selections = other.read(cx).selections.disjoint.to_vec();
 2363                    if other_selections.is_empty() {
 2364                        return;
 2365                    }
 2366                    this.selections.change_with(cx, |selections| {
 2367                        selections.select_anchors(other_selections);
 2368                    });
 2369                }
 2370                _ => {}
 2371            });
 2372
 2373        let this_subscription =
 2374            cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
 2375                EditorEvent::SelectionsChanged { local: true } => {
 2376                    let these_selections = this.selections.disjoint.to_vec();
 2377                    if these_selections.is_empty() {
 2378                        return;
 2379                    }
 2380                    other.update(cx, |other_editor, cx| {
 2381                        other_editor.selections.change_with(cx, |selections| {
 2382                            selections.select_anchors(these_selections);
 2383                        })
 2384                    });
 2385                }
 2386                _ => {}
 2387            });
 2388
 2389        Subscription::join(other_subscription, this_subscription)
 2390    }
 2391
 2392    pub fn change_selections<R>(
 2393        &mut self,
 2394        autoscroll: Option<Autoscroll>,
 2395        window: &mut Window,
 2396        cx: &mut Context<Self>,
 2397        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2398    ) -> R {
 2399        self.change_selections_inner(autoscroll, true, window, cx, change)
 2400    }
 2401
 2402    fn change_selections_inner<R>(
 2403        &mut self,
 2404        autoscroll: Option<Autoscroll>,
 2405        request_completions: bool,
 2406        window: &mut Window,
 2407        cx: &mut Context<Self>,
 2408        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2409    ) -> R {
 2410        let old_cursor_position = self.selections.newest_anchor().head();
 2411        self.push_to_selection_history();
 2412
 2413        let (changed, result) = self.selections.change_with(cx, change);
 2414
 2415        if changed {
 2416            if let Some(autoscroll) = autoscroll {
 2417                self.request_autoscroll(autoscroll, cx);
 2418            }
 2419            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2420
 2421            if self.should_open_signature_help_automatically(
 2422                &old_cursor_position,
 2423                self.signature_help_state.backspace_pressed(),
 2424                cx,
 2425            ) {
 2426                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2427            }
 2428            self.signature_help_state.set_backspace_pressed(false);
 2429        }
 2430
 2431        result
 2432    }
 2433
 2434    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2435    where
 2436        I: IntoIterator<Item = (Range<S>, T)>,
 2437        S: ToOffset,
 2438        T: Into<Arc<str>>,
 2439    {
 2440        if self.read_only(cx) {
 2441            return;
 2442        }
 2443
 2444        self.buffer
 2445            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2446    }
 2447
 2448    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2449    where
 2450        I: IntoIterator<Item = (Range<S>, T)>,
 2451        S: ToOffset,
 2452        T: Into<Arc<str>>,
 2453    {
 2454        if self.read_only(cx) {
 2455            return;
 2456        }
 2457
 2458        self.buffer.update(cx, |buffer, cx| {
 2459            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2460        });
 2461    }
 2462
 2463    pub fn edit_with_block_indent<I, S, T>(
 2464        &mut self,
 2465        edits: I,
 2466        original_indent_columns: Vec<Option<u32>>,
 2467        cx: &mut Context<Self>,
 2468    ) where
 2469        I: IntoIterator<Item = (Range<S>, T)>,
 2470        S: ToOffset,
 2471        T: Into<Arc<str>>,
 2472    {
 2473        if self.read_only(cx) {
 2474            return;
 2475        }
 2476
 2477        self.buffer.update(cx, |buffer, cx| {
 2478            buffer.edit(
 2479                edits,
 2480                Some(AutoindentMode::Block {
 2481                    original_indent_columns,
 2482                }),
 2483                cx,
 2484            )
 2485        });
 2486    }
 2487
 2488    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2489        self.hide_context_menu(window, cx);
 2490
 2491        match phase {
 2492            SelectPhase::Begin {
 2493                position,
 2494                add,
 2495                click_count,
 2496            } => self.begin_selection(position, add, click_count, window, cx),
 2497            SelectPhase::BeginColumnar {
 2498                position,
 2499                goal_column,
 2500                reset,
 2501            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2502            SelectPhase::Extend {
 2503                position,
 2504                click_count,
 2505            } => self.extend_selection(position, click_count, window, cx),
 2506            SelectPhase::Update {
 2507                position,
 2508                goal_column,
 2509                scroll_delta,
 2510            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2511            SelectPhase::End => self.end_selection(window, cx),
 2512        }
 2513    }
 2514
 2515    fn extend_selection(
 2516        &mut self,
 2517        position: DisplayPoint,
 2518        click_count: usize,
 2519        window: &mut Window,
 2520        cx: &mut Context<Self>,
 2521    ) {
 2522        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2523        let tail = self.selections.newest::<usize>(cx).tail();
 2524        self.begin_selection(position, false, click_count, window, cx);
 2525
 2526        let position = position.to_offset(&display_map, Bias::Left);
 2527        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2528
 2529        let mut pending_selection = self
 2530            .selections
 2531            .pending_anchor()
 2532            .expect("extend_selection not called with pending selection");
 2533        if position >= tail {
 2534            pending_selection.start = tail_anchor;
 2535        } else {
 2536            pending_selection.end = tail_anchor;
 2537            pending_selection.reversed = true;
 2538        }
 2539
 2540        let mut pending_mode = self.selections.pending_mode().unwrap();
 2541        match &mut pending_mode {
 2542            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2543            _ => {}
 2544        }
 2545
 2546        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2547            s.set_pending(pending_selection, pending_mode)
 2548        });
 2549    }
 2550
 2551    fn begin_selection(
 2552        &mut self,
 2553        position: DisplayPoint,
 2554        add: bool,
 2555        click_count: usize,
 2556        window: &mut Window,
 2557        cx: &mut Context<Self>,
 2558    ) {
 2559        if !self.focus_handle.is_focused(window) {
 2560            self.last_focused_descendant = None;
 2561            window.focus(&self.focus_handle);
 2562        }
 2563
 2564        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2565        let buffer = &display_map.buffer_snapshot;
 2566        let newest_selection = self.selections.newest_anchor().clone();
 2567        let position = display_map.clip_point(position, Bias::Left);
 2568
 2569        let start;
 2570        let end;
 2571        let mode;
 2572        let mut auto_scroll;
 2573        match click_count {
 2574            1 => {
 2575                start = buffer.anchor_before(position.to_point(&display_map));
 2576                end = start;
 2577                mode = SelectMode::Character;
 2578                auto_scroll = true;
 2579            }
 2580            2 => {
 2581                let range = movement::surrounding_word(&display_map, position);
 2582                start = buffer.anchor_before(range.start.to_point(&display_map));
 2583                end = buffer.anchor_before(range.end.to_point(&display_map));
 2584                mode = SelectMode::Word(start..end);
 2585                auto_scroll = true;
 2586            }
 2587            3 => {
 2588                let position = display_map
 2589                    .clip_point(position, Bias::Left)
 2590                    .to_point(&display_map);
 2591                let line_start = display_map.prev_line_boundary(position).0;
 2592                let next_line_start = buffer.clip_point(
 2593                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2594                    Bias::Left,
 2595                );
 2596                start = buffer.anchor_before(line_start);
 2597                end = buffer.anchor_before(next_line_start);
 2598                mode = SelectMode::Line(start..end);
 2599                auto_scroll = true;
 2600            }
 2601            _ => {
 2602                start = buffer.anchor_before(0);
 2603                end = buffer.anchor_before(buffer.len());
 2604                mode = SelectMode::All;
 2605                auto_scroll = false;
 2606            }
 2607        }
 2608        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2609
 2610        let point_to_delete: Option<usize> = {
 2611            let selected_points: Vec<Selection<Point>> =
 2612                self.selections.disjoint_in_range(start..end, cx);
 2613
 2614            if !add || click_count > 1 {
 2615                None
 2616            } else if !selected_points.is_empty() {
 2617                Some(selected_points[0].id)
 2618            } else {
 2619                let clicked_point_already_selected =
 2620                    self.selections.disjoint.iter().find(|selection| {
 2621                        selection.start.to_point(buffer) == start.to_point(buffer)
 2622                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2623                    });
 2624
 2625                clicked_point_already_selected.map(|selection| selection.id)
 2626            }
 2627        };
 2628
 2629        let selections_count = self.selections.count();
 2630
 2631        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2632            if let Some(point_to_delete) = point_to_delete {
 2633                s.delete(point_to_delete);
 2634
 2635                if selections_count == 1 {
 2636                    s.set_pending_anchor_range(start..end, mode);
 2637                }
 2638            } else {
 2639                if !add {
 2640                    s.clear_disjoint();
 2641                } else if click_count > 1 {
 2642                    s.delete(newest_selection.id)
 2643                }
 2644
 2645                s.set_pending_anchor_range(start..end, mode);
 2646            }
 2647        });
 2648    }
 2649
 2650    fn begin_columnar_selection(
 2651        &mut self,
 2652        position: DisplayPoint,
 2653        goal_column: u32,
 2654        reset: bool,
 2655        window: &mut Window,
 2656        cx: &mut Context<Self>,
 2657    ) {
 2658        if !self.focus_handle.is_focused(window) {
 2659            self.last_focused_descendant = None;
 2660            window.focus(&self.focus_handle);
 2661        }
 2662
 2663        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2664
 2665        if reset {
 2666            let pointer_position = display_map
 2667                .buffer_snapshot
 2668                .anchor_before(position.to_point(&display_map));
 2669
 2670            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2671                s.clear_disjoint();
 2672                s.set_pending_anchor_range(
 2673                    pointer_position..pointer_position,
 2674                    SelectMode::Character,
 2675                );
 2676            });
 2677        }
 2678
 2679        let tail = self.selections.newest::<Point>(cx).tail();
 2680        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2681
 2682        if !reset {
 2683            self.select_columns(
 2684                tail.to_display_point(&display_map),
 2685                position,
 2686                goal_column,
 2687                &display_map,
 2688                window,
 2689                cx,
 2690            );
 2691        }
 2692    }
 2693
 2694    fn update_selection(
 2695        &mut self,
 2696        position: DisplayPoint,
 2697        goal_column: u32,
 2698        scroll_delta: gpui::Point<f32>,
 2699        window: &mut Window,
 2700        cx: &mut Context<Self>,
 2701    ) {
 2702        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2703
 2704        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2705            let tail = tail.to_display_point(&display_map);
 2706            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2707        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2708            let buffer = self.buffer.read(cx).snapshot(cx);
 2709            let head;
 2710            let tail;
 2711            let mode = self.selections.pending_mode().unwrap();
 2712            match &mode {
 2713                SelectMode::Character => {
 2714                    head = position.to_point(&display_map);
 2715                    tail = pending.tail().to_point(&buffer);
 2716                }
 2717                SelectMode::Word(original_range) => {
 2718                    let original_display_range = original_range.start.to_display_point(&display_map)
 2719                        ..original_range.end.to_display_point(&display_map);
 2720                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2721                        ..original_display_range.end.to_point(&display_map);
 2722                    if movement::is_inside_word(&display_map, position)
 2723                        || original_display_range.contains(&position)
 2724                    {
 2725                        let word_range = movement::surrounding_word(&display_map, position);
 2726                        if word_range.start < original_display_range.start {
 2727                            head = word_range.start.to_point(&display_map);
 2728                        } else {
 2729                            head = word_range.end.to_point(&display_map);
 2730                        }
 2731                    } else {
 2732                        head = position.to_point(&display_map);
 2733                    }
 2734
 2735                    if head <= original_buffer_range.start {
 2736                        tail = original_buffer_range.end;
 2737                    } else {
 2738                        tail = original_buffer_range.start;
 2739                    }
 2740                }
 2741                SelectMode::Line(original_range) => {
 2742                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2743
 2744                    let position = display_map
 2745                        .clip_point(position, Bias::Left)
 2746                        .to_point(&display_map);
 2747                    let line_start = display_map.prev_line_boundary(position).0;
 2748                    let next_line_start = buffer.clip_point(
 2749                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2750                        Bias::Left,
 2751                    );
 2752
 2753                    if line_start < original_range.start {
 2754                        head = line_start
 2755                    } else {
 2756                        head = next_line_start
 2757                    }
 2758
 2759                    if head <= original_range.start {
 2760                        tail = original_range.end;
 2761                    } else {
 2762                        tail = original_range.start;
 2763                    }
 2764                }
 2765                SelectMode::All => {
 2766                    return;
 2767                }
 2768            };
 2769
 2770            if head < tail {
 2771                pending.start = buffer.anchor_before(head);
 2772                pending.end = buffer.anchor_before(tail);
 2773                pending.reversed = true;
 2774            } else {
 2775                pending.start = buffer.anchor_before(tail);
 2776                pending.end = buffer.anchor_before(head);
 2777                pending.reversed = false;
 2778            }
 2779
 2780            self.change_selections(None, window, cx, |s| {
 2781                s.set_pending(pending, mode);
 2782            });
 2783        } else {
 2784            log::error!("update_selection dispatched with no pending selection");
 2785            return;
 2786        }
 2787
 2788        self.apply_scroll_delta(scroll_delta, window, cx);
 2789        cx.notify();
 2790    }
 2791
 2792    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2793        self.columnar_selection_tail.take();
 2794        if self.selections.pending_anchor().is_some() {
 2795            let selections = self.selections.all::<usize>(cx);
 2796            self.change_selections(None, window, cx, |s| {
 2797                s.select(selections);
 2798                s.clear_pending();
 2799            });
 2800        }
 2801    }
 2802
 2803    fn select_columns(
 2804        &mut self,
 2805        tail: DisplayPoint,
 2806        head: DisplayPoint,
 2807        goal_column: u32,
 2808        display_map: &DisplaySnapshot,
 2809        window: &mut Window,
 2810        cx: &mut Context<Self>,
 2811    ) {
 2812        let start_row = cmp::min(tail.row(), head.row());
 2813        let end_row = cmp::max(tail.row(), head.row());
 2814        let start_column = cmp::min(tail.column(), goal_column);
 2815        let end_column = cmp::max(tail.column(), goal_column);
 2816        let reversed = start_column < tail.column();
 2817
 2818        let selection_ranges = (start_row.0..=end_row.0)
 2819            .map(DisplayRow)
 2820            .filter_map(|row| {
 2821                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2822                    let start = display_map
 2823                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2824                        .to_point(display_map);
 2825                    let end = display_map
 2826                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2827                        .to_point(display_map);
 2828                    if reversed {
 2829                        Some(end..start)
 2830                    } else {
 2831                        Some(start..end)
 2832                    }
 2833                } else {
 2834                    None
 2835                }
 2836            })
 2837            .collect::<Vec<_>>();
 2838
 2839        self.change_selections(None, window, cx, |s| {
 2840            s.select_ranges(selection_ranges);
 2841        });
 2842        cx.notify();
 2843    }
 2844
 2845    pub fn has_pending_nonempty_selection(&self) -> bool {
 2846        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2847            Some(Selection { start, end, .. }) => start != end,
 2848            None => false,
 2849        };
 2850
 2851        pending_nonempty_selection
 2852            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2853    }
 2854
 2855    pub fn has_pending_selection(&self) -> bool {
 2856        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2857    }
 2858
 2859    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2860        self.selection_mark_mode = false;
 2861
 2862        if self.clear_expanded_diff_hunks(cx) {
 2863            cx.notify();
 2864            return;
 2865        }
 2866        if self.dismiss_menus_and_popups(true, window, cx) {
 2867            return;
 2868        }
 2869
 2870        if self.mode == EditorMode::Full
 2871            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2872        {
 2873            return;
 2874        }
 2875
 2876        cx.propagate();
 2877    }
 2878
 2879    pub fn dismiss_menus_and_popups(
 2880        &mut self,
 2881        is_user_requested: bool,
 2882        window: &mut Window,
 2883        cx: &mut Context<Self>,
 2884    ) -> bool {
 2885        if self.take_rename(false, window, cx).is_some() {
 2886            return true;
 2887        }
 2888
 2889        if hide_hover(self, cx) {
 2890            return true;
 2891        }
 2892
 2893        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2894            return true;
 2895        }
 2896
 2897        if self.hide_context_menu(window, cx).is_some() {
 2898            return true;
 2899        }
 2900
 2901        if self.mouse_context_menu.take().is_some() {
 2902            return true;
 2903        }
 2904
 2905        if is_user_requested && self.discard_inline_completion(true, cx) {
 2906            return true;
 2907        }
 2908
 2909        if self.snippet_stack.pop().is_some() {
 2910            return true;
 2911        }
 2912
 2913        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2914            self.dismiss_diagnostics(cx);
 2915            return true;
 2916        }
 2917
 2918        false
 2919    }
 2920
 2921    fn linked_editing_ranges_for(
 2922        &self,
 2923        selection: Range<text::Anchor>,
 2924        cx: &App,
 2925    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2926        if self.linked_edit_ranges.is_empty() {
 2927            return None;
 2928        }
 2929        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2930            selection.end.buffer_id.and_then(|end_buffer_id| {
 2931                if selection.start.buffer_id != Some(end_buffer_id) {
 2932                    return None;
 2933                }
 2934                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2935                let snapshot = buffer.read(cx).snapshot();
 2936                self.linked_edit_ranges
 2937                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2938                    .map(|ranges| (ranges, snapshot, buffer))
 2939            })?;
 2940        use text::ToOffset as TO;
 2941        // find offset from the start of current range to current cursor position
 2942        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2943
 2944        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2945        let start_difference = start_offset - start_byte_offset;
 2946        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2947        let end_difference = end_offset - start_byte_offset;
 2948        // Current range has associated linked ranges.
 2949        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2950        for range in linked_ranges.iter() {
 2951            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2952            let end_offset = start_offset + end_difference;
 2953            let start_offset = start_offset + start_difference;
 2954            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2955                continue;
 2956            }
 2957            if self.selections.disjoint_anchor_ranges().any(|s| {
 2958                if s.start.buffer_id != selection.start.buffer_id
 2959                    || s.end.buffer_id != selection.end.buffer_id
 2960                {
 2961                    return false;
 2962                }
 2963                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2964                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2965            }) {
 2966                continue;
 2967            }
 2968            let start = buffer_snapshot.anchor_after(start_offset);
 2969            let end = buffer_snapshot.anchor_after(end_offset);
 2970            linked_edits
 2971                .entry(buffer.clone())
 2972                .or_default()
 2973                .push(start..end);
 2974        }
 2975        Some(linked_edits)
 2976    }
 2977
 2978    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2979        let text: Arc<str> = text.into();
 2980
 2981        if self.read_only(cx) {
 2982            return;
 2983        }
 2984
 2985        let selections = self.selections.all_adjusted(cx);
 2986        let mut bracket_inserted = false;
 2987        let mut edits = Vec::new();
 2988        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2989        let mut new_selections = Vec::with_capacity(selections.len());
 2990        let mut new_autoclose_regions = Vec::new();
 2991        let snapshot = self.buffer.read(cx).read(cx);
 2992
 2993        for (selection, autoclose_region) in
 2994            self.selections_with_autoclose_regions(selections, &snapshot)
 2995        {
 2996            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2997                // Determine if the inserted text matches the opening or closing
 2998                // bracket of any of this language's bracket pairs.
 2999                let mut bracket_pair = None;
 3000                let mut is_bracket_pair_start = false;
 3001                let mut is_bracket_pair_end = false;
 3002                if !text.is_empty() {
 3003                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3004                    //  and they are removing the character that triggered IME popup.
 3005                    for (pair, enabled) in scope.brackets() {
 3006                        if !pair.close && !pair.surround {
 3007                            continue;
 3008                        }
 3009
 3010                        if enabled && pair.start.ends_with(text.as_ref()) {
 3011                            let prefix_len = pair.start.len() - text.len();
 3012                            let preceding_text_matches_prefix = prefix_len == 0
 3013                                || (selection.start.column >= (prefix_len as u32)
 3014                                    && snapshot.contains_str_at(
 3015                                        Point::new(
 3016                                            selection.start.row,
 3017                                            selection.start.column - (prefix_len as u32),
 3018                                        ),
 3019                                        &pair.start[..prefix_len],
 3020                                    ));
 3021                            if preceding_text_matches_prefix {
 3022                                bracket_pair = Some(pair.clone());
 3023                                is_bracket_pair_start = true;
 3024                                break;
 3025                            }
 3026                        }
 3027                        if pair.end.as_str() == text.as_ref() {
 3028                            bracket_pair = Some(pair.clone());
 3029                            is_bracket_pair_end = true;
 3030                            break;
 3031                        }
 3032                    }
 3033                }
 3034
 3035                if let Some(bracket_pair) = bracket_pair {
 3036                    let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
 3037                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3038                    let auto_surround =
 3039                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3040                    if selection.is_empty() {
 3041                        if is_bracket_pair_start {
 3042                            // If the inserted text is a suffix of an opening bracket and the
 3043                            // selection is preceded by the rest of the opening bracket, then
 3044                            // insert the closing bracket.
 3045                            let following_text_allows_autoclose = snapshot
 3046                                .chars_at(selection.start)
 3047                                .next()
 3048                                .map_or(true, |c| scope.should_autoclose_before(c));
 3049
 3050                            let preceding_text_allows_autoclose = selection.start.column == 0
 3051                                || snapshot.reversed_chars_at(selection.start).next().map_or(
 3052                                    true,
 3053                                    |c| {
 3054                                        bracket_pair.start != bracket_pair.end
 3055                                            || !snapshot
 3056                                                .char_classifier_at(selection.start)
 3057                                                .is_word(c)
 3058                                    },
 3059                                );
 3060
 3061                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3062                                && bracket_pair.start.len() == 1
 3063                            {
 3064                                let target = bracket_pair.start.chars().next().unwrap();
 3065                                let current_line_count = snapshot
 3066                                    .reversed_chars_at(selection.start)
 3067                                    .take_while(|&c| c != '\n')
 3068                                    .filter(|&c| c == target)
 3069                                    .count();
 3070                                current_line_count % 2 == 1
 3071                            } else {
 3072                                false
 3073                            };
 3074
 3075                            if autoclose
 3076                                && bracket_pair.close
 3077                                && following_text_allows_autoclose
 3078                                && preceding_text_allows_autoclose
 3079                                && !is_closing_quote
 3080                            {
 3081                                let anchor = snapshot.anchor_before(selection.end);
 3082                                new_selections.push((selection.map(|_| anchor), text.len()));
 3083                                new_autoclose_regions.push((
 3084                                    anchor,
 3085                                    text.len(),
 3086                                    selection.id,
 3087                                    bracket_pair.clone(),
 3088                                ));
 3089                                edits.push((
 3090                                    selection.range(),
 3091                                    format!("{}{}", text, bracket_pair.end).into(),
 3092                                ));
 3093                                bracket_inserted = true;
 3094                                continue;
 3095                            }
 3096                        }
 3097
 3098                        if let Some(region) = autoclose_region {
 3099                            // If the selection is followed by an auto-inserted closing bracket,
 3100                            // then don't insert that closing bracket again; just move the selection
 3101                            // past the closing bracket.
 3102                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3103                                && text.as_ref() == region.pair.end.as_str();
 3104                            if should_skip {
 3105                                let anchor = snapshot.anchor_after(selection.end);
 3106                                new_selections
 3107                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3108                                continue;
 3109                            }
 3110                        }
 3111
 3112                        let always_treat_brackets_as_autoclosed = snapshot
 3113                            .language_settings_at(selection.start, cx)
 3114                            .always_treat_brackets_as_autoclosed;
 3115                        if always_treat_brackets_as_autoclosed
 3116                            && is_bracket_pair_end
 3117                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3118                        {
 3119                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3120                            // and the inserted text is a closing bracket and the selection is followed
 3121                            // by the closing bracket then move the selection past the closing bracket.
 3122                            let anchor = snapshot.anchor_after(selection.end);
 3123                            new_selections.push((selection.map(|_| anchor), text.len()));
 3124                            continue;
 3125                        }
 3126                    }
 3127                    // If an opening bracket is 1 character long and is typed while
 3128                    // text is selected, then surround that text with the bracket pair.
 3129                    else if auto_surround
 3130                        && bracket_pair.surround
 3131                        && is_bracket_pair_start
 3132                        && bracket_pair.start.chars().count() == 1
 3133                    {
 3134                        edits.push((selection.start..selection.start, text.clone()));
 3135                        edits.push((
 3136                            selection.end..selection.end,
 3137                            bracket_pair.end.as_str().into(),
 3138                        ));
 3139                        bracket_inserted = true;
 3140                        new_selections.push((
 3141                            Selection {
 3142                                id: selection.id,
 3143                                start: snapshot.anchor_after(selection.start),
 3144                                end: snapshot.anchor_before(selection.end),
 3145                                reversed: selection.reversed,
 3146                                goal: selection.goal,
 3147                            },
 3148                            0,
 3149                        ));
 3150                        continue;
 3151                    }
 3152                }
 3153            }
 3154
 3155            if self.auto_replace_emoji_shortcode
 3156                && selection.is_empty()
 3157                && text.as_ref().ends_with(':')
 3158            {
 3159                if let Some(possible_emoji_short_code) =
 3160                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3161                {
 3162                    if !possible_emoji_short_code.is_empty() {
 3163                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3164                            let emoji_shortcode_start = Point::new(
 3165                                selection.start.row,
 3166                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3167                            );
 3168
 3169                            // Remove shortcode from buffer
 3170                            edits.push((
 3171                                emoji_shortcode_start..selection.start,
 3172                                "".to_string().into(),
 3173                            ));
 3174                            new_selections.push((
 3175                                Selection {
 3176                                    id: selection.id,
 3177                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3178                                    end: snapshot.anchor_before(selection.start),
 3179                                    reversed: selection.reversed,
 3180                                    goal: selection.goal,
 3181                                },
 3182                                0,
 3183                            ));
 3184
 3185                            // Insert emoji
 3186                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3187                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3188                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3189
 3190                            continue;
 3191                        }
 3192                    }
 3193                }
 3194            }
 3195
 3196            // If not handling any auto-close operation, then just replace the selected
 3197            // text with the given input and move the selection to the end of the
 3198            // newly inserted text.
 3199            let anchor = snapshot.anchor_after(selection.end);
 3200            if !self.linked_edit_ranges.is_empty() {
 3201                let start_anchor = snapshot.anchor_before(selection.start);
 3202
 3203                let is_word_char = text.chars().next().map_or(true, |char| {
 3204                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3205                    classifier.is_word(char)
 3206                });
 3207
 3208                if is_word_char {
 3209                    if let Some(ranges) = self
 3210                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3211                    {
 3212                        for (buffer, edits) in ranges {
 3213                            linked_edits
 3214                                .entry(buffer.clone())
 3215                                .or_default()
 3216                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3217                        }
 3218                    }
 3219                }
 3220            }
 3221
 3222            new_selections.push((selection.map(|_| anchor), 0));
 3223            edits.push((selection.start..selection.end, text.clone()));
 3224        }
 3225
 3226        drop(snapshot);
 3227
 3228        self.transact(window, cx, |this, window, cx| {
 3229            let initial_buffer_versions =
 3230                jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
 3231
 3232            this.buffer.update(cx, |buffer, cx| {
 3233                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3234            });
 3235            for (buffer, edits) in linked_edits {
 3236                buffer.update(cx, |buffer, cx| {
 3237                    let snapshot = buffer.snapshot();
 3238                    let edits = edits
 3239                        .into_iter()
 3240                        .map(|(range, text)| {
 3241                            use text::ToPoint as TP;
 3242                            let end_point = TP::to_point(&range.end, &snapshot);
 3243                            let start_point = TP::to_point(&range.start, &snapshot);
 3244                            (start_point..end_point, text)
 3245                        })
 3246                        .sorted_by_key(|(range, _)| range.start);
 3247                    buffer.edit(edits, None, cx);
 3248                })
 3249            }
 3250            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3251            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3252            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3253            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3254                .zip(new_selection_deltas)
 3255                .map(|(selection, delta)| Selection {
 3256                    id: selection.id,
 3257                    start: selection.start + delta,
 3258                    end: selection.end + delta,
 3259                    reversed: selection.reversed,
 3260                    goal: SelectionGoal::None,
 3261                })
 3262                .collect::<Vec<_>>();
 3263
 3264            let mut i = 0;
 3265            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3266                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3267                let start = map.buffer_snapshot.anchor_before(position);
 3268                let end = map.buffer_snapshot.anchor_after(position);
 3269                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3270                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3271                        Ordering::Less => i += 1,
 3272                        Ordering::Greater => break,
 3273                        Ordering::Equal => {
 3274                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3275                                Ordering::Less => i += 1,
 3276                                Ordering::Equal => break,
 3277                                Ordering::Greater => break,
 3278                            }
 3279                        }
 3280                    }
 3281                }
 3282                this.autoclose_regions.insert(
 3283                    i,
 3284                    AutocloseRegion {
 3285                        selection_id,
 3286                        range: start..end,
 3287                        pair,
 3288                    },
 3289                );
 3290            }
 3291
 3292            let had_active_inline_completion = this.has_active_inline_completion();
 3293            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3294                s.select(new_selections)
 3295            });
 3296
 3297            if !bracket_inserted {
 3298                if let Some(on_type_format_task) =
 3299                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3300                {
 3301                    on_type_format_task.detach_and_log_err(cx);
 3302                }
 3303            }
 3304
 3305            let editor_settings = EditorSettings::get_global(cx);
 3306            if bracket_inserted
 3307                && (editor_settings.auto_signature_help
 3308                    || editor_settings.show_signature_help_after_edits)
 3309            {
 3310                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3311            }
 3312
 3313            let trigger_in_words =
 3314                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3315            if this.hard_wrap.is_some() {
 3316                let latest: Range<Point> = this.selections.newest(cx).range();
 3317                if latest.is_empty()
 3318                    && this
 3319                        .buffer()
 3320                        .read(cx)
 3321                        .snapshot(cx)
 3322                        .line_len(MultiBufferRow(latest.start.row))
 3323                        == latest.start.column
 3324                {
 3325                    this.rewrap_impl(
 3326                        RewrapOptions {
 3327                            override_language_settings: true,
 3328                            preserve_existing_whitespace: true,
 3329                        },
 3330                        cx,
 3331                    )
 3332                }
 3333            }
 3334            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3335            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3336            this.refresh_inline_completion(true, false, window, cx);
 3337            jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
 3338        });
 3339    }
 3340
 3341    fn find_possible_emoji_shortcode_at_position(
 3342        snapshot: &MultiBufferSnapshot,
 3343        position: Point,
 3344    ) -> Option<String> {
 3345        let mut chars = Vec::new();
 3346        let mut found_colon = false;
 3347        for char in snapshot.reversed_chars_at(position).take(100) {
 3348            // Found a possible emoji shortcode in the middle of the buffer
 3349            if found_colon {
 3350                if char.is_whitespace() {
 3351                    chars.reverse();
 3352                    return Some(chars.iter().collect());
 3353                }
 3354                // If the previous character is not a whitespace, we are in the middle of a word
 3355                // and we only want to complete the shortcode if the word is made up of other emojis
 3356                let mut containing_word = String::new();
 3357                for ch in snapshot
 3358                    .reversed_chars_at(position)
 3359                    .skip(chars.len() + 1)
 3360                    .take(100)
 3361                {
 3362                    if ch.is_whitespace() {
 3363                        break;
 3364                    }
 3365                    containing_word.push(ch);
 3366                }
 3367                let containing_word = containing_word.chars().rev().collect::<String>();
 3368                if util::word_consists_of_emojis(containing_word.as_str()) {
 3369                    chars.reverse();
 3370                    return Some(chars.iter().collect());
 3371                }
 3372            }
 3373
 3374            if char.is_whitespace() || !char.is_ascii() {
 3375                return None;
 3376            }
 3377            if char == ':' {
 3378                found_colon = true;
 3379            } else {
 3380                chars.push(char);
 3381            }
 3382        }
 3383        // Found a possible emoji shortcode at the beginning of the buffer
 3384        chars.reverse();
 3385        Some(chars.iter().collect())
 3386    }
 3387
 3388    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3389        self.transact(window, cx, |this, window, cx| {
 3390            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3391                let selections = this.selections.all::<usize>(cx);
 3392                let multi_buffer = this.buffer.read(cx);
 3393                let buffer = multi_buffer.snapshot(cx);
 3394                selections
 3395                    .iter()
 3396                    .map(|selection| {
 3397                        let start_point = selection.start.to_point(&buffer);
 3398                        let mut indent =
 3399                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3400                        indent.len = cmp::min(indent.len, start_point.column);
 3401                        let start = selection.start;
 3402                        let end = selection.end;
 3403                        let selection_is_empty = start == end;
 3404                        let language_scope = buffer.language_scope_at(start);
 3405                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3406                            &language_scope
 3407                        {
 3408                            let insert_extra_newline =
 3409                                insert_extra_newline_brackets(&buffer, start..end, language)
 3410                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3411
 3412                            // Comment extension on newline is allowed only for cursor selections
 3413                            let comment_delimiter = maybe!({
 3414                                if !selection_is_empty {
 3415                                    return None;
 3416                                }
 3417
 3418                                if !multi_buffer.language_settings(cx).extend_comment_on_newline {
 3419                                    return None;
 3420                                }
 3421
 3422                                let delimiters = language.line_comment_prefixes();
 3423                                let max_len_of_delimiter =
 3424                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3425                                let (snapshot, range) =
 3426                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3427
 3428                                let mut index_of_first_non_whitespace = 0;
 3429                                let comment_candidate = snapshot
 3430                                    .chars_for_range(range)
 3431                                    .skip_while(|c| {
 3432                                        let should_skip = c.is_whitespace();
 3433                                        if should_skip {
 3434                                            index_of_first_non_whitespace += 1;
 3435                                        }
 3436                                        should_skip
 3437                                    })
 3438                                    .take(max_len_of_delimiter)
 3439                                    .collect::<String>();
 3440                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3441                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3442                                })?;
 3443                                let cursor_is_placed_after_comment_marker =
 3444                                    index_of_first_non_whitespace + comment_prefix.len()
 3445                                        <= start_point.column as usize;
 3446                                if cursor_is_placed_after_comment_marker {
 3447                                    Some(comment_prefix.clone())
 3448                                } else {
 3449                                    None
 3450                                }
 3451                            });
 3452                            (comment_delimiter, insert_extra_newline)
 3453                        } else {
 3454                            (None, false)
 3455                        };
 3456
 3457                        let capacity_for_delimiter = comment_delimiter
 3458                            .as_deref()
 3459                            .map(str::len)
 3460                            .unwrap_or_default();
 3461                        let mut new_text =
 3462                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3463                        new_text.push('\n');
 3464                        new_text.extend(indent.chars());
 3465                        if let Some(delimiter) = &comment_delimiter {
 3466                            new_text.push_str(delimiter);
 3467                        }
 3468                        if insert_extra_newline {
 3469                            new_text = new_text.repeat(2);
 3470                        }
 3471
 3472                        let anchor = buffer.anchor_after(end);
 3473                        let new_selection = selection.map(|_| anchor);
 3474                        (
 3475                            (start..end, new_text),
 3476                            (insert_extra_newline, new_selection),
 3477                        )
 3478                    })
 3479                    .unzip()
 3480            };
 3481
 3482            this.edit_with_autoindent(edits, cx);
 3483            let buffer = this.buffer.read(cx).snapshot(cx);
 3484            let new_selections = selection_fixup_info
 3485                .into_iter()
 3486                .map(|(extra_newline_inserted, new_selection)| {
 3487                    let mut cursor = new_selection.end.to_point(&buffer);
 3488                    if extra_newline_inserted {
 3489                        cursor.row -= 1;
 3490                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3491                    }
 3492                    new_selection.map(|_| cursor)
 3493                })
 3494                .collect();
 3495
 3496            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3497                s.select(new_selections)
 3498            });
 3499            this.refresh_inline_completion(true, false, window, cx);
 3500        });
 3501    }
 3502
 3503    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3504        let buffer = self.buffer.read(cx);
 3505        let snapshot = buffer.snapshot(cx);
 3506
 3507        let mut edits = Vec::new();
 3508        let mut rows = Vec::new();
 3509
 3510        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3511            let cursor = selection.head();
 3512            let row = cursor.row;
 3513
 3514            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3515
 3516            let newline = "\n".to_string();
 3517            edits.push((start_of_line..start_of_line, newline));
 3518
 3519            rows.push(row + rows_inserted as u32);
 3520        }
 3521
 3522        self.transact(window, cx, |editor, window, cx| {
 3523            editor.edit(edits, cx);
 3524
 3525            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3526                let mut index = 0;
 3527                s.move_cursors_with(|map, _, _| {
 3528                    let row = rows[index];
 3529                    index += 1;
 3530
 3531                    let point = Point::new(row, 0);
 3532                    let boundary = map.next_line_boundary(point).1;
 3533                    let clipped = map.clip_point(boundary, Bias::Left);
 3534
 3535                    (clipped, SelectionGoal::None)
 3536                });
 3537            });
 3538
 3539            let mut indent_edits = Vec::new();
 3540            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3541            for row in rows {
 3542                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3543                for (row, indent) in indents {
 3544                    if indent.len == 0 {
 3545                        continue;
 3546                    }
 3547
 3548                    let text = match indent.kind {
 3549                        IndentKind::Space => " ".repeat(indent.len as usize),
 3550                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3551                    };
 3552                    let point = Point::new(row.0, 0);
 3553                    indent_edits.push((point..point, text));
 3554                }
 3555            }
 3556            editor.edit(indent_edits, cx);
 3557        });
 3558    }
 3559
 3560    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3561        let buffer = self.buffer.read(cx);
 3562        let snapshot = buffer.snapshot(cx);
 3563
 3564        let mut edits = Vec::new();
 3565        let mut rows = Vec::new();
 3566        let mut rows_inserted = 0;
 3567
 3568        for selection in self.selections.all_adjusted(cx) {
 3569            let cursor = selection.head();
 3570            let row = cursor.row;
 3571
 3572            let point = Point::new(row + 1, 0);
 3573            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3574
 3575            let newline = "\n".to_string();
 3576            edits.push((start_of_line..start_of_line, newline));
 3577
 3578            rows_inserted += 1;
 3579            rows.push(row + rows_inserted);
 3580        }
 3581
 3582        self.transact(window, cx, |editor, window, cx| {
 3583            editor.edit(edits, cx);
 3584
 3585            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3586                let mut index = 0;
 3587                s.move_cursors_with(|map, _, _| {
 3588                    let row = rows[index];
 3589                    index += 1;
 3590
 3591                    let point = Point::new(row, 0);
 3592                    let boundary = map.next_line_boundary(point).1;
 3593                    let clipped = map.clip_point(boundary, Bias::Left);
 3594
 3595                    (clipped, SelectionGoal::None)
 3596                });
 3597            });
 3598
 3599            let mut indent_edits = Vec::new();
 3600            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3601            for row in rows {
 3602                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3603                for (row, indent) in indents {
 3604                    if indent.len == 0 {
 3605                        continue;
 3606                    }
 3607
 3608                    let text = match indent.kind {
 3609                        IndentKind::Space => " ".repeat(indent.len as usize),
 3610                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3611                    };
 3612                    let point = Point::new(row.0, 0);
 3613                    indent_edits.push((point..point, text));
 3614                }
 3615            }
 3616            editor.edit(indent_edits, cx);
 3617        });
 3618    }
 3619
 3620    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3621        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3622            original_indent_columns: Vec::new(),
 3623        });
 3624        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3625    }
 3626
 3627    fn insert_with_autoindent_mode(
 3628        &mut self,
 3629        text: &str,
 3630        autoindent_mode: Option<AutoindentMode>,
 3631        window: &mut Window,
 3632        cx: &mut Context<Self>,
 3633    ) {
 3634        if self.read_only(cx) {
 3635            return;
 3636        }
 3637
 3638        let text: Arc<str> = text.into();
 3639        self.transact(window, cx, |this, window, cx| {
 3640            let old_selections = this.selections.all_adjusted(cx);
 3641            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3642                let anchors = {
 3643                    let snapshot = buffer.read(cx);
 3644                    old_selections
 3645                        .iter()
 3646                        .map(|s| {
 3647                            let anchor = snapshot.anchor_after(s.head());
 3648                            s.map(|_| anchor)
 3649                        })
 3650                        .collect::<Vec<_>>()
 3651                };
 3652                buffer.edit(
 3653                    old_selections
 3654                        .iter()
 3655                        .map(|s| (s.start..s.end, text.clone())),
 3656                    autoindent_mode,
 3657                    cx,
 3658                );
 3659                anchors
 3660            });
 3661
 3662            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3663                s.select_anchors(selection_anchors);
 3664            });
 3665
 3666            cx.notify();
 3667        });
 3668    }
 3669
 3670    fn trigger_completion_on_input(
 3671        &mut self,
 3672        text: &str,
 3673        trigger_in_words: bool,
 3674        window: &mut Window,
 3675        cx: &mut Context<Self>,
 3676    ) {
 3677        let ignore_completion_provider = self
 3678            .context_menu
 3679            .borrow()
 3680            .as_ref()
 3681            .map(|menu| match menu {
 3682                CodeContextMenu::Completions(completions_menu) => {
 3683                    completions_menu.ignore_completion_provider
 3684                }
 3685                CodeContextMenu::CodeActions(_) => false,
 3686            })
 3687            .unwrap_or(false);
 3688
 3689        if ignore_completion_provider {
 3690            self.show_word_completions(&ShowWordCompletions, window, cx);
 3691        } else if self.is_completion_trigger(text, trigger_in_words, cx) {
 3692            self.show_completions(
 3693                &ShowCompletions {
 3694                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3695                },
 3696                window,
 3697                cx,
 3698            );
 3699        } else {
 3700            self.hide_context_menu(window, cx);
 3701        }
 3702    }
 3703
 3704    fn is_completion_trigger(
 3705        &self,
 3706        text: &str,
 3707        trigger_in_words: bool,
 3708        cx: &mut Context<Self>,
 3709    ) -> bool {
 3710        let position = self.selections.newest_anchor().head();
 3711        let multibuffer = self.buffer.read(cx);
 3712        let Some(buffer) = position
 3713            .buffer_id
 3714            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3715        else {
 3716            return false;
 3717        };
 3718
 3719        if let Some(completion_provider) = &self.completion_provider {
 3720            completion_provider.is_completion_trigger(
 3721                &buffer,
 3722                position.text_anchor,
 3723                text,
 3724                trigger_in_words,
 3725                cx,
 3726            )
 3727        } else {
 3728            false
 3729        }
 3730    }
 3731
 3732    /// If any empty selections is touching the start of its innermost containing autoclose
 3733    /// region, expand it to select the brackets.
 3734    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3735        let selections = self.selections.all::<usize>(cx);
 3736        let buffer = self.buffer.read(cx).read(cx);
 3737        let new_selections = self
 3738            .selections_with_autoclose_regions(selections, &buffer)
 3739            .map(|(mut selection, region)| {
 3740                if !selection.is_empty() {
 3741                    return selection;
 3742                }
 3743
 3744                if let Some(region) = region {
 3745                    let mut range = region.range.to_offset(&buffer);
 3746                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3747                        range.start -= region.pair.start.len();
 3748                        if buffer.contains_str_at(range.start, &region.pair.start)
 3749                            && buffer.contains_str_at(range.end, &region.pair.end)
 3750                        {
 3751                            range.end += region.pair.end.len();
 3752                            selection.start = range.start;
 3753                            selection.end = range.end;
 3754
 3755                            return selection;
 3756                        }
 3757                    }
 3758                }
 3759
 3760                let always_treat_brackets_as_autoclosed = buffer
 3761                    .language_settings_at(selection.start, cx)
 3762                    .always_treat_brackets_as_autoclosed;
 3763
 3764                if !always_treat_brackets_as_autoclosed {
 3765                    return selection;
 3766                }
 3767
 3768                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3769                    for (pair, enabled) in scope.brackets() {
 3770                        if !enabled || !pair.close {
 3771                            continue;
 3772                        }
 3773
 3774                        if buffer.contains_str_at(selection.start, &pair.end) {
 3775                            let pair_start_len = pair.start.len();
 3776                            if buffer.contains_str_at(
 3777                                selection.start.saturating_sub(pair_start_len),
 3778                                &pair.start,
 3779                            ) {
 3780                                selection.start -= pair_start_len;
 3781                                selection.end += pair.end.len();
 3782
 3783                                return selection;
 3784                            }
 3785                        }
 3786                    }
 3787                }
 3788
 3789                selection
 3790            })
 3791            .collect();
 3792
 3793        drop(buffer);
 3794        self.change_selections(None, window, cx, |selections| {
 3795            selections.select(new_selections)
 3796        });
 3797    }
 3798
 3799    /// Iterate the given selections, and for each one, find the smallest surrounding
 3800    /// autoclose region. This uses the ordering of the selections and the autoclose
 3801    /// regions to avoid repeated comparisons.
 3802    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3803        &'a self,
 3804        selections: impl IntoIterator<Item = Selection<D>>,
 3805        buffer: &'a MultiBufferSnapshot,
 3806    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3807        let mut i = 0;
 3808        let mut regions = self.autoclose_regions.as_slice();
 3809        selections.into_iter().map(move |selection| {
 3810            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3811
 3812            let mut enclosing = None;
 3813            while let Some(pair_state) = regions.get(i) {
 3814                if pair_state.range.end.to_offset(buffer) < range.start {
 3815                    regions = &regions[i + 1..];
 3816                    i = 0;
 3817                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3818                    break;
 3819                } else {
 3820                    if pair_state.selection_id == selection.id {
 3821                        enclosing = Some(pair_state);
 3822                    }
 3823                    i += 1;
 3824                }
 3825            }
 3826
 3827            (selection, enclosing)
 3828        })
 3829    }
 3830
 3831    /// Remove any autoclose regions that no longer contain their selection.
 3832    fn invalidate_autoclose_regions(
 3833        &mut self,
 3834        mut selections: &[Selection<Anchor>],
 3835        buffer: &MultiBufferSnapshot,
 3836    ) {
 3837        self.autoclose_regions.retain(|state| {
 3838            let mut i = 0;
 3839            while let Some(selection) = selections.get(i) {
 3840                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3841                    selections = &selections[1..];
 3842                    continue;
 3843                }
 3844                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3845                    break;
 3846                }
 3847                if selection.id == state.selection_id {
 3848                    return true;
 3849                } else {
 3850                    i += 1;
 3851                }
 3852            }
 3853            false
 3854        });
 3855    }
 3856
 3857    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3858        let offset = position.to_offset(buffer);
 3859        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3860        if offset > word_range.start && kind == Some(CharKind::Word) {
 3861            Some(
 3862                buffer
 3863                    .text_for_range(word_range.start..offset)
 3864                    .collect::<String>(),
 3865            )
 3866        } else {
 3867            None
 3868        }
 3869    }
 3870
 3871    pub fn toggle_inlay_hints(
 3872        &mut self,
 3873        _: &ToggleInlayHints,
 3874        _: &mut Window,
 3875        cx: &mut Context<Self>,
 3876    ) {
 3877        self.refresh_inlay_hints(
 3878            InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
 3879            cx,
 3880        );
 3881    }
 3882
 3883    pub fn inlay_hints_enabled(&self) -> bool {
 3884        self.inlay_hint_cache.enabled
 3885    }
 3886
 3887    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3888        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3889            return;
 3890        }
 3891
 3892        let reason_description = reason.description();
 3893        let ignore_debounce = matches!(
 3894            reason,
 3895            InlayHintRefreshReason::SettingsChange(_)
 3896                | InlayHintRefreshReason::Toggle(_)
 3897                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3898                | InlayHintRefreshReason::ModifiersChanged(_)
 3899        );
 3900        let (invalidate_cache, required_languages) = match reason {
 3901            InlayHintRefreshReason::ModifiersChanged(enabled) => {
 3902                match self.inlay_hint_cache.modifiers_override(enabled) {
 3903                    Some(enabled) => {
 3904                        if enabled {
 3905                            (InvalidationStrategy::RefreshRequested, None)
 3906                        } else {
 3907                            self.splice_inlays(
 3908                                &self
 3909                                    .visible_inlay_hints(cx)
 3910                                    .iter()
 3911                                    .map(|inlay| inlay.id)
 3912                                    .collect::<Vec<InlayId>>(),
 3913                                Vec::new(),
 3914                                cx,
 3915                            );
 3916                            return;
 3917                        }
 3918                    }
 3919                    None => return,
 3920                }
 3921            }
 3922            InlayHintRefreshReason::Toggle(enabled) => {
 3923                if self.inlay_hint_cache.toggle(enabled) {
 3924                    if enabled {
 3925                        (InvalidationStrategy::RefreshRequested, None)
 3926                    } else {
 3927                        self.splice_inlays(
 3928                            &self
 3929                                .visible_inlay_hints(cx)
 3930                                .iter()
 3931                                .map(|inlay| inlay.id)
 3932                                .collect::<Vec<InlayId>>(),
 3933                            Vec::new(),
 3934                            cx,
 3935                        );
 3936                        return;
 3937                    }
 3938                } else {
 3939                    return;
 3940                }
 3941            }
 3942            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3943                match self.inlay_hint_cache.update_settings(
 3944                    &self.buffer,
 3945                    new_settings,
 3946                    self.visible_inlay_hints(cx),
 3947                    cx,
 3948                ) {
 3949                    ControlFlow::Break(Some(InlaySplice {
 3950                        to_remove,
 3951                        to_insert,
 3952                    })) => {
 3953                        self.splice_inlays(&to_remove, to_insert, cx);
 3954                        return;
 3955                    }
 3956                    ControlFlow::Break(None) => return,
 3957                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3958                }
 3959            }
 3960            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3961                if let Some(InlaySplice {
 3962                    to_remove,
 3963                    to_insert,
 3964                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3965                {
 3966                    self.splice_inlays(&to_remove, to_insert, cx);
 3967                }
 3968                return;
 3969            }
 3970            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3971            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3972                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3973            }
 3974            InlayHintRefreshReason::RefreshRequested => {
 3975                (InvalidationStrategy::RefreshRequested, None)
 3976            }
 3977        };
 3978
 3979        if let Some(InlaySplice {
 3980            to_remove,
 3981            to_insert,
 3982        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3983            reason_description,
 3984            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3985            invalidate_cache,
 3986            ignore_debounce,
 3987            cx,
 3988        ) {
 3989            self.splice_inlays(&to_remove, to_insert, cx);
 3990        }
 3991    }
 3992
 3993    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3994        self.display_map
 3995            .read(cx)
 3996            .current_inlays()
 3997            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3998            .cloned()
 3999            .collect()
 4000    }
 4001
 4002    pub fn excerpts_for_inlay_hints_query(
 4003        &self,
 4004        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4005        cx: &mut Context<Editor>,
 4006    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 4007        let Some(project) = self.project.as_ref() else {
 4008            return HashMap::default();
 4009        };
 4010        let project = project.read(cx);
 4011        let multi_buffer = self.buffer().read(cx);
 4012        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4013        let multi_buffer_visible_start = self
 4014            .scroll_manager
 4015            .anchor()
 4016            .anchor
 4017            .to_point(&multi_buffer_snapshot);
 4018        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4019            multi_buffer_visible_start
 4020                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4021            Bias::Left,
 4022        );
 4023        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4024        multi_buffer_snapshot
 4025            .range_to_buffer_ranges(multi_buffer_visible_range)
 4026            .into_iter()
 4027            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4028            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 4029                let buffer_file = project::File::from_dyn(buffer.file())?;
 4030                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4031                let worktree_entry = buffer_worktree
 4032                    .read(cx)
 4033                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4034                if worktree_entry.is_ignored {
 4035                    return None;
 4036                }
 4037
 4038                let language = buffer.language()?;
 4039                if let Some(restrict_to_languages) = restrict_to_languages {
 4040                    if !restrict_to_languages.contains(language) {
 4041                        return None;
 4042                    }
 4043                }
 4044                Some((
 4045                    excerpt_id,
 4046                    (
 4047                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 4048                        buffer.version().clone(),
 4049                        excerpt_visible_range,
 4050                    ),
 4051                ))
 4052            })
 4053            .collect()
 4054    }
 4055
 4056    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 4057        TextLayoutDetails {
 4058            text_system: window.text_system().clone(),
 4059            editor_style: self.style.clone().unwrap(),
 4060            rem_size: window.rem_size(),
 4061            scroll_anchor: self.scroll_manager.anchor(),
 4062            visible_rows: self.visible_line_count(),
 4063            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4064        }
 4065    }
 4066
 4067    pub fn splice_inlays(
 4068        &self,
 4069        to_remove: &[InlayId],
 4070        to_insert: Vec<Inlay>,
 4071        cx: &mut Context<Self>,
 4072    ) {
 4073        self.display_map.update(cx, |display_map, cx| {
 4074            display_map.splice_inlays(to_remove, to_insert, cx)
 4075        });
 4076        cx.notify();
 4077    }
 4078
 4079    fn trigger_on_type_formatting(
 4080        &self,
 4081        input: String,
 4082        window: &mut Window,
 4083        cx: &mut Context<Self>,
 4084    ) -> Option<Task<Result<()>>> {
 4085        if input.len() != 1 {
 4086            return None;
 4087        }
 4088
 4089        let project = self.project.as_ref()?;
 4090        let position = self.selections.newest_anchor().head();
 4091        let (buffer, buffer_position) = self
 4092            .buffer
 4093            .read(cx)
 4094            .text_anchor_for_position(position, cx)?;
 4095
 4096        let settings = language_settings::language_settings(
 4097            buffer
 4098                .read(cx)
 4099                .language_at(buffer_position)
 4100                .map(|l| l.name()),
 4101            buffer.read(cx).file(),
 4102            cx,
 4103        );
 4104        if !settings.use_on_type_format {
 4105            return None;
 4106        }
 4107
 4108        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4109        // hence we do LSP request & edit on host side only — add formats to host's history.
 4110        let push_to_lsp_host_history = true;
 4111        // If this is not the host, append its history with new edits.
 4112        let push_to_client_history = project.read(cx).is_via_collab();
 4113
 4114        let on_type_formatting = project.update(cx, |project, cx| {
 4115            project.on_type_format(
 4116                buffer.clone(),
 4117                buffer_position,
 4118                input,
 4119                push_to_lsp_host_history,
 4120                cx,
 4121            )
 4122        });
 4123        Some(cx.spawn_in(window, async move |editor, cx| {
 4124            if let Some(transaction) = on_type_formatting.await? {
 4125                if push_to_client_history {
 4126                    buffer
 4127                        .update(cx, |buffer, _| {
 4128                            buffer.push_transaction(transaction, Instant::now());
 4129                        })
 4130                        .ok();
 4131                }
 4132                editor.update(cx, |editor, cx| {
 4133                    editor.refresh_document_highlights(cx);
 4134                })?;
 4135            }
 4136            Ok(())
 4137        }))
 4138    }
 4139
 4140    pub fn show_word_completions(
 4141        &mut self,
 4142        _: &ShowWordCompletions,
 4143        window: &mut Window,
 4144        cx: &mut Context<Self>,
 4145    ) {
 4146        self.open_completions_menu(true, None, window, cx);
 4147    }
 4148
 4149    pub fn show_completions(
 4150        &mut self,
 4151        options: &ShowCompletions,
 4152        window: &mut Window,
 4153        cx: &mut Context<Self>,
 4154    ) {
 4155        self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
 4156    }
 4157
 4158    fn open_completions_menu(
 4159        &mut self,
 4160        ignore_completion_provider: bool,
 4161        trigger: Option<&str>,
 4162        window: &mut Window,
 4163        cx: &mut Context<Self>,
 4164    ) {
 4165        if self.pending_rename.is_some() {
 4166            return;
 4167        }
 4168        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 4169            return;
 4170        }
 4171
 4172        let position = self.selections.newest_anchor().head();
 4173        if position.diff_base_anchor.is_some() {
 4174            return;
 4175        }
 4176        let (buffer, buffer_position) =
 4177            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4178                output
 4179            } else {
 4180                return;
 4181            };
 4182        let buffer_snapshot = buffer.read(cx).snapshot();
 4183        let show_completion_documentation = buffer_snapshot
 4184            .settings_at(buffer_position, cx)
 4185            .show_completion_documentation;
 4186
 4187        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4188
 4189        let trigger_kind = match trigger {
 4190            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4191                CompletionTriggerKind::TRIGGER_CHARACTER
 4192            }
 4193            _ => CompletionTriggerKind::INVOKED,
 4194        };
 4195        let completion_context = CompletionContext {
 4196            trigger_character: trigger.and_then(|trigger| {
 4197                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4198                    Some(String::from(trigger))
 4199                } else {
 4200                    None
 4201                }
 4202            }),
 4203            trigger_kind,
 4204        };
 4205
 4206        let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
 4207        let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
 4208            let word_to_exclude = buffer_snapshot
 4209                .text_for_range(old_range.clone())
 4210                .collect::<String>();
 4211            (
 4212                buffer_snapshot.anchor_before(old_range.start)
 4213                    ..buffer_snapshot.anchor_after(old_range.end),
 4214                Some(word_to_exclude),
 4215            )
 4216        } else {
 4217            (buffer_position..buffer_position, None)
 4218        };
 4219
 4220        let completion_settings = language_settings(
 4221            buffer_snapshot
 4222                .language_at(buffer_position)
 4223                .map(|language| language.name()),
 4224            buffer_snapshot.file(),
 4225            cx,
 4226        )
 4227        .completions;
 4228
 4229        // The document can be large, so stay in reasonable bounds when searching for words,
 4230        // otherwise completion pop-up might be slow to appear.
 4231        const WORD_LOOKUP_ROWS: u32 = 5_000;
 4232        let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
 4233        let min_word_search = buffer_snapshot.clip_point(
 4234            Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
 4235            Bias::Left,
 4236        );
 4237        let max_word_search = buffer_snapshot.clip_point(
 4238            Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
 4239            Bias::Right,
 4240        );
 4241        let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
 4242            ..buffer_snapshot.point_to_offset(max_word_search);
 4243
 4244        let provider = self
 4245            .completion_provider
 4246            .as_ref()
 4247            .filter(|_| !ignore_completion_provider);
 4248        let skip_digits = query
 4249            .as_ref()
 4250            .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
 4251
 4252        let (mut words, provided_completions) = match provider {
 4253            Some(provider) => {
 4254                let completions =
 4255                    provider.completions(&buffer, buffer_position, completion_context, window, cx);
 4256
 4257                let words = match completion_settings.words {
 4258                    WordsCompletionMode::Disabled => Task::ready(HashMap::default()),
 4259                    WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
 4260                        .background_spawn(async move {
 4261                            buffer_snapshot.words_in_range(WordsQuery {
 4262                                fuzzy_contents: None,
 4263                                range: word_search_range,
 4264                                skip_digits,
 4265                            })
 4266                        }),
 4267                };
 4268
 4269                (words, completions)
 4270            }
 4271            None => (
 4272                cx.background_spawn(async move {
 4273                    buffer_snapshot.words_in_range(WordsQuery {
 4274                        fuzzy_contents: None,
 4275                        range: word_search_range,
 4276                        skip_digits,
 4277                    })
 4278                }),
 4279                Task::ready(Ok(None)),
 4280            ),
 4281        };
 4282
 4283        let sort_completions = provider
 4284            .as_ref()
 4285            .map_or(true, |provider| provider.sort_completions());
 4286
 4287        let id = post_inc(&mut self.next_completion_id);
 4288        let task = cx.spawn_in(window, async move |editor, cx| {
 4289            async move {
 4290                editor.update(cx, |this, _| {
 4291                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4292                })?;
 4293
 4294                let mut completions = Vec::new();
 4295                if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
 4296                    completions.extend(provided_completions);
 4297                    if completion_settings.words == WordsCompletionMode::Fallback {
 4298                        words = Task::ready(HashMap::default());
 4299                    }
 4300                }
 4301
 4302                let mut words = words.await;
 4303                if let Some(word_to_exclude) = &word_to_exclude {
 4304                    words.remove(word_to_exclude);
 4305                }
 4306                for lsp_completion in &completions {
 4307                    words.remove(&lsp_completion.new_text);
 4308                }
 4309                completions.extend(words.into_iter().map(|(word, word_range)| Completion {
 4310                    old_range: old_range.clone(),
 4311                    new_text: word.clone(),
 4312                    label: CodeLabel::plain(word, None),
 4313                    documentation: None,
 4314                    source: CompletionSource::BufferWord {
 4315                        word_range,
 4316                        resolved: false,
 4317                    },
 4318                    confirm: None,
 4319                }));
 4320
 4321                let menu = if completions.is_empty() {
 4322                    None
 4323                } else {
 4324                    let mut menu = CompletionsMenu::new(
 4325                        id,
 4326                        sort_completions,
 4327                        show_completion_documentation,
 4328                        ignore_completion_provider,
 4329                        position,
 4330                        buffer.clone(),
 4331                        completions.into(),
 4332                    );
 4333
 4334                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4335                        .await;
 4336
 4337                    menu.visible().then_some(menu)
 4338                };
 4339
 4340                editor.update_in(cx, |editor, window, cx| {
 4341                    match editor.context_menu.borrow().as_ref() {
 4342                        None => {}
 4343                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4344                            if prev_menu.id > id {
 4345                                return;
 4346                            }
 4347                        }
 4348                        _ => return,
 4349                    }
 4350
 4351                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4352                        let mut menu = menu.unwrap();
 4353                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4354
 4355                        *editor.context_menu.borrow_mut() =
 4356                            Some(CodeContextMenu::Completions(menu));
 4357
 4358                        if editor.show_edit_predictions_in_menu() {
 4359                            editor.update_visible_inline_completion(window, cx);
 4360                        } else {
 4361                            editor.discard_inline_completion(false, cx);
 4362                        }
 4363
 4364                        cx.notify();
 4365                    } else if editor.completion_tasks.len() <= 1 {
 4366                        // If there are no more completion tasks and the last menu was
 4367                        // empty, we should hide it.
 4368                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4369                        // If it was already hidden and we don't show inline
 4370                        // completions in the menu, we should also show the
 4371                        // inline-completion when available.
 4372                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4373                            editor.update_visible_inline_completion(window, cx);
 4374                        }
 4375                    }
 4376                })?;
 4377
 4378                anyhow::Ok(())
 4379            }
 4380            .log_err()
 4381            .await
 4382        });
 4383
 4384        self.completion_tasks.push((id, task));
 4385    }
 4386
 4387    pub fn confirm_completion(
 4388        &mut self,
 4389        action: &ConfirmCompletion,
 4390        window: &mut Window,
 4391        cx: &mut Context<Self>,
 4392    ) -> Option<Task<Result<()>>> {
 4393        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4394    }
 4395
 4396    pub fn compose_completion(
 4397        &mut self,
 4398        action: &ComposeCompletion,
 4399        window: &mut Window,
 4400        cx: &mut Context<Self>,
 4401    ) -> Option<Task<Result<()>>> {
 4402        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4403    }
 4404
 4405    fn do_completion(
 4406        &mut self,
 4407        item_ix: Option<usize>,
 4408        intent: CompletionIntent,
 4409        window: &mut Window,
 4410        cx: &mut Context<Editor>,
 4411    ) -> Option<Task<Result<()>>> {
 4412        let completions_menu =
 4413            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4414                menu
 4415            } else {
 4416                return None;
 4417            };
 4418
 4419        let candidate_id = {
 4420            let entries = completions_menu.entries.borrow();
 4421            let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4422            if self.show_edit_predictions_in_menu() {
 4423                self.discard_inline_completion(true, cx);
 4424            }
 4425            mat.candidate_id
 4426        };
 4427
 4428        let buffer_handle = completions_menu.buffer;
 4429        let completion = completions_menu
 4430            .completions
 4431            .borrow()
 4432            .get(candidate_id)?
 4433            .clone();
 4434        cx.stop_propagation();
 4435
 4436        if self.selections.newest_anchor().start.buffer_id
 4437            != Some(buffer_handle.read(cx).remote_id())
 4438        {
 4439            return None;
 4440        }
 4441
 4442        let snippet;
 4443        let new_text;
 4444        if completion.is_snippet() {
 4445            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4446            new_text = snippet.as_ref().unwrap().text.clone();
 4447        } else {
 4448            snippet = None;
 4449            new_text = completion.new_text.clone();
 4450        };
 4451
 4452        let newest_selection = self.selections.newest::<usize>(cx);
 4453        let selections = self.selections.all::<usize>(cx);
 4454        let buffer = buffer_handle.read(cx);
 4455        let old_range = completion.old_range.to_offset(buffer);
 4456        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4457
 4458        let start_distance = newest_selection.start.saturating_sub(old_range.start);
 4459        let end_distance = old_range.end.saturating_sub(newest_selection.end);
 4460        let mut common_prefix_len = old_text
 4461            .bytes()
 4462            .zip(new_text.bytes())
 4463            .take_while(|(a, b)| a == b)
 4464            .count();
 4465
 4466        let snapshot = self.buffer.read(cx).snapshot(cx);
 4467        let mut range_to_replace: Option<Range<isize>> = None;
 4468        let mut ranges = Vec::new();
 4469        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4470        for selection in &selections {
 4471            if snapshot.contains_str_at(selection.start.saturating_sub(start_distance), &old_text) {
 4472                let start = selection.start.saturating_sub(start_distance);
 4473                let end = selection.end + end_distance;
 4474                if selection.id == newest_selection.id {
 4475                    range_to_replace = Some(
 4476                        ((start + common_prefix_len) as isize - selection.start as isize)
 4477                            ..(end as isize - selection.start as isize),
 4478                    );
 4479                }
 4480                ranges.push(start + common_prefix_len..end);
 4481            } else {
 4482                common_prefix_len = 0;
 4483                ranges.clear();
 4484                ranges.extend(selections.iter().map(|s| {
 4485                    if s.id == newest_selection.id {
 4486                        range_to_replace = Some(
 4487                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4488                                - selection.start as isize
 4489                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4490                                    - selection.start as isize,
 4491                        );
 4492                        old_range.clone()
 4493                    } else {
 4494                        s.start..s.end
 4495                    }
 4496                }));
 4497                break;
 4498            }
 4499            if !self.linked_edit_ranges.is_empty() {
 4500                let start_anchor = snapshot.anchor_before(selection.head());
 4501                let end_anchor = snapshot.anchor_after(selection.tail());
 4502                if let Some(ranges) = self
 4503                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4504                {
 4505                    for (buffer, edits) in ranges {
 4506                        linked_edits.entry(buffer.clone()).or_default().extend(
 4507                            edits
 4508                                .into_iter()
 4509                                .map(|range| (range, new_text[common_prefix_len..].to_owned())),
 4510                        );
 4511                    }
 4512                }
 4513            }
 4514        }
 4515        let text = &new_text[common_prefix_len..];
 4516
 4517        cx.emit(EditorEvent::InputHandled {
 4518            utf16_range_to_replace: range_to_replace,
 4519            text: text.into(),
 4520        });
 4521
 4522        self.transact(window, cx, |this, window, cx| {
 4523            if let Some(mut snippet) = snippet {
 4524                snippet.text = text.to_string();
 4525                for tabstop in snippet
 4526                    .tabstops
 4527                    .iter_mut()
 4528                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4529                {
 4530                    tabstop.start -= common_prefix_len as isize;
 4531                    tabstop.end -= common_prefix_len as isize;
 4532                }
 4533
 4534                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4535            } else {
 4536                this.buffer.update(cx, |buffer, cx| {
 4537                    let edits = ranges.iter().map(|range| (range.clone(), text));
 4538                    buffer.edit(edits, this.autoindent_mode.clone(), cx);
 4539                });
 4540            }
 4541            for (buffer, edits) in linked_edits {
 4542                buffer.update(cx, |buffer, cx| {
 4543                    let snapshot = buffer.snapshot();
 4544                    let edits = edits
 4545                        .into_iter()
 4546                        .map(|(range, text)| {
 4547                            use text::ToPoint as TP;
 4548                            let end_point = TP::to_point(&range.end, &snapshot);
 4549                            let start_point = TP::to_point(&range.start, &snapshot);
 4550                            (start_point..end_point, text)
 4551                        })
 4552                        .sorted_by_key(|(range, _)| range.start);
 4553                    buffer.edit(edits, None, cx);
 4554                })
 4555            }
 4556
 4557            this.refresh_inline_completion(true, false, window, cx);
 4558        });
 4559
 4560        let show_new_completions_on_confirm = completion
 4561            .confirm
 4562            .as_ref()
 4563            .map_or(false, |confirm| confirm(intent, window, cx));
 4564        if show_new_completions_on_confirm {
 4565            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4566        }
 4567
 4568        let provider = self.completion_provider.as_ref()?;
 4569        drop(completion);
 4570        let apply_edits = provider.apply_additional_edits_for_completion(
 4571            buffer_handle,
 4572            completions_menu.completions.clone(),
 4573            candidate_id,
 4574            true,
 4575            cx,
 4576        );
 4577
 4578        let editor_settings = EditorSettings::get_global(cx);
 4579        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4580            // After the code completion is finished, users often want to know what signatures are needed.
 4581            // so we should automatically call signature_help
 4582            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4583        }
 4584
 4585        Some(cx.foreground_executor().spawn(async move {
 4586            apply_edits.await?;
 4587            Ok(())
 4588        }))
 4589    }
 4590
 4591    pub fn toggle_code_actions(
 4592        &mut self,
 4593        action: &ToggleCodeActions,
 4594        window: &mut Window,
 4595        cx: &mut Context<Self>,
 4596    ) {
 4597        let mut context_menu = self.context_menu.borrow_mut();
 4598        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4599            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4600                // Toggle if we're selecting the same one
 4601                *context_menu = None;
 4602                cx.notify();
 4603                return;
 4604            } else {
 4605                // Otherwise, clear it and start a new one
 4606                *context_menu = None;
 4607                cx.notify();
 4608            }
 4609        }
 4610        drop(context_menu);
 4611        let snapshot = self.snapshot(window, cx);
 4612        let deployed_from_indicator = action.deployed_from_indicator;
 4613        let mut task = self.code_actions_task.take();
 4614        let action = action.clone();
 4615        cx.spawn_in(window, async move |editor, cx| {
 4616            while let Some(prev_task) = task {
 4617                prev_task.await.log_err();
 4618                task = editor.update(cx, |this, _| this.code_actions_task.take())?;
 4619            }
 4620
 4621            let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
 4622                if editor.focus_handle.is_focused(window) {
 4623                    let multibuffer_point = action
 4624                        .deployed_from_indicator
 4625                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4626                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4627                    let (buffer, buffer_row) = snapshot
 4628                        .buffer_snapshot
 4629                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4630                        .and_then(|(buffer_snapshot, range)| {
 4631                            editor
 4632                                .buffer
 4633                                .read(cx)
 4634                                .buffer(buffer_snapshot.remote_id())
 4635                                .map(|buffer| (buffer, range.start.row))
 4636                        })?;
 4637                    let (_, code_actions) = editor
 4638                        .available_code_actions
 4639                        .clone()
 4640                        .and_then(|(location, code_actions)| {
 4641                            let snapshot = location.buffer.read(cx).snapshot();
 4642                            let point_range = location.range.to_point(&snapshot);
 4643                            let point_range = point_range.start.row..=point_range.end.row;
 4644                            if point_range.contains(&buffer_row) {
 4645                                Some((location, code_actions))
 4646                            } else {
 4647                                None
 4648                            }
 4649                        })
 4650                        .unzip();
 4651                    let buffer_id = buffer.read(cx).remote_id();
 4652                    let tasks = editor
 4653                        .tasks
 4654                        .get(&(buffer_id, buffer_row))
 4655                        .map(|t| Arc::new(t.to_owned()));
 4656                    if tasks.is_none() && code_actions.is_none() {
 4657                        return None;
 4658                    }
 4659
 4660                    editor.completion_tasks.clear();
 4661                    editor.discard_inline_completion(false, cx);
 4662                    let task_context =
 4663                        tasks
 4664                            .as_ref()
 4665                            .zip(editor.project.clone())
 4666                            .map(|(tasks, project)| {
 4667                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4668                            });
 4669
 4670                    Some(cx.spawn_in(window, async move |editor, cx| {
 4671                        let task_context = match task_context {
 4672                            Some(task_context) => task_context.await,
 4673                            None => None,
 4674                        };
 4675                        let resolved_tasks =
 4676                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4677                                Rc::new(ResolvedTasks {
 4678                                    templates: tasks.resolve(&task_context).collect(),
 4679                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4680                                        multibuffer_point.row,
 4681                                        tasks.column,
 4682                                    )),
 4683                                })
 4684                            });
 4685                        let spawn_straight_away = resolved_tasks
 4686                            .as_ref()
 4687                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4688                            && code_actions
 4689                                .as_ref()
 4690                                .map_or(true, |actions| actions.is_empty());
 4691                        if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
 4692                            *editor.context_menu.borrow_mut() =
 4693                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4694                                    buffer,
 4695                                    actions: CodeActionContents {
 4696                                        tasks: resolved_tasks,
 4697                                        actions: code_actions,
 4698                                    },
 4699                                    selected_item: Default::default(),
 4700                                    scroll_handle: UniformListScrollHandle::default(),
 4701                                    deployed_from_indicator,
 4702                                }));
 4703                            if spawn_straight_away {
 4704                                if let Some(task) = editor.confirm_code_action(
 4705                                    &ConfirmCodeAction { item_ix: Some(0) },
 4706                                    window,
 4707                                    cx,
 4708                                ) {
 4709                                    cx.notify();
 4710                                    return task;
 4711                                }
 4712                            }
 4713                            cx.notify();
 4714                            Task::ready(Ok(()))
 4715                        }) {
 4716                            task.await
 4717                        } else {
 4718                            Ok(())
 4719                        }
 4720                    }))
 4721                } else {
 4722                    Some(Task::ready(Ok(())))
 4723                }
 4724            })?;
 4725            if let Some(task) = spawned_test_task {
 4726                task.await?;
 4727            }
 4728
 4729            Ok::<_, anyhow::Error>(())
 4730        })
 4731        .detach_and_log_err(cx);
 4732    }
 4733
 4734    pub fn confirm_code_action(
 4735        &mut self,
 4736        action: &ConfirmCodeAction,
 4737        window: &mut Window,
 4738        cx: &mut Context<Self>,
 4739    ) -> Option<Task<Result<()>>> {
 4740        let actions_menu =
 4741            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4742                menu
 4743            } else {
 4744                return None;
 4745            };
 4746        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4747        let action = actions_menu.actions.get(action_ix)?;
 4748        let title = action.label();
 4749        let buffer = actions_menu.buffer;
 4750        let workspace = self.workspace()?;
 4751
 4752        match action {
 4753            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4754                workspace.update(cx, |workspace, cx| {
 4755                    workspace::tasks::schedule_resolved_task(
 4756                        workspace,
 4757                        task_source_kind,
 4758                        resolved_task,
 4759                        false,
 4760                        cx,
 4761                    );
 4762
 4763                    Some(Task::ready(Ok(())))
 4764                })
 4765            }
 4766            CodeActionsItem::CodeAction {
 4767                excerpt_id,
 4768                action,
 4769                provider,
 4770            } => {
 4771                let apply_code_action =
 4772                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4773                let workspace = workspace.downgrade();
 4774                Some(cx.spawn_in(window, async move |editor, cx| {
 4775                    let project_transaction = apply_code_action.await?;
 4776                    Self::open_project_transaction(
 4777                        &editor,
 4778                        workspace,
 4779                        project_transaction,
 4780                        title,
 4781                        cx,
 4782                    )
 4783                    .await
 4784                }))
 4785            }
 4786        }
 4787    }
 4788
 4789    pub async fn open_project_transaction(
 4790        this: &WeakEntity<Editor>,
 4791        workspace: WeakEntity<Workspace>,
 4792        transaction: ProjectTransaction,
 4793        title: String,
 4794        cx: &mut AsyncWindowContext,
 4795    ) -> Result<()> {
 4796        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4797        cx.update(|_, cx| {
 4798            entries.sort_unstable_by_key(|(buffer, _)| {
 4799                buffer.read(cx).file().map(|f| f.path().clone())
 4800            });
 4801        })?;
 4802
 4803        // If the project transaction's edits are all contained within this editor, then
 4804        // avoid opening a new editor to display them.
 4805
 4806        if let Some((buffer, transaction)) = entries.first() {
 4807            if entries.len() == 1 {
 4808                let excerpt = this.update(cx, |editor, cx| {
 4809                    editor
 4810                        .buffer()
 4811                        .read(cx)
 4812                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4813                })?;
 4814                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4815                    if excerpted_buffer == *buffer {
 4816                        let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
 4817                            let excerpt_range = excerpt_range.to_offset(buffer);
 4818                            buffer
 4819                                .edited_ranges_for_transaction::<usize>(transaction)
 4820                                .all(|range| {
 4821                                    excerpt_range.start <= range.start
 4822                                        && excerpt_range.end >= range.end
 4823                                })
 4824                        })?;
 4825
 4826                        if all_edits_within_excerpt {
 4827                            return Ok(());
 4828                        }
 4829                    }
 4830                }
 4831            }
 4832        } else {
 4833            return Ok(());
 4834        }
 4835
 4836        let mut ranges_to_highlight = Vec::new();
 4837        let excerpt_buffer = cx.new(|cx| {
 4838            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4839            for (buffer_handle, transaction) in &entries {
 4840                let buffer = buffer_handle.read(cx);
 4841                ranges_to_highlight.extend(
 4842                    multibuffer.push_excerpts_with_context_lines(
 4843                        buffer_handle.clone(),
 4844                        buffer
 4845                            .edited_ranges_for_transaction::<usize>(transaction)
 4846                            .collect(),
 4847                        DEFAULT_MULTIBUFFER_CONTEXT,
 4848                        cx,
 4849                    ),
 4850                );
 4851            }
 4852            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4853            multibuffer
 4854        })?;
 4855
 4856        workspace.update_in(cx, |workspace, window, cx| {
 4857            let project = workspace.project().clone();
 4858            let editor =
 4859                cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
 4860            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4861            editor.update(cx, |editor, cx| {
 4862                editor.highlight_background::<Self>(
 4863                    &ranges_to_highlight,
 4864                    |theme| theme.editor_highlighted_line_background,
 4865                    cx,
 4866                );
 4867            });
 4868        })?;
 4869
 4870        Ok(())
 4871    }
 4872
 4873    pub fn clear_code_action_providers(&mut self) {
 4874        self.code_action_providers.clear();
 4875        self.available_code_actions.take();
 4876    }
 4877
 4878    pub fn add_code_action_provider(
 4879        &mut self,
 4880        provider: Rc<dyn CodeActionProvider>,
 4881        window: &mut Window,
 4882        cx: &mut Context<Self>,
 4883    ) {
 4884        if self
 4885            .code_action_providers
 4886            .iter()
 4887            .any(|existing_provider| existing_provider.id() == provider.id())
 4888        {
 4889            return;
 4890        }
 4891
 4892        self.code_action_providers.push(provider);
 4893        self.refresh_code_actions(window, cx);
 4894    }
 4895
 4896    pub fn remove_code_action_provider(
 4897        &mut self,
 4898        id: Arc<str>,
 4899        window: &mut Window,
 4900        cx: &mut Context<Self>,
 4901    ) {
 4902        self.code_action_providers
 4903            .retain(|provider| provider.id() != id);
 4904        self.refresh_code_actions(window, cx);
 4905    }
 4906
 4907    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4908        let buffer = self.buffer.read(cx);
 4909        let newest_selection = self.selections.newest_anchor().clone();
 4910        if newest_selection.head().diff_base_anchor.is_some() {
 4911            return None;
 4912        }
 4913        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4914        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4915        if start_buffer != end_buffer {
 4916            return None;
 4917        }
 4918
 4919        self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
 4920            cx.background_executor()
 4921                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4922                .await;
 4923
 4924            let (providers, tasks) = this.update_in(cx, |this, window, cx| {
 4925                let providers = this.code_action_providers.clone();
 4926                let tasks = this
 4927                    .code_action_providers
 4928                    .iter()
 4929                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4930                    .collect::<Vec<_>>();
 4931                (providers, tasks)
 4932            })?;
 4933
 4934            let mut actions = Vec::new();
 4935            for (provider, provider_actions) in
 4936                providers.into_iter().zip(future::join_all(tasks).await)
 4937            {
 4938                if let Some(provider_actions) = provider_actions.log_err() {
 4939                    actions.extend(provider_actions.into_iter().map(|action| {
 4940                        AvailableCodeAction {
 4941                            excerpt_id: newest_selection.start.excerpt_id,
 4942                            action,
 4943                            provider: provider.clone(),
 4944                        }
 4945                    }));
 4946                }
 4947            }
 4948
 4949            this.update(cx, |this, cx| {
 4950                this.available_code_actions = if actions.is_empty() {
 4951                    None
 4952                } else {
 4953                    Some((
 4954                        Location {
 4955                            buffer: start_buffer,
 4956                            range: start..end,
 4957                        },
 4958                        actions.into(),
 4959                    ))
 4960                };
 4961                cx.notify();
 4962            })
 4963        }));
 4964        None
 4965    }
 4966
 4967    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4968        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4969            self.show_git_blame_inline = false;
 4970
 4971            self.show_git_blame_inline_delay_task =
 4972                Some(cx.spawn_in(window, async move |this, cx| {
 4973                    cx.background_executor().timer(delay).await;
 4974
 4975                    this.update(cx, |this, cx| {
 4976                        this.show_git_blame_inline = true;
 4977                        cx.notify();
 4978                    })
 4979                    .log_err();
 4980                }));
 4981        }
 4982    }
 4983
 4984    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4985        if self.pending_rename.is_some() {
 4986            return None;
 4987        }
 4988
 4989        let provider = self.semantics_provider.clone()?;
 4990        let buffer = self.buffer.read(cx);
 4991        let newest_selection = self.selections.newest_anchor().clone();
 4992        let cursor_position = newest_selection.head();
 4993        let (cursor_buffer, cursor_buffer_position) =
 4994            buffer.text_anchor_for_position(cursor_position, cx)?;
 4995        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4996        if cursor_buffer != tail_buffer {
 4997            return None;
 4998        }
 4999        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 5000        self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
 5001            cx.background_executor()
 5002                .timer(Duration::from_millis(debounce))
 5003                .await;
 5004
 5005            let highlights = if let Some(highlights) = cx
 5006                .update(|cx| {
 5007                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5008                })
 5009                .ok()
 5010                .flatten()
 5011            {
 5012                highlights.await.log_err()
 5013            } else {
 5014                None
 5015            };
 5016
 5017            if let Some(highlights) = highlights {
 5018                this.update(cx, |this, cx| {
 5019                    if this.pending_rename.is_some() {
 5020                        return;
 5021                    }
 5022
 5023                    let buffer_id = cursor_position.buffer_id;
 5024                    let buffer = this.buffer.read(cx);
 5025                    if !buffer
 5026                        .text_anchor_for_position(cursor_position, cx)
 5027                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5028                    {
 5029                        return;
 5030                    }
 5031
 5032                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5033                    let mut write_ranges = Vec::new();
 5034                    let mut read_ranges = Vec::new();
 5035                    for highlight in highlights {
 5036                        for (excerpt_id, excerpt_range) in
 5037                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 5038                        {
 5039                            let start = highlight
 5040                                .range
 5041                                .start
 5042                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5043                            let end = highlight
 5044                                .range
 5045                                .end
 5046                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5047                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5048                                continue;
 5049                            }
 5050
 5051                            let range = Anchor {
 5052                                buffer_id,
 5053                                excerpt_id,
 5054                                text_anchor: start,
 5055                                diff_base_anchor: None,
 5056                            }..Anchor {
 5057                                buffer_id,
 5058                                excerpt_id,
 5059                                text_anchor: end,
 5060                                diff_base_anchor: None,
 5061                            };
 5062                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5063                                write_ranges.push(range);
 5064                            } else {
 5065                                read_ranges.push(range);
 5066                            }
 5067                        }
 5068                    }
 5069
 5070                    this.highlight_background::<DocumentHighlightRead>(
 5071                        &read_ranges,
 5072                        |theme| theme.editor_document_highlight_read_background,
 5073                        cx,
 5074                    );
 5075                    this.highlight_background::<DocumentHighlightWrite>(
 5076                        &write_ranges,
 5077                        |theme| theme.editor_document_highlight_write_background,
 5078                        cx,
 5079                    );
 5080                    cx.notify();
 5081                })
 5082                .log_err();
 5083            }
 5084        }));
 5085        None
 5086    }
 5087
 5088    pub fn refresh_selected_text_highlights(
 5089        &mut self,
 5090        window: &mut Window,
 5091        cx: &mut Context<Editor>,
 5092    ) {
 5093        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 5094            return;
 5095        }
 5096        self.selection_highlight_task.take();
 5097        if !EditorSettings::get_global(cx).selection_highlight {
 5098            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5099            return;
 5100        }
 5101        if self.selections.count() != 1 || self.selections.line_mode {
 5102            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5103            return;
 5104        }
 5105        let selection = self.selections.newest::<Point>(cx);
 5106        if selection.is_empty() || selection.start.row != selection.end.row {
 5107            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5108            return;
 5109        }
 5110        let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
 5111        self.selection_highlight_task = Some(cx.spawn_in(window, async move |editor, cx| {
 5112            cx.background_executor()
 5113                .timer(Duration::from_millis(debounce))
 5114                .await;
 5115            let Some(Some(matches_task)) = editor
 5116                .update_in(cx, |editor, _, cx| {
 5117                    if editor.selections.count() != 1 || editor.selections.line_mode {
 5118                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5119                        return None;
 5120                    }
 5121                    let selection = editor.selections.newest::<Point>(cx);
 5122                    if selection.is_empty() || selection.start.row != selection.end.row {
 5123                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5124                        return None;
 5125                    }
 5126                    let buffer = editor.buffer().read(cx).snapshot(cx);
 5127                    let query = buffer.text_for_range(selection.range()).collect::<String>();
 5128                    if query.trim().is_empty() {
 5129                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5130                        return None;
 5131                    }
 5132                    Some(cx.background_spawn(async move {
 5133                        let mut ranges = Vec::new();
 5134                        let selection_anchors = selection.range().to_anchors(&buffer);
 5135                        for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
 5136                            for (search_buffer, search_range, excerpt_id) in
 5137                                buffer.range_to_buffer_ranges(range)
 5138                            {
 5139                                ranges.extend(
 5140                                    project::search::SearchQuery::text(
 5141                                        query.clone(),
 5142                                        false,
 5143                                        false,
 5144                                        false,
 5145                                        Default::default(),
 5146                                        Default::default(),
 5147                                        None,
 5148                                    )
 5149                                    .unwrap()
 5150                                    .search(search_buffer, Some(search_range.clone()))
 5151                                    .await
 5152                                    .into_iter()
 5153                                    .filter_map(
 5154                                        |match_range| {
 5155                                            let start = search_buffer.anchor_after(
 5156                                                search_range.start + match_range.start,
 5157                                            );
 5158                                            let end = search_buffer.anchor_before(
 5159                                                search_range.start + match_range.end,
 5160                                            );
 5161                                            let range = Anchor::range_in_buffer(
 5162                                                excerpt_id,
 5163                                                search_buffer.remote_id(),
 5164                                                start..end,
 5165                                            );
 5166                                            (range != selection_anchors).then_some(range)
 5167                                        },
 5168                                    ),
 5169                                );
 5170                            }
 5171                        }
 5172                        ranges
 5173                    }))
 5174                })
 5175                .log_err()
 5176            else {
 5177                return;
 5178            };
 5179            let matches = matches_task.await;
 5180            editor
 5181                .update_in(cx, |editor, _, cx| {
 5182                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5183                    if !matches.is_empty() {
 5184                        editor.highlight_background::<SelectedTextHighlight>(
 5185                            &matches,
 5186                            |theme| theme.editor_document_highlight_bracket_background,
 5187                            cx,
 5188                        )
 5189                    }
 5190                })
 5191                .log_err();
 5192        }));
 5193    }
 5194
 5195    pub fn refresh_inline_completion(
 5196        &mut self,
 5197        debounce: bool,
 5198        user_requested: bool,
 5199        window: &mut Window,
 5200        cx: &mut Context<Self>,
 5201    ) -> Option<()> {
 5202        let provider = self.edit_prediction_provider()?;
 5203        let cursor = self.selections.newest_anchor().head();
 5204        let (buffer, cursor_buffer_position) =
 5205            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5206
 5207        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 5208            self.discard_inline_completion(false, cx);
 5209            return None;
 5210        }
 5211
 5212        if !user_requested
 5213            && (!self.should_show_edit_predictions()
 5214                || !self.is_focused(window)
 5215                || buffer.read(cx).is_empty())
 5216        {
 5217            self.discard_inline_completion(false, cx);
 5218            return None;
 5219        }
 5220
 5221        self.update_visible_inline_completion(window, cx);
 5222        provider.refresh(
 5223            self.project.clone(),
 5224            buffer,
 5225            cursor_buffer_position,
 5226            debounce,
 5227            cx,
 5228        );
 5229        Some(())
 5230    }
 5231
 5232    fn show_edit_predictions_in_menu(&self) -> bool {
 5233        match self.edit_prediction_settings {
 5234            EditPredictionSettings::Disabled => false,
 5235            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 5236        }
 5237    }
 5238
 5239    pub fn edit_predictions_enabled(&self) -> bool {
 5240        match self.edit_prediction_settings {
 5241            EditPredictionSettings::Disabled => false,
 5242            EditPredictionSettings::Enabled { .. } => true,
 5243        }
 5244    }
 5245
 5246    fn edit_prediction_requires_modifier(&self) -> bool {
 5247        match self.edit_prediction_settings {
 5248            EditPredictionSettings::Disabled => false,
 5249            EditPredictionSettings::Enabled {
 5250                preview_requires_modifier,
 5251                ..
 5252            } => preview_requires_modifier,
 5253        }
 5254    }
 5255
 5256    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 5257        if self.edit_prediction_provider.is_none() {
 5258            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5259        } else {
 5260            let selection = self.selections.newest_anchor();
 5261            let cursor = selection.head();
 5262
 5263            if let Some((buffer, cursor_buffer_position)) =
 5264                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5265            {
 5266                self.edit_prediction_settings =
 5267                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5268            }
 5269        }
 5270    }
 5271
 5272    fn edit_prediction_settings_at_position(
 5273        &self,
 5274        buffer: &Entity<Buffer>,
 5275        buffer_position: language::Anchor,
 5276        cx: &App,
 5277    ) -> EditPredictionSettings {
 5278        if self.mode != EditorMode::Full
 5279            || !self.show_inline_completions_override.unwrap_or(true)
 5280            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 5281        {
 5282            return EditPredictionSettings::Disabled;
 5283        }
 5284
 5285        let buffer = buffer.read(cx);
 5286
 5287        let file = buffer.file();
 5288
 5289        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 5290            return EditPredictionSettings::Disabled;
 5291        };
 5292
 5293        let by_provider = matches!(
 5294            self.menu_inline_completions_policy,
 5295            MenuInlineCompletionsPolicy::ByProvider
 5296        );
 5297
 5298        let show_in_menu = by_provider
 5299            && self
 5300                .edit_prediction_provider
 5301                .as_ref()
 5302                .map_or(false, |provider| {
 5303                    provider.provider.show_completions_in_menu()
 5304                });
 5305
 5306        let preview_requires_modifier =
 5307            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 5308
 5309        EditPredictionSettings::Enabled {
 5310            show_in_menu,
 5311            preview_requires_modifier,
 5312        }
 5313    }
 5314
 5315    fn should_show_edit_predictions(&self) -> bool {
 5316        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 5317    }
 5318
 5319    pub fn edit_prediction_preview_is_active(&self) -> bool {
 5320        matches!(
 5321            self.edit_prediction_preview,
 5322            EditPredictionPreview::Active { .. }
 5323        )
 5324    }
 5325
 5326    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 5327        let cursor = self.selections.newest_anchor().head();
 5328        if let Some((buffer, cursor_position)) =
 5329            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5330        {
 5331            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 5332        } else {
 5333            false
 5334        }
 5335    }
 5336
 5337    fn edit_predictions_enabled_in_buffer(
 5338        &self,
 5339        buffer: &Entity<Buffer>,
 5340        buffer_position: language::Anchor,
 5341        cx: &App,
 5342    ) -> bool {
 5343        maybe!({
 5344            if self.read_only(cx) {
 5345                return Some(false);
 5346            }
 5347            let provider = self.edit_prediction_provider()?;
 5348            if !provider.is_enabled(&buffer, buffer_position, cx) {
 5349                return Some(false);
 5350            }
 5351            let buffer = buffer.read(cx);
 5352            let Some(file) = buffer.file() else {
 5353                return Some(true);
 5354            };
 5355            let settings = all_language_settings(Some(file), cx);
 5356            Some(settings.edit_predictions_enabled_for_file(file, cx))
 5357        })
 5358        .unwrap_or(false)
 5359    }
 5360
 5361    fn cycle_inline_completion(
 5362        &mut self,
 5363        direction: Direction,
 5364        window: &mut Window,
 5365        cx: &mut Context<Self>,
 5366    ) -> Option<()> {
 5367        let provider = self.edit_prediction_provider()?;
 5368        let cursor = self.selections.newest_anchor().head();
 5369        let (buffer, cursor_buffer_position) =
 5370            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5371        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 5372            return None;
 5373        }
 5374
 5375        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5376        self.update_visible_inline_completion(window, cx);
 5377
 5378        Some(())
 5379    }
 5380
 5381    pub fn show_inline_completion(
 5382        &mut self,
 5383        _: &ShowEditPrediction,
 5384        window: &mut Window,
 5385        cx: &mut Context<Self>,
 5386    ) {
 5387        if !self.has_active_inline_completion() {
 5388            self.refresh_inline_completion(false, true, window, cx);
 5389            return;
 5390        }
 5391
 5392        self.update_visible_inline_completion(window, cx);
 5393    }
 5394
 5395    pub fn display_cursor_names(
 5396        &mut self,
 5397        _: &DisplayCursorNames,
 5398        window: &mut Window,
 5399        cx: &mut Context<Self>,
 5400    ) {
 5401        self.show_cursor_names(window, cx);
 5402    }
 5403
 5404    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5405        self.show_cursor_names = true;
 5406        cx.notify();
 5407        cx.spawn_in(window, async move |this, cx| {
 5408            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5409            this.update(cx, |this, cx| {
 5410                this.show_cursor_names = false;
 5411                cx.notify()
 5412            })
 5413            .ok()
 5414        })
 5415        .detach();
 5416    }
 5417
 5418    pub fn next_edit_prediction(
 5419        &mut self,
 5420        _: &NextEditPrediction,
 5421        window: &mut Window,
 5422        cx: &mut Context<Self>,
 5423    ) {
 5424        if self.has_active_inline_completion() {
 5425            self.cycle_inline_completion(Direction::Next, window, cx);
 5426        } else {
 5427            let is_copilot_disabled = self
 5428                .refresh_inline_completion(false, true, window, cx)
 5429                .is_none();
 5430            if is_copilot_disabled {
 5431                cx.propagate();
 5432            }
 5433        }
 5434    }
 5435
 5436    pub fn previous_edit_prediction(
 5437        &mut self,
 5438        _: &PreviousEditPrediction,
 5439        window: &mut Window,
 5440        cx: &mut Context<Self>,
 5441    ) {
 5442        if self.has_active_inline_completion() {
 5443            self.cycle_inline_completion(Direction::Prev, window, cx);
 5444        } else {
 5445            let is_copilot_disabled = self
 5446                .refresh_inline_completion(false, true, window, cx)
 5447                .is_none();
 5448            if is_copilot_disabled {
 5449                cx.propagate();
 5450            }
 5451        }
 5452    }
 5453
 5454    pub fn accept_edit_prediction(
 5455        &mut self,
 5456        _: &AcceptEditPrediction,
 5457        window: &mut Window,
 5458        cx: &mut Context<Self>,
 5459    ) {
 5460        if self.show_edit_predictions_in_menu() {
 5461            self.hide_context_menu(window, cx);
 5462        }
 5463
 5464        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5465            return;
 5466        };
 5467
 5468        self.report_inline_completion_event(
 5469            active_inline_completion.completion_id.clone(),
 5470            true,
 5471            cx,
 5472        );
 5473
 5474        match &active_inline_completion.completion {
 5475            InlineCompletion::Move { target, .. } => {
 5476                let target = *target;
 5477
 5478                if let Some(position_map) = &self.last_position_map {
 5479                    if position_map
 5480                        .visible_row_range
 5481                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5482                        || !self.edit_prediction_requires_modifier()
 5483                    {
 5484                        self.unfold_ranges(&[target..target], true, false, cx);
 5485                        // Note that this is also done in vim's handler of the Tab action.
 5486                        self.change_selections(
 5487                            Some(Autoscroll::newest()),
 5488                            window,
 5489                            cx,
 5490                            |selections| {
 5491                                selections.select_anchor_ranges([target..target]);
 5492                            },
 5493                        );
 5494                        self.clear_row_highlights::<EditPredictionPreview>();
 5495
 5496                        self.edit_prediction_preview
 5497                            .set_previous_scroll_position(None);
 5498                    } else {
 5499                        self.edit_prediction_preview
 5500                            .set_previous_scroll_position(Some(
 5501                                position_map.snapshot.scroll_anchor,
 5502                            ));
 5503
 5504                        self.highlight_rows::<EditPredictionPreview>(
 5505                            target..target,
 5506                            cx.theme().colors().editor_highlighted_line_background,
 5507                            true,
 5508                            cx,
 5509                        );
 5510                        self.request_autoscroll(Autoscroll::fit(), cx);
 5511                    }
 5512                }
 5513            }
 5514            InlineCompletion::Edit { edits, .. } => {
 5515                if let Some(provider) = self.edit_prediction_provider() {
 5516                    provider.accept(cx);
 5517                }
 5518
 5519                let snapshot = self.buffer.read(cx).snapshot(cx);
 5520                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5521
 5522                self.buffer.update(cx, |buffer, cx| {
 5523                    buffer.edit(edits.iter().cloned(), None, cx)
 5524                });
 5525
 5526                self.change_selections(None, window, cx, |s| {
 5527                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5528                });
 5529
 5530                self.update_visible_inline_completion(window, cx);
 5531                if self.active_inline_completion.is_none() {
 5532                    self.refresh_inline_completion(true, true, window, cx);
 5533                }
 5534
 5535                cx.notify();
 5536            }
 5537        }
 5538
 5539        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 5540    }
 5541
 5542    pub fn accept_partial_inline_completion(
 5543        &mut self,
 5544        _: &AcceptPartialEditPrediction,
 5545        window: &mut Window,
 5546        cx: &mut Context<Self>,
 5547    ) {
 5548        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5549            return;
 5550        };
 5551        if self.selections.count() != 1 {
 5552            return;
 5553        }
 5554
 5555        self.report_inline_completion_event(
 5556            active_inline_completion.completion_id.clone(),
 5557            true,
 5558            cx,
 5559        );
 5560
 5561        match &active_inline_completion.completion {
 5562            InlineCompletion::Move { target, .. } => {
 5563                let target = *target;
 5564                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5565                    selections.select_anchor_ranges([target..target]);
 5566                });
 5567            }
 5568            InlineCompletion::Edit { edits, .. } => {
 5569                // Find an insertion that starts at the cursor position.
 5570                let snapshot = self.buffer.read(cx).snapshot(cx);
 5571                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5572                let insertion = edits.iter().find_map(|(range, text)| {
 5573                    let range = range.to_offset(&snapshot);
 5574                    if range.is_empty() && range.start == cursor_offset {
 5575                        Some(text)
 5576                    } else {
 5577                        None
 5578                    }
 5579                });
 5580
 5581                if let Some(text) = insertion {
 5582                    let mut partial_completion = text
 5583                        .chars()
 5584                        .by_ref()
 5585                        .take_while(|c| c.is_alphabetic())
 5586                        .collect::<String>();
 5587                    if partial_completion.is_empty() {
 5588                        partial_completion = text
 5589                            .chars()
 5590                            .by_ref()
 5591                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5592                            .collect::<String>();
 5593                    }
 5594
 5595                    cx.emit(EditorEvent::InputHandled {
 5596                        utf16_range_to_replace: None,
 5597                        text: partial_completion.clone().into(),
 5598                    });
 5599
 5600                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5601
 5602                    self.refresh_inline_completion(true, true, window, cx);
 5603                    cx.notify();
 5604                } else {
 5605                    self.accept_edit_prediction(&Default::default(), window, cx);
 5606                }
 5607            }
 5608        }
 5609    }
 5610
 5611    fn discard_inline_completion(
 5612        &mut self,
 5613        should_report_inline_completion_event: bool,
 5614        cx: &mut Context<Self>,
 5615    ) -> bool {
 5616        if should_report_inline_completion_event {
 5617            let completion_id = self
 5618                .active_inline_completion
 5619                .as_ref()
 5620                .and_then(|active_completion| active_completion.completion_id.clone());
 5621
 5622            self.report_inline_completion_event(completion_id, false, cx);
 5623        }
 5624
 5625        if let Some(provider) = self.edit_prediction_provider() {
 5626            provider.discard(cx);
 5627        }
 5628
 5629        self.take_active_inline_completion(cx)
 5630    }
 5631
 5632    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5633        let Some(provider) = self.edit_prediction_provider() else {
 5634            return;
 5635        };
 5636
 5637        let Some((_, buffer, _)) = self
 5638            .buffer
 5639            .read(cx)
 5640            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5641        else {
 5642            return;
 5643        };
 5644
 5645        let extension = buffer
 5646            .read(cx)
 5647            .file()
 5648            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5649
 5650        let event_type = match accepted {
 5651            true => "Edit Prediction Accepted",
 5652            false => "Edit Prediction Discarded",
 5653        };
 5654        telemetry::event!(
 5655            event_type,
 5656            provider = provider.name(),
 5657            prediction_id = id,
 5658            suggestion_accepted = accepted,
 5659            file_extension = extension,
 5660        );
 5661    }
 5662
 5663    pub fn has_active_inline_completion(&self) -> bool {
 5664        self.active_inline_completion.is_some()
 5665    }
 5666
 5667    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5668        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5669            return false;
 5670        };
 5671
 5672        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5673        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5674        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5675        true
 5676    }
 5677
 5678    /// Returns true when we're displaying the edit prediction popover below the cursor
 5679    /// like we are not previewing and the LSP autocomplete menu is visible
 5680    /// or we are in `when_holding_modifier` mode.
 5681    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5682        if self.edit_prediction_preview_is_active()
 5683            || !self.show_edit_predictions_in_menu()
 5684            || !self.edit_predictions_enabled()
 5685        {
 5686            return false;
 5687        }
 5688
 5689        if self.has_visible_completions_menu() {
 5690            return true;
 5691        }
 5692
 5693        has_completion && self.edit_prediction_requires_modifier()
 5694    }
 5695
 5696    fn handle_modifiers_changed(
 5697        &mut self,
 5698        modifiers: Modifiers,
 5699        position_map: &PositionMap,
 5700        window: &mut Window,
 5701        cx: &mut Context<Self>,
 5702    ) {
 5703        if self.show_edit_predictions_in_menu() {
 5704            self.update_edit_prediction_preview(&modifiers, window, cx);
 5705        }
 5706
 5707        self.update_selection_mode(&modifiers, position_map, window, cx);
 5708
 5709        let mouse_position = window.mouse_position();
 5710        if !position_map.text_hitbox.is_hovered(window) {
 5711            return;
 5712        }
 5713
 5714        self.update_hovered_link(
 5715            position_map.point_for_position(mouse_position),
 5716            &position_map.snapshot,
 5717            modifiers,
 5718            window,
 5719            cx,
 5720        )
 5721    }
 5722
 5723    fn update_selection_mode(
 5724        &mut self,
 5725        modifiers: &Modifiers,
 5726        position_map: &PositionMap,
 5727        window: &mut Window,
 5728        cx: &mut Context<Self>,
 5729    ) {
 5730        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 5731            return;
 5732        }
 5733
 5734        let mouse_position = window.mouse_position();
 5735        let point_for_position = position_map.point_for_position(mouse_position);
 5736        let position = point_for_position.previous_valid;
 5737
 5738        self.select(
 5739            SelectPhase::BeginColumnar {
 5740                position,
 5741                reset: false,
 5742                goal_column: point_for_position.exact_unclipped.column(),
 5743            },
 5744            window,
 5745            cx,
 5746        );
 5747    }
 5748
 5749    fn update_edit_prediction_preview(
 5750        &mut self,
 5751        modifiers: &Modifiers,
 5752        window: &mut Window,
 5753        cx: &mut Context<Self>,
 5754    ) {
 5755        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5756        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5757            return;
 5758        };
 5759
 5760        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5761            if matches!(
 5762                self.edit_prediction_preview,
 5763                EditPredictionPreview::Inactive { .. }
 5764            ) {
 5765                self.edit_prediction_preview = EditPredictionPreview::Active {
 5766                    previous_scroll_position: None,
 5767                    since: Instant::now(),
 5768                };
 5769
 5770                self.update_visible_inline_completion(window, cx);
 5771                cx.notify();
 5772            }
 5773        } else if let EditPredictionPreview::Active {
 5774            previous_scroll_position,
 5775            since,
 5776        } = self.edit_prediction_preview
 5777        {
 5778            if let (Some(previous_scroll_position), Some(position_map)) =
 5779                (previous_scroll_position, self.last_position_map.as_ref())
 5780            {
 5781                self.set_scroll_position(
 5782                    previous_scroll_position
 5783                        .scroll_position(&position_map.snapshot.display_snapshot),
 5784                    window,
 5785                    cx,
 5786                );
 5787            }
 5788
 5789            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 5790                released_too_fast: since.elapsed() < Duration::from_millis(200),
 5791            };
 5792            self.clear_row_highlights::<EditPredictionPreview>();
 5793            self.update_visible_inline_completion(window, cx);
 5794            cx.notify();
 5795        }
 5796    }
 5797
 5798    fn update_visible_inline_completion(
 5799        &mut self,
 5800        _window: &mut Window,
 5801        cx: &mut Context<Self>,
 5802    ) -> Option<()> {
 5803        let selection = self.selections.newest_anchor();
 5804        let cursor = selection.head();
 5805        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5806        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5807        let excerpt_id = cursor.excerpt_id;
 5808
 5809        let show_in_menu = self.show_edit_predictions_in_menu();
 5810        let completions_menu_has_precedence = !show_in_menu
 5811            && (self.context_menu.borrow().is_some()
 5812                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5813
 5814        if completions_menu_has_precedence
 5815            || !offset_selection.is_empty()
 5816            || self
 5817                .active_inline_completion
 5818                .as_ref()
 5819                .map_or(false, |completion| {
 5820                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5821                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5822                    !invalidation_range.contains(&offset_selection.head())
 5823                })
 5824        {
 5825            self.discard_inline_completion(false, cx);
 5826            return None;
 5827        }
 5828
 5829        self.take_active_inline_completion(cx);
 5830        let Some(provider) = self.edit_prediction_provider() else {
 5831            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5832            return None;
 5833        };
 5834
 5835        let (buffer, cursor_buffer_position) =
 5836            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5837
 5838        self.edit_prediction_settings =
 5839            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5840
 5841        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 5842
 5843        if self.edit_prediction_indent_conflict {
 5844            let cursor_point = cursor.to_point(&multibuffer);
 5845
 5846            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 5847
 5848            if let Some((_, indent)) = indents.iter().next() {
 5849                if indent.len == cursor_point.column {
 5850                    self.edit_prediction_indent_conflict = false;
 5851                }
 5852            }
 5853        }
 5854
 5855        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5856        let edits = inline_completion
 5857            .edits
 5858            .into_iter()
 5859            .flat_map(|(range, new_text)| {
 5860                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5861                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5862                Some((start..end, new_text))
 5863            })
 5864            .collect::<Vec<_>>();
 5865        if edits.is_empty() {
 5866            return None;
 5867        }
 5868
 5869        let first_edit_start = edits.first().unwrap().0.start;
 5870        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5871        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5872
 5873        let last_edit_end = edits.last().unwrap().0.end;
 5874        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5875        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5876
 5877        let cursor_row = cursor.to_point(&multibuffer).row;
 5878
 5879        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5880
 5881        let mut inlay_ids = Vec::new();
 5882        let invalidation_row_range;
 5883        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5884            Some(cursor_row..edit_end_row)
 5885        } else if cursor_row > edit_end_row {
 5886            Some(edit_start_row..cursor_row)
 5887        } else {
 5888            None
 5889        };
 5890        let is_move =
 5891            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5892        let completion = if is_move {
 5893            invalidation_row_range =
 5894                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5895            let target = first_edit_start;
 5896            InlineCompletion::Move { target, snapshot }
 5897        } else {
 5898            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 5899                && !self.inline_completions_hidden_for_vim_mode;
 5900
 5901            if show_completions_in_buffer {
 5902                if edits
 5903                    .iter()
 5904                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5905                {
 5906                    let mut inlays = Vec::new();
 5907                    for (range, new_text) in &edits {
 5908                        let inlay = Inlay::inline_completion(
 5909                            post_inc(&mut self.next_inlay_id),
 5910                            range.start,
 5911                            new_text.as_str(),
 5912                        );
 5913                        inlay_ids.push(inlay.id);
 5914                        inlays.push(inlay);
 5915                    }
 5916
 5917                    self.splice_inlays(&[], inlays, cx);
 5918                } else {
 5919                    let background_color = cx.theme().status().deleted_background;
 5920                    self.highlight_text::<InlineCompletionHighlight>(
 5921                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5922                        HighlightStyle {
 5923                            background_color: Some(background_color),
 5924                            ..Default::default()
 5925                        },
 5926                        cx,
 5927                    );
 5928                }
 5929            }
 5930
 5931            invalidation_row_range = edit_start_row..edit_end_row;
 5932
 5933            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5934                if provider.show_tab_accept_marker() {
 5935                    EditDisplayMode::TabAccept
 5936                } else {
 5937                    EditDisplayMode::Inline
 5938                }
 5939            } else {
 5940                EditDisplayMode::DiffPopover
 5941            };
 5942
 5943            InlineCompletion::Edit {
 5944                edits,
 5945                edit_preview: inline_completion.edit_preview,
 5946                display_mode,
 5947                snapshot,
 5948            }
 5949        };
 5950
 5951        let invalidation_range = multibuffer
 5952            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5953            ..multibuffer.anchor_after(Point::new(
 5954                invalidation_row_range.end,
 5955                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5956            ));
 5957
 5958        self.stale_inline_completion_in_menu = None;
 5959        self.active_inline_completion = Some(InlineCompletionState {
 5960            inlay_ids,
 5961            completion,
 5962            completion_id: inline_completion.id,
 5963            invalidation_range,
 5964        });
 5965
 5966        cx.notify();
 5967
 5968        Some(())
 5969    }
 5970
 5971    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5972        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5973    }
 5974
 5975    fn render_code_actions_indicator(
 5976        &self,
 5977        _style: &EditorStyle,
 5978        row: DisplayRow,
 5979        is_active: bool,
 5980        breakpoint: Option<&(Anchor, Breakpoint)>,
 5981        cx: &mut Context<Self>,
 5982    ) -> Option<IconButton> {
 5983        let color = Color::Muted;
 5984
 5985        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 5986        let bp_kind = Arc::new(
 5987            breakpoint
 5988                .map(|(_, bp)| bp.kind.clone())
 5989                .unwrap_or(BreakpointKind::Standard),
 5990        );
 5991
 5992        if self.available_code_actions.is_some() {
 5993            Some(
 5994                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5995                    .shape(ui::IconButtonShape::Square)
 5996                    .icon_size(IconSize::XSmall)
 5997                    .icon_color(color)
 5998                    .toggle_state(is_active)
 5999                    .tooltip({
 6000                        let focus_handle = self.focus_handle.clone();
 6001                        move |window, cx| {
 6002                            Tooltip::for_action_in(
 6003                                "Toggle Code Actions",
 6004                                &ToggleCodeActions {
 6005                                    deployed_from_indicator: None,
 6006                                },
 6007                                &focus_handle,
 6008                                window,
 6009                                cx,
 6010                            )
 6011                        }
 6012                    })
 6013                    .on_click(cx.listener(move |editor, _e, window, cx| {
 6014                        window.focus(&editor.focus_handle(cx));
 6015                        editor.toggle_code_actions(
 6016                            &ToggleCodeActions {
 6017                                deployed_from_indicator: Some(row),
 6018                            },
 6019                            window,
 6020                            cx,
 6021                        );
 6022                    }))
 6023                    .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6024                        editor.set_breakpoint_context_menu(
 6025                            row,
 6026                            position,
 6027                            bp_kind.clone(),
 6028                            event.down.position,
 6029                            window,
 6030                            cx,
 6031                        );
 6032                    })),
 6033            )
 6034        } else {
 6035            None
 6036        }
 6037    }
 6038
 6039    fn clear_tasks(&mut self) {
 6040        self.tasks.clear()
 6041    }
 6042
 6043    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 6044        if self.tasks.insert(key, value).is_some() {
 6045            // This case should hopefully be rare, but just in case...
 6046            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 6047        }
 6048    }
 6049
 6050    /// Get all display points of breakpoints that will be rendered within editor
 6051    ///
 6052    /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
 6053    /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
 6054    /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
 6055    fn active_breakpoints(
 6056        &mut self,
 6057        range: Range<DisplayRow>,
 6058        window: &mut Window,
 6059        cx: &mut Context<Self>,
 6060    ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
 6061        let mut breakpoint_display_points = HashMap::default();
 6062
 6063        let Some(breakpoint_store) = self.breakpoint_store.clone() else {
 6064            return breakpoint_display_points;
 6065        };
 6066
 6067        let snapshot = self.snapshot(window, cx);
 6068
 6069        let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
 6070        let Some(project) = self.project.as_ref() else {
 6071            return breakpoint_display_points;
 6072        };
 6073
 6074        if let Some(buffer) = self.buffer.read(cx).as_singleton() {
 6075            let buffer_snapshot = buffer.read(cx).snapshot();
 6076
 6077            for breakpoint in
 6078                breakpoint_store
 6079                    .read(cx)
 6080                    .breakpoints(&buffer, None, buffer_snapshot.clone(), cx)
 6081            {
 6082                let point = buffer_snapshot.summary_for_anchor::<Point>(&breakpoint.0);
 6083                let mut anchor = multi_buffer_snapshot.anchor_before(point);
 6084                anchor.text_anchor = breakpoint.0;
 6085
 6086                breakpoint_display_points.insert(
 6087                    snapshot
 6088                        .point_to_display_point(
 6089                            MultiBufferPoint {
 6090                                row: point.row,
 6091                                column: point.column,
 6092                            },
 6093                            Bias::Left,
 6094                        )
 6095                        .row(),
 6096                    (anchor, breakpoint.1.clone()),
 6097                );
 6098            }
 6099
 6100            return breakpoint_display_points;
 6101        }
 6102
 6103        let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
 6104            ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
 6105        for excerpt_boundary in multi_buffer_snapshot.excerpt_boundaries_in_range(range) {
 6106            let info = excerpt_boundary.next;
 6107
 6108            let Some(excerpt_ranges) = multi_buffer_snapshot.range_for_excerpt(info.id) else {
 6109                continue;
 6110            };
 6111
 6112            let Some(buffer) =
 6113                project.read_with(cx, |this, cx| this.buffer_for_id(info.buffer_id, cx))
 6114            else {
 6115                continue;
 6116            };
 6117
 6118            if buffer.read(cx).file().is_none() {
 6119                continue;
 6120            }
 6121            let breakpoints = breakpoint_store.read(cx).breakpoints(
 6122                &buffer,
 6123                Some(info.range.context.start..info.range.context.end),
 6124                info.buffer.clone(),
 6125                cx,
 6126            );
 6127
 6128            // To translate a breakpoint's position within a singular buffer to a multi buffer
 6129            // position we need to know it's excerpt starting location, it's position within
 6130            // the singular buffer, and if that position is within the excerpt's range.
 6131            let excerpt_head = excerpt_ranges
 6132                .start
 6133                .to_display_point(&snapshot.display_snapshot);
 6134
 6135            let buffer_start = info
 6136                .buffer
 6137                .summary_for_anchor::<Point>(&info.range.context.start);
 6138
 6139            for (anchor, breakpoint) in breakpoints {
 6140                let as_row = info.buffer.summary_for_anchor::<Point>(&anchor).row;
 6141                let delta = as_row - buffer_start.row;
 6142
 6143                let position = excerpt_head + DisplayPoint::new(DisplayRow(delta), 0);
 6144
 6145                let anchor = snapshot.display_point_to_anchor(position, Bias::Left);
 6146
 6147                breakpoint_display_points.insert(position.row(), (anchor, breakpoint.clone()));
 6148            }
 6149        }
 6150
 6151        breakpoint_display_points
 6152    }
 6153
 6154    fn breakpoint_context_menu(
 6155        &self,
 6156        anchor: Anchor,
 6157        kind: Arc<BreakpointKind>,
 6158        window: &mut Window,
 6159        cx: &mut Context<Self>,
 6160    ) -> Entity<ui::ContextMenu> {
 6161        let weak_editor = cx.weak_entity();
 6162        let focus_handle = self.focus_handle(cx);
 6163
 6164        let second_entry_msg = if kind.log_message().is_some() {
 6165            "Edit Log Breakpoint"
 6166        } else {
 6167            "Add Log Breakpoint"
 6168        };
 6169
 6170        ui::ContextMenu::build(window, cx, |menu, _, _cx| {
 6171            menu.on_blur_subscription(Subscription::new(|| {}))
 6172                .context(focus_handle)
 6173                .entry("Toggle Breakpoint", None, {
 6174                    let weak_editor = weak_editor.clone();
 6175                    move |_window, cx| {
 6176                        weak_editor
 6177                            .update(cx, |this, cx| {
 6178                                this.edit_breakpoint_at_anchor(
 6179                                    anchor,
 6180                                    BreakpointKind::Standard,
 6181                                    BreakpointEditAction::Toggle,
 6182                                    cx,
 6183                                );
 6184                            })
 6185                            .log_err();
 6186                    }
 6187                })
 6188                .entry(second_entry_msg, None, move |window, cx| {
 6189                    weak_editor
 6190                        .update(cx, |this, cx| {
 6191                            this.add_edit_breakpoint_block(anchor, kind.as_ref(), window, cx);
 6192                        })
 6193                        .log_err();
 6194                })
 6195        })
 6196    }
 6197
 6198    fn render_breakpoint(
 6199        &self,
 6200        position: Anchor,
 6201        row: DisplayRow,
 6202        kind: &BreakpointKind,
 6203        cx: &mut Context<Self>,
 6204    ) -> IconButton {
 6205        let color = if self
 6206            .gutter_breakpoint_indicator
 6207            .is_some_and(|gutter_bp| gutter_bp.row() == row)
 6208        {
 6209            Color::Hint
 6210        } else {
 6211            Color::Debugger
 6212        };
 6213
 6214        let icon = match &kind {
 6215            BreakpointKind::Standard => ui::IconName::DebugBreakpoint,
 6216            BreakpointKind::Log(_) => ui::IconName::DebugLogBreakpoint,
 6217        };
 6218        let arc_kind = Arc::new(kind.clone());
 6219        let arc_kind2 = arc_kind.clone();
 6220
 6221        IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
 6222            .icon_size(IconSize::XSmall)
 6223            .size(ui::ButtonSize::None)
 6224            .icon_color(color)
 6225            .style(ButtonStyle::Transparent)
 6226            .on_click(cx.listener(move |editor, _e, window, cx| {
 6227                window.focus(&editor.focus_handle(cx));
 6228                editor.edit_breakpoint_at_anchor(
 6229                    position,
 6230                    arc_kind.as_ref().clone(),
 6231                    BreakpointEditAction::Toggle,
 6232                    cx,
 6233                );
 6234            }))
 6235            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6236                editor.set_breakpoint_context_menu(
 6237                    row,
 6238                    Some(position),
 6239                    arc_kind2.clone(),
 6240                    event.down.position,
 6241                    window,
 6242                    cx,
 6243                );
 6244            }))
 6245    }
 6246
 6247    fn build_tasks_context(
 6248        project: &Entity<Project>,
 6249        buffer: &Entity<Buffer>,
 6250        buffer_row: u32,
 6251        tasks: &Arc<RunnableTasks>,
 6252        cx: &mut Context<Self>,
 6253    ) -> Task<Option<task::TaskContext>> {
 6254        let position = Point::new(buffer_row, tasks.column);
 6255        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 6256        let location = Location {
 6257            buffer: buffer.clone(),
 6258            range: range_start..range_start,
 6259        };
 6260        // Fill in the environmental variables from the tree-sitter captures
 6261        let mut captured_task_variables = TaskVariables::default();
 6262        for (capture_name, value) in tasks.extra_variables.clone() {
 6263            captured_task_variables.insert(
 6264                task::VariableName::Custom(capture_name.into()),
 6265                value.clone(),
 6266            );
 6267        }
 6268        project.update(cx, |project, cx| {
 6269            project.task_store().update(cx, |task_store, cx| {
 6270                task_store.task_context_for_location(captured_task_variables, location, cx)
 6271            })
 6272        })
 6273    }
 6274
 6275    pub fn spawn_nearest_task(
 6276        &mut self,
 6277        action: &SpawnNearestTask,
 6278        window: &mut Window,
 6279        cx: &mut Context<Self>,
 6280    ) {
 6281        let Some((workspace, _)) = self.workspace.clone() else {
 6282            return;
 6283        };
 6284        let Some(project) = self.project.clone() else {
 6285            return;
 6286        };
 6287
 6288        // Try to find a closest, enclosing node using tree-sitter that has a
 6289        // task
 6290        let Some((buffer, buffer_row, tasks)) = self
 6291            .find_enclosing_node_task(cx)
 6292            // Or find the task that's closest in row-distance.
 6293            .or_else(|| self.find_closest_task(cx))
 6294        else {
 6295            return;
 6296        };
 6297
 6298        let reveal_strategy = action.reveal;
 6299        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 6300        cx.spawn_in(window, async move |_, cx| {
 6301            let context = task_context.await?;
 6302            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 6303
 6304            let resolved = resolved_task.resolved.as_mut()?;
 6305            resolved.reveal = reveal_strategy;
 6306
 6307            workspace
 6308                .update(cx, |workspace, cx| {
 6309                    workspace::tasks::schedule_resolved_task(
 6310                        workspace,
 6311                        task_source_kind,
 6312                        resolved_task,
 6313                        false,
 6314                        cx,
 6315                    );
 6316                })
 6317                .ok()
 6318        })
 6319        .detach();
 6320    }
 6321
 6322    fn find_closest_task(
 6323        &mut self,
 6324        cx: &mut Context<Self>,
 6325    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6326        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 6327
 6328        let ((buffer_id, row), tasks) = self
 6329            .tasks
 6330            .iter()
 6331            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 6332
 6333        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 6334        let tasks = Arc::new(tasks.to_owned());
 6335        Some((buffer, *row, tasks))
 6336    }
 6337
 6338    fn find_enclosing_node_task(
 6339        &mut self,
 6340        cx: &mut Context<Self>,
 6341    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6342        let snapshot = self.buffer.read(cx).snapshot(cx);
 6343        let offset = self.selections.newest::<usize>(cx).head();
 6344        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 6345        let buffer_id = excerpt.buffer().remote_id();
 6346
 6347        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 6348        let mut cursor = layer.node().walk();
 6349
 6350        while cursor.goto_first_child_for_byte(offset).is_some() {
 6351            if cursor.node().end_byte() == offset {
 6352                cursor.goto_next_sibling();
 6353            }
 6354        }
 6355
 6356        // Ascend to the smallest ancestor that contains the range and has a task.
 6357        loop {
 6358            let node = cursor.node();
 6359            let node_range = node.byte_range();
 6360            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 6361
 6362            // Check if this node contains our offset
 6363            if node_range.start <= offset && node_range.end >= offset {
 6364                // If it contains offset, check for task
 6365                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 6366                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 6367                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 6368                }
 6369            }
 6370
 6371            if !cursor.goto_parent() {
 6372                break;
 6373            }
 6374        }
 6375        None
 6376    }
 6377
 6378    fn render_run_indicator(
 6379        &self,
 6380        _style: &EditorStyle,
 6381        is_active: bool,
 6382        row: DisplayRow,
 6383        breakpoint: Option<(Anchor, Breakpoint)>,
 6384        cx: &mut Context<Self>,
 6385    ) -> IconButton {
 6386        let color = Color::Muted;
 6387
 6388        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6389        let bp_kind = Arc::new(
 6390            breakpoint
 6391                .map(|(_, bp)| bp.kind)
 6392                .unwrap_or(BreakpointKind::Standard),
 6393        );
 6394
 6395        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 6396            .shape(ui::IconButtonShape::Square)
 6397            .icon_size(IconSize::XSmall)
 6398            .icon_color(color)
 6399            .toggle_state(is_active)
 6400            .on_click(cx.listener(move |editor, _e, window, cx| {
 6401                window.focus(&editor.focus_handle(cx));
 6402                editor.toggle_code_actions(
 6403                    &ToggleCodeActions {
 6404                        deployed_from_indicator: Some(row),
 6405                    },
 6406                    window,
 6407                    cx,
 6408                );
 6409            }))
 6410            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6411                editor.set_breakpoint_context_menu(
 6412                    row,
 6413                    position,
 6414                    bp_kind.clone(),
 6415                    event.down.position,
 6416                    window,
 6417                    cx,
 6418                );
 6419            }))
 6420    }
 6421
 6422    pub fn context_menu_visible(&self) -> bool {
 6423        !self.edit_prediction_preview_is_active()
 6424            && self
 6425                .context_menu
 6426                .borrow()
 6427                .as_ref()
 6428                .map_or(false, |menu| menu.visible())
 6429    }
 6430
 6431    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 6432        self.context_menu
 6433            .borrow()
 6434            .as_ref()
 6435            .map(|menu| menu.origin())
 6436    }
 6437
 6438    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 6439    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 6440
 6441    fn render_edit_prediction_popover(
 6442        &mut self,
 6443        text_bounds: &Bounds<Pixels>,
 6444        content_origin: gpui::Point<Pixels>,
 6445        editor_snapshot: &EditorSnapshot,
 6446        visible_row_range: Range<DisplayRow>,
 6447        scroll_top: f32,
 6448        scroll_bottom: f32,
 6449        line_layouts: &[LineWithInvisibles],
 6450        line_height: Pixels,
 6451        scroll_pixel_position: gpui::Point<Pixels>,
 6452        newest_selection_head: Option<DisplayPoint>,
 6453        editor_width: Pixels,
 6454        style: &EditorStyle,
 6455        window: &mut Window,
 6456        cx: &mut App,
 6457    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6458        let active_inline_completion = self.active_inline_completion.as_ref()?;
 6459
 6460        if self.edit_prediction_visible_in_cursor_popover(true) {
 6461            return None;
 6462        }
 6463
 6464        match &active_inline_completion.completion {
 6465            InlineCompletion::Move { target, .. } => {
 6466                let target_display_point = target.to_display_point(editor_snapshot);
 6467
 6468                if self.edit_prediction_requires_modifier() {
 6469                    if !self.edit_prediction_preview_is_active() {
 6470                        return None;
 6471                    }
 6472
 6473                    self.render_edit_prediction_modifier_jump_popover(
 6474                        text_bounds,
 6475                        content_origin,
 6476                        visible_row_range,
 6477                        line_layouts,
 6478                        line_height,
 6479                        scroll_pixel_position,
 6480                        newest_selection_head,
 6481                        target_display_point,
 6482                        window,
 6483                        cx,
 6484                    )
 6485                } else {
 6486                    self.render_edit_prediction_eager_jump_popover(
 6487                        text_bounds,
 6488                        content_origin,
 6489                        editor_snapshot,
 6490                        visible_row_range,
 6491                        scroll_top,
 6492                        scroll_bottom,
 6493                        line_height,
 6494                        scroll_pixel_position,
 6495                        target_display_point,
 6496                        editor_width,
 6497                        window,
 6498                        cx,
 6499                    )
 6500                }
 6501            }
 6502            InlineCompletion::Edit {
 6503                display_mode: EditDisplayMode::Inline,
 6504                ..
 6505            } => None,
 6506            InlineCompletion::Edit {
 6507                display_mode: EditDisplayMode::TabAccept,
 6508                edits,
 6509                ..
 6510            } => {
 6511                let range = &edits.first()?.0;
 6512                let target_display_point = range.end.to_display_point(editor_snapshot);
 6513
 6514                self.render_edit_prediction_end_of_line_popover(
 6515                    "Accept",
 6516                    editor_snapshot,
 6517                    visible_row_range,
 6518                    target_display_point,
 6519                    line_height,
 6520                    scroll_pixel_position,
 6521                    content_origin,
 6522                    editor_width,
 6523                    window,
 6524                    cx,
 6525                )
 6526            }
 6527            InlineCompletion::Edit {
 6528                edits,
 6529                edit_preview,
 6530                display_mode: EditDisplayMode::DiffPopover,
 6531                snapshot,
 6532            } => self.render_edit_prediction_diff_popover(
 6533                text_bounds,
 6534                content_origin,
 6535                editor_snapshot,
 6536                visible_row_range,
 6537                line_layouts,
 6538                line_height,
 6539                scroll_pixel_position,
 6540                newest_selection_head,
 6541                editor_width,
 6542                style,
 6543                edits,
 6544                edit_preview,
 6545                snapshot,
 6546                window,
 6547                cx,
 6548            ),
 6549        }
 6550    }
 6551
 6552    fn render_edit_prediction_modifier_jump_popover(
 6553        &mut self,
 6554        text_bounds: &Bounds<Pixels>,
 6555        content_origin: gpui::Point<Pixels>,
 6556        visible_row_range: Range<DisplayRow>,
 6557        line_layouts: &[LineWithInvisibles],
 6558        line_height: Pixels,
 6559        scroll_pixel_position: gpui::Point<Pixels>,
 6560        newest_selection_head: Option<DisplayPoint>,
 6561        target_display_point: DisplayPoint,
 6562        window: &mut Window,
 6563        cx: &mut App,
 6564    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6565        let scrolled_content_origin =
 6566            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 6567
 6568        const SCROLL_PADDING_Y: Pixels = px(12.);
 6569
 6570        if target_display_point.row() < visible_row_range.start {
 6571            return self.render_edit_prediction_scroll_popover(
 6572                |_| SCROLL_PADDING_Y,
 6573                IconName::ArrowUp,
 6574                visible_row_range,
 6575                line_layouts,
 6576                newest_selection_head,
 6577                scrolled_content_origin,
 6578                window,
 6579                cx,
 6580            );
 6581        } else if target_display_point.row() >= visible_row_range.end {
 6582            return self.render_edit_prediction_scroll_popover(
 6583                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 6584                IconName::ArrowDown,
 6585                visible_row_range,
 6586                line_layouts,
 6587                newest_selection_head,
 6588                scrolled_content_origin,
 6589                window,
 6590                cx,
 6591            );
 6592        }
 6593
 6594        const POLE_WIDTH: Pixels = px(2.);
 6595
 6596        let line_layout =
 6597            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 6598        let target_column = target_display_point.column() as usize;
 6599
 6600        let target_x = line_layout.x_for_index(target_column);
 6601        let target_y =
 6602            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 6603
 6604        let flag_on_right = target_x < text_bounds.size.width / 2.;
 6605
 6606        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 6607        border_color.l += 0.001;
 6608
 6609        let mut element = v_flex()
 6610            .items_end()
 6611            .when(flag_on_right, |el| el.items_start())
 6612            .child(if flag_on_right {
 6613                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6614                    .rounded_bl(px(0.))
 6615                    .rounded_tl(px(0.))
 6616                    .border_l_2()
 6617                    .border_color(border_color)
 6618            } else {
 6619                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6620                    .rounded_br(px(0.))
 6621                    .rounded_tr(px(0.))
 6622                    .border_r_2()
 6623                    .border_color(border_color)
 6624            })
 6625            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 6626            .into_any();
 6627
 6628        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6629
 6630        let mut origin = scrolled_content_origin + point(target_x, target_y)
 6631            - point(
 6632                if flag_on_right {
 6633                    POLE_WIDTH
 6634                } else {
 6635                    size.width - POLE_WIDTH
 6636                },
 6637                size.height - line_height,
 6638            );
 6639
 6640        origin.x = origin.x.max(content_origin.x);
 6641
 6642        element.prepaint_at(origin, window, cx);
 6643
 6644        Some((element, origin))
 6645    }
 6646
 6647    fn render_edit_prediction_scroll_popover(
 6648        &mut self,
 6649        to_y: impl Fn(Size<Pixels>) -> Pixels,
 6650        scroll_icon: IconName,
 6651        visible_row_range: Range<DisplayRow>,
 6652        line_layouts: &[LineWithInvisibles],
 6653        newest_selection_head: Option<DisplayPoint>,
 6654        scrolled_content_origin: gpui::Point<Pixels>,
 6655        window: &mut Window,
 6656        cx: &mut App,
 6657    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6658        let mut element = self
 6659            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 6660            .into_any();
 6661
 6662        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6663
 6664        let cursor = newest_selection_head?;
 6665        let cursor_row_layout =
 6666            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 6667        let cursor_column = cursor.column() as usize;
 6668
 6669        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 6670
 6671        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 6672
 6673        element.prepaint_at(origin, window, cx);
 6674        Some((element, origin))
 6675    }
 6676
 6677    fn render_edit_prediction_eager_jump_popover(
 6678        &mut self,
 6679        text_bounds: &Bounds<Pixels>,
 6680        content_origin: gpui::Point<Pixels>,
 6681        editor_snapshot: &EditorSnapshot,
 6682        visible_row_range: Range<DisplayRow>,
 6683        scroll_top: f32,
 6684        scroll_bottom: f32,
 6685        line_height: Pixels,
 6686        scroll_pixel_position: gpui::Point<Pixels>,
 6687        target_display_point: DisplayPoint,
 6688        editor_width: Pixels,
 6689        window: &mut Window,
 6690        cx: &mut App,
 6691    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6692        if target_display_point.row().as_f32() < scroll_top {
 6693            let mut element = self
 6694                .render_edit_prediction_line_popover(
 6695                    "Jump to Edit",
 6696                    Some(IconName::ArrowUp),
 6697                    window,
 6698                    cx,
 6699                )?
 6700                .into_any();
 6701
 6702            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6703            let offset = point(
 6704                (text_bounds.size.width - size.width) / 2.,
 6705                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6706            );
 6707
 6708            let origin = text_bounds.origin + offset;
 6709            element.prepaint_at(origin, window, cx);
 6710            Some((element, origin))
 6711        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 6712            let mut element = self
 6713                .render_edit_prediction_line_popover(
 6714                    "Jump to Edit",
 6715                    Some(IconName::ArrowDown),
 6716                    window,
 6717                    cx,
 6718                )?
 6719                .into_any();
 6720
 6721            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6722            let offset = point(
 6723                (text_bounds.size.width - size.width) / 2.,
 6724                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6725            );
 6726
 6727            let origin = text_bounds.origin + offset;
 6728            element.prepaint_at(origin, window, cx);
 6729            Some((element, origin))
 6730        } else {
 6731            self.render_edit_prediction_end_of_line_popover(
 6732                "Jump to Edit",
 6733                editor_snapshot,
 6734                visible_row_range,
 6735                target_display_point,
 6736                line_height,
 6737                scroll_pixel_position,
 6738                content_origin,
 6739                editor_width,
 6740                window,
 6741                cx,
 6742            )
 6743        }
 6744    }
 6745
 6746    fn render_edit_prediction_end_of_line_popover(
 6747        self: &mut Editor,
 6748        label: &'static str,
 6749        editor_snapshot: &EditorSnapshot,
 6750        visible_row_range: Range<DisplayRow>,
 6751        target_display_point: DisplayPoint,
 6752        line_height: Pixels,
 6753        scroll_pixel_position: gpui::Point<Pixels>,
 6754        content_origin: gpui::Point<Pixels>,
 6755        editor_width: Pixels,
 6756        window: &mut Window,
 6757        cx: &mut App,
 6758    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6759        let target_line_end = DisplayPoint::new(
 6760            target_display_point.row(),
 6761            editor_snapshot.line_len(target_display_point.row()),
 6762        );
 6763
 6764        let mut element = self
 6765            .render_edit_prediction_line_popover(label, None, window, cx)?
 6766            .into_any();
 6767
 6768        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6769
 6770        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 6771
 6772        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 6773        let mut origin = start_point
 6774            + line_origin
 6775            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 6776        origin.x = origin.x.max(content_origin.x);
 6777
 6778        let max_x = content_origin.x + editor_width - size.width;
 6779
 6780        if origin.x > max_x {
 6781            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 6782
 6783            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 6784                origin.y += offset;
 6785                IconName::ArrowUp
 6786            } else {
 6787                origin.y -= offset;
 6788                IconName::ArrowDown
 6789            };
 6790
 6791            element = self
 6792                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 6793                .into_any();
 6794
 6795            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6796
 6797            origin.x = content_origin.x + editor_width - size.width - px(2.);
 6798        }
 6799
 6800        element.prepaint_at(origin, window, cx);
 6801        Some((element, origin))
 6802    }
 6803
 6804    fn render_edit_prediction_diff_popover(
 6805        self: &Editor,
 6806        text_bounds: &Bounds<Pixels>,
 6807        content_origin: gpui::Point<Pixels>,
 6808        editor_snapshot: &EditorSnapshot,
 6809        visible_row_range: Range<DisplayRow>,
 6810        line_layouts: &[LineWithInvisibles],
 6811        line_height: Pixels,
 6812        scroll_pixel_position: gpui::Point<Pixels>,
 6813        newest_selection_head: Option<DisplayPoint>,
 6814        editor_width: Pixels,
 6815        style: &EditorStyle,
 6816        edits: &Vec<(Range<Anchor>, String)>,
 6817        edit_preview: &Option<language::EditPreview>,
 6818        snapshot: &language::BufferSnapshot,
 6819        window: &mut Window,
 6820        cx: &mut App,
 6821    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6822        let edit_start = edits
 6823            .first()
 6824            .unwrap()
 6825            .0
 6826            .start
 6827            .to_display_point(editor_snapshot);
 6828        let edit_end = edits
 6829            .last()
 6830            .unwrap()
 6831            .0
 6832            .end
 6833            .to_display_point(editor_snapshot);
 6834
 6835        let is_visible = visible_row_range.contains(&edit_start.row())
 6836            || visible_row_range.contains(&edit_end.row());
 6837        if !is_visible {
 6838            return None;
 6839        }
 6840
 6841        let highlighted_edits =
 6842            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 6843
 6844        let styled_text = highlighted_edits.to_styled_text(&style.text);
 6845        let line_count = highlighted_edits.text.lines().count();
 6846
 6847        const BORDER_WIDTH: Pixels = px(1.);
 6848
 6849        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 6850        let has_keybind = keybind.is_some();
 6851
 6852        let mut element = h_flex()
 6853            .items_start()
 6854            .child(
 6855                h_flex()
 6856                    .bg(cx.theme().colors().editor_background)
 6857                    .border(BORDER_WIDTH)
 6858                    .shadow_sm()
 6859                    .border_color(cx.theme().colors().border)
 6860                    .rounded_l_lg()
 6861                    .when(line_count > 1, |el| el.rounded_br_lg())
 6862                    .pr_1()
 6863                    .child(styled_text),
 6864            )
 6865            .child(
 6866                h_flex()
 6867                    .h(line_height + BORDER_WIDTH * px(2.))
 6868                    .px_1p5()
 6869                    .gap_1()
 6870                    // Workaround: For some reason, there's a gap if we don't do this
 6871                    .ml(-BORDER_WIDTH)
 6872                    .shadow(smallvec![gpui::BoxShadow {
 6873                        color: gpui::black().opacity(0.05),
 6874                        offset: point(px(1.), px(1.)),
 6875                        blur_radius: px(2.),
 6876                        spread_radius: px(0.),
 6877                    }])
 6878                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 6879                    .border(BORDER_WIDTH)
 6880                    .border_color(cx.theme().colors().border)
 6881                    .rounded_r_lg()
 6882                    .id("edit_prediction_diff_popover_keybind")
 6883                    .when(!has_keybind, |el| {
 6884                        let status_colors = cx.theme().status();
 6885
 6886                        el.bg(status_colors.error_background)
 6887                            .border_color(status_colors.error.opacity(0.6))
 6888                            .child(Icon::new(IconName::Info).color(Color::Error))
 6889                            .cursor_default()
 6890                            .hoverable_tooltip(move |_window, cx| {
 6891                                cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 6892                            })
 6893                    })
 6894                    .children(keybind),
 6895            )
 6896            .into_any();
 6897
 6898        let longest_row =
 6899            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 6900        let longest_line_width = if visible_row_range.contains(&longest_row) {
 6901            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 6902        } else {
 6903            layout_line(
 6904                longest_row,
 6905                editor_snapshot,
 6906                style,
 6907                editor_width,
 6908                |_| false,
 6909                window,
 6910                cx,
 6911            )
 6912            .width
 6913        };
 6914
 6915        let viewport_bounds =
 6916            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 6917                right: -EditorElement::SCROLLBAR_WIDTH,
 6918                ..Default::default()
 6919            });
 6920
 6921        let x_after_longest =
 6922            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 6923                - scroll_pixel_position.x;
 6924
 6925        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6926
 6927        // Fully visible if it can be displayed within the window (allow overlapping other
 6928        // panes). However, this is only allowed if the popover starts within text_bounds.
 6929        let can_position_to_the_right = x_after_longest < text_bounds.right()
 6930            && x_after_longest + element_bounds.width < viewport_bounds.right();
 6931
 6932        let mut origin = if can_position_to_the_right {
 6933            point(
 6934                x_after_longest,
 6935                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 6936                    - scroll_pixel_position.y,
 6937            )
 6938        } else {
 6939            let cursor_row = newest_selection_head.map(|head| head.row());
 6940            let above_edit = edit_start
 6941                .row()
 6942                .0
 6943                .checked_sub(line_count as u32)
 6944                .map(DisplayRow);
 6945            let below_edit = Some(edit_end.row() + 1);
 6946            let above_cursor =
 6947                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 6948            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 6949
 6950            // Place the edit popover adjacent to the edit if there is a location
 6951            // available that is onscreen and does not obscure the cursor. Otherwise,
 6952            // place it adjacent to the cursor.
 6953            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 6954                .into_iter()
 6955                .flatten()
 6956                .find(|&start_row| {
 6957                    let end_row = start_row + line_count as u32;
 6958                    visible_row_range.contains(&start_row)
 6959                        && visible_row_range.contains(&end_row)
 6960                        && cursor_row.map_or(true, |cursor_row| {
 6961                            !((start_row..end_row).contains(&cursor_row))
 6962                        })
 6963                })?;
 6964
 6965            content_origin
 6966                + point(
 6967                    -scroll_pixel_position.x,
 6968                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 6969                )
 6970        };
 6971
 6972        origin.x -= BORDER_WIDTH;
 6973
 6974        window.defer_draw(element, origin, 1);
 6975
 6976        // Do not return an element, since it will already be drawn due to defer_draw.
 6977        None
 6978    }
 6979
 6980    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 6981        px(30.)
 6982    }
 6983
 6984    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 6985        if self.read_only(cx) {
 6986            cx.theme().players().read_only()
 6987        } else {
 6988            self.style.as_ref().unwrap().local_player
 6989        }
 6990    }
 6991
 6992    fn render_edit_prediction_accept_keybind(
 6993        &self,
 6994        window: &mut Window,
 6995        cx: &App,
 6996    ) -> Option<AnyElement> {
 6997        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 6998        let accept_keystroke = accept_binding.keystroke()?;
 6999
 7000        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7001
 7002        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 7003            Color::Accent
 7004        } else {
 7005            Color::Muted
 7006        };
 7007
 7008        h_flex()
 7009            .px_0p5()
 7010            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 7011            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7012            .text_size(TextSize::XSmall.rems(cx))
 7013            .child(h_flex().children(ui::render_modifiers(
 7014                &accept_keystroke.modifiers,
 7015                PlatformStyle::platform(),
 7016                Some(modifiers_color),
 7017                Some(IconSize::XSmall.rems().into()),
 7018                true,
 7019            )))
 7020            .when(is_platform_style_mac, |parent| {
 7021                parent.child(accept_keystroke.key.clone())
 7022            })
 7023            .when(!is_platform_style_mac, |parent| {
 7024                parent.child(
 7025                    Key::new(
 7026                        util::capitalize(&accept_keystroke.key),
 7027                        Some(Color::Default),
 7028                    )
 7029                    .size(Some(IconSize::XSmall.rems().into())),
 7030                )
 7031            })
 7032            .into_any()
 7033            .into()
 7034    }
 7035
 7036    fn render_edit_prediction_line_popover(
 7037        &self,
 7038        label: impl Into<SharedString>,
 7039        icon: Option<IconName>,
 7040        window: &mut Window,
 7041        cx: &App,
 7042    ) -> Option<Stateful<Div>> {
 7043        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 7044
 7045        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7046        let has_keybind = keybind.is_some();
 7047
 7048        let result = h_flex()
 7049            .id("ep-line-popover")
 7050            .py_0p5()
 7051            .pl_1()
 7052            .pr(padding_right)
 7053            .gap_1()
 7054            .rounded_md()
 7055            .border_1()
 7056            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7057            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 7058            .shadow_sm()
 7059            .when(!has_keybind, |el| {
 7060                let status_colors = cx.theme().status();
 7061
 7062                el.bg(status_colors.error_background)
 7063                    .border_color(status_colors.error.opacity(0.6))
 7064                    .pl_2()
 7065                    .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
 7066                    .cursor_default()
 7067                    .hoverable_tooltip(move |_window, cx| {
 7068                        cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7069                    })
 7070            })
 7071            .children(keybind)
 7072            .child(
 7073                Label::new(label)
 7074                    .size(LabelSize::Small)
 7075                    .when(!has_keybind, |el| {
 7076                        el.color(cx.theme().status().error.into()).strikethrough()
 7077                    }),
 7078            )
 7079            .when(!has_keybind, |el| {
 7080                el.child(
 7081                    h_flex().ml_1().child(
 7082                        Icon::new(IconName::Info)
 7083                            .size(IconSize::Small)
 7084                            .color(cx.theme().status().error.into()),
 7085                    ),
 7086                )
 7087            })
 7088            .when_some(icon, |element, icon| {
 7089                element.child(
 7090                    div()
 7091                        .mt(px(1.5))
 7092                        .child(Icon::new(icon).size(IconSize::Small)),
 7093                )
 7094            });
 7095
 7096        Some(result)
 7097    }
 7098
 7099    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 7100        let accent_color = cx.theme().colors().text_accent;
 7101        let editor_bg_color = cx.theme().colors().editor_background;
 7102        editor_bg_color.blend(accent_color.opacity(0.1))
 7103    }
 7104
 7105    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 7106        let accent_color = cx.theme().colors().text_accent;
 7107        let editor_bg_color = cx.theme().colors().editor_background;
 7108        editor_bg_color.blend(accent_color.opacity(0.6))
 7109    }
 7110
 7111    fn render_edit_prediction_cursor_popover(
 7112        &self,
 7113        min_width: Pixels,
 7114        max_width: Pixels,
 7115        cursor_point: Point,
 7116        style: &EditorStyle,
 7117        accept_keystroke: Option<&gpui::Keystroke>,
 7118        _window: &Window,
 7119        cx: &mut Context<Editor>,
 7120    ) -> Option<AnyElement> {
 7121        let provider = self.edit_prediction_provider.as_ref()?;
 7122
 7123        if provider.provider.needs_terms_acceptance(cx) {
 7124            return Some(
 7125                h_flex()
 7126                    .min_w(min_width)
 7127                    .flex_1()
 7128                    .px_2()
 7129                    .py_1()
 7130                    .gap_3()
 7131                    .elevation_2(cx)
 7132                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 7133                    .id("accept-terms")
 7134                    .cursor_pointer()
 7135                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 7136                    .on_click(cx.listener(|this, _event, window, cx| {
 7137                        cx.stop_propagation();
 7138                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 7139                        window.dispatch_action(
 7140                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 7141                            cx,
 7142                        );
 7143                    }))
 7144                    .child(
 7145                        h_flex()
 7146                            .flex_1()
 7147                            .gap_2()
 7148                            .child(Icon::new(IconName::ZedPredict))
 7149                            .child(Label::new("Accept Terms of Service"))
 7150                            .child(div().w_full())
 7151                            .child(
 7152                                Icon::new(IconName::ArrowUpRight)
 7153                                    .color(Color::Muted)
 7154                                    .size(IconSize::Small),
 7155                            )
 7156                            .into_any_element(),
 7157                    )
 7158                    .into_any(),
 7159            );
 7160        }
 7161
 7162        let is_refreshing = provider.provider.is_refreshing(cx);
 7163
 7164        fn pending_completion_container() -> Div {
 7165            h_flex()
 7166                .h_full()
 7167                .flex_1()
 7168                .gap_2()
 7169                .child(Icon::new(IconName::ZedPredict))
 7170        }
 7171
 7172        let completion = match &self.active_inline_completion {
 7173            Some(prediction) => {
 7174                if !self.has_visible_completions_menu() {
 7175                    const RADIUS: Pixels = px(6.);
 7176                    const BORDER_WIDTH: Pixels = px(1.);
 7177
 7178                    return Some(
 7179                        h_flex()
 7180                            .elevation_2(cx)
 7181                            .border(BORDER_WIDTH)
 7182                            .border_color(cx.theme().colors().border)
 7183                            .when(accept_keystroke.is_none(), |el| {
 7184                                el.border_color(cx.theme().status().error)
 7185                            })
 7186                            .rounded(RADIUS)
 7187                            .rounded_tl(px(0.))
 7188                            .overflow_hidden()
 7189                            .child(div().px_1p5().child(match &prediction.completion {
 7190                                InlineCompletion::Move { target, snapshot } => {
 7191                                    use text::ToPoint as _;
 7192                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 7193                                    {
 7194                                        Icon::new(IconName::ZedPredictDown)
 7195                                    } else {
 7196                                        Icon::new(IconName::ZedPredictUp)
 7197                                    }
 7198                                }
 7199                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 7200                            }))
 7201                            .child(
 7202                                h_flex()
 7203                                    .gap_1()
 7204                                    .py_1()
 7205                                    .px_2()
 7206                                    .rounded_r(RADIUS - BORDER_WIDTH)
 7207                                    .border_l_1()
 7208                                    .border_color(cx.theme().colors().border)
 7209                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7210                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 7211                                        el.child(
 7212                                            Label::new("Hold")
 7213                                                .size(LabelSize::Small)
 7214                                                .when(accept_keystroke.is_none(), |el| {
 7215                                                    el.strikethrough()
 7216                                                })
 7217                                                .line_height_style(LineHeightStyle::UiLabel),
 7218                                        )
 7219                                    })
 7220                                    .id("edit_prediction_cursor_popover_keybind")
 7221                                    .when(accept_keystroke.is_none(), |el| {
 7222                                        let status_colors = cx.theme().status();
 7223
 7224                                        el.bg(status_colors.error_background)
 7225                                            .border_color(status_colors.error.opacity(0.6))
 7226                                            .child(Icon::new(IconName::Info).color(Color::Error))
 7227                                            .cursor_default()
 7228                                            .hoverable_tooltip(move |_window, cx| {
 7229                                                cx.new(|_| MissingEditPredictionKeybindingTooltip)
 7230                                                    .into()
 7231                                            })
 7232                                    })
 7233                                    .when_some(
 7234                                        accept_keystroke.as_ref(),
 7235                                        |el, accept_keystroke| {
 7236                                            el.child(h_flex().children(ui::render_modifiers(
 7237                                                &accept_keystroke.modifiers,
 7238                                                PlatformStyle::platform(),
 7239                                                Some(Color::Default),
 7240                                                Some(IconSize::XSmall.rems().into()),
 7241                                                false,
 7242                                            )))
 7243                                        },
 7244                                    ),
 7245                            )
 7246                            .into_any(),
 7247                    );
 7248                }
 7249
 7250                self.render_edit_prediction_cursor_popover_preview(
 7251                    prediction,
 7252                    cursor_point,
 7253                    style,
 7254                    cx,
 7255                )?
 7256            }
 7257
 7258            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 7259                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 7260                    stale_completion,
 7261                    cursor_point,
 7262                    style,
 7263                    cx,
 7264                )?,
 7265
 7266                None => {
 7267                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 7268                }
 7269            },
 7270
 7271            None => pending_completion_container().child(Label::new("No Prediction")),
 7272        };
 7273
 7274        let completion = if is_refreshing {
 7275            completion
 7276                .with_animation(
 7277                    "loading-completion",
 7278                    Animation::new(Duration::from_secs(2))
 7279                        .repeat()
 7280                        .with_easing(pulsating_between(0.4, 0.8)),
 7281                    |label, delta| label.opacity(delta),
 7282                )
 7283                .into_any_element()
 7284        } else {
 7285            completion.into_any_element()
 7286        };
 7287
 7288        let has_completion = self.active_inline_completion.is_some();
 7289
 7290        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7291        Some(
 7292            h_flex()
 7293                .min_w(min_width)
 7294                .max_w(max_width)
 7295                .flex_1()
 7296                .elevation_2(cx)
 7297                .border_color(cx.theme().colors().border)
 7298                .child(
 7299                    div()
 7300                        .flex_1()
 7301                        .py_1()
 7302                        .px_2()
 7303                        .overflow_hidden()
 7304                        .child(completion),
 7305                )
 7306                .when_some(accept_keystroke, |el, accept_keystroke| {
 7307                    if !accept_keystroke.modifiers.modified() {
 7308                        return el;
 7309                    }
 7310
 7311                    el.child(
 7312                        h_flex()
 7313                            .h_full()
 7314                            .border_l_1()
 7315                            .rounded_r_lg()
 7316                            .border_color(cx.theme().colors().border)
 7317                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7318                            .gap_1()
 7319                            .py_1()
 7320                            .px_2()
 7321                            .child(
 7322                                h_flex()
 7323                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7324                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 7325                                    .child(h_flex().children(ui::render_modifiers(
 7326                                        &accept_keystroke.modifiers,
 7327                                        PlatformStyle::platform(),
 7328                                        Some(if !has_completion {
 7329                                            Color::Muted
 7330                                        } else {
 7331                                            Color::Default
 7332                                        }),
 7333                                        None,
 7334                                        false,
 7335                                    ))),
 7336                            )
 7337                            .child(Label::new("Preview").into_any_element())
 7338                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 7339                    )
 7340                })
 7341                .into_any(),
 7342        )
 7343    }
 7344
 7345    fn render_edit_prediction_cursor_popover_preview(
 7346        &self,
 7347        completion: &InlineCompletionState,
 7348        cursor_point: Point,
 7349        style: &EditorStyle,
 7350        cx: &mut Context<Editor>,
 7351    ) -> Option<Div> {
 7352        use text::ToPoint as _;
 7353
 7354        fn render_relative_row_jump(
 7355            prefix: impl Into<String>,
 7356            current_row: u32,
 7357            target_row: u32,
 7358        ) -> Div {
 7359            let (row_diff, arrow) = if target_row < current_row {
 7360                (current_row - target_row, IconName::ArrowUp)
 7361            } else {
 7362                (target_row - current_row, IconName::ArrowDown)
 7363            };
 7364
 7365            h_flex()
 7366                .child(
 7367                    Label::new(format!("{}{}", prefix.into(), row_diff))
 7368                        .color(Color::Muted)
 7369                        .size(LabelSize::Small),
 7370                )
 7371                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 7372        }
 7373
 7374        match &completion.completion {
 7375            InlineCompletion::Move {
 7376                target, snapshot, ..
 7377            } => Some(
 7378                h_flex()
 7379                    .px_2()
 7380                    .gap_2()
 7381                    .flex_1()
 7382                    .child(
 7383                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 7384                            Icon::new(IconName::ZedPredictDown)
 7385                        } else {
 7386                            Icon::new(IconName::ZedPredictUp)
 7387                        },
 7388                    )
 7389                    .child(Label::new("Jump to Edit")),
 7390            ),
 7391
 7392            InlineCompletion::Edit {
 7393                edits,
 7394                edit_preview,
 7395                snapshot,
 7396                display_mode: _,
 7397            } => {
 7398                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 7399
 7400                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 7401                    &snapshot,
 7402                    &edits,
 7403                    edit_preview.as_ref()?,
 7404                    true,
 7405                    cx,
 7406                )
 7407                .first_line_preview();
 7408
 7409                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 7410                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 7411
 7412                let preview = h_flex()
 7413                    .gap_1()
 7414                    .min_w_16()
 7415                    .child(styled_text)
 7416                    .when(has_more_lines, |parent| parent.child(""));
 7417
 7418                let left = if first_edit_row != cursor_point.row {
 7419                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 7420                        .into_any_element()
 7421                } else {
 7422                    Icon::new(IconName::ZedPredict).into_any_element()
 7423                };
 7424
 7425                Some(
 7426                    h_flex()
 7427                        .h_full()
 7428                        .flex_1()
 7429                        .gap_2()
 7430                        .pr_1()
 7431                        .overflow_x_hidden()
 7432                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7433                        .child(left)
 7434                        .child(preview),
 7435                )
 7436            }
 7437        }
 7438    }
 7439
 7440    fn render_context_menu(
 7441        &self,
 7442        style: &EditorStyle,
 7443        max_height_in_lines: u32,
 7444        y_flipped: bool,
 7445        window: &mut Window,
 7446        cx: &mut Context<Editor>,
 7447    ) -> Option<AnyElement> {
 7448        let menu = self.context_menu.borrow();
 7449        let menu = menu.as_ref()?;
 7450        if !menu.visible() {
 7451            return None;
 7452        };
 7453        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 7454    }
 7455
 7456    fn render_context_menu_aside(
 7457        &mut self,
 7458        max_size: Size<Pixels>,
 7459        window: &mut Window,
 7460        cx: &mut Context<Editor>,
 7461    ) -> Option<AnyElement> {
 7462        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 7463            if menu.visible() {
 7464                menu.render_aside(self, max_size, window, cx)
 7465            } else {
 7466                None
 7467            }
 7468        })
 7469    }
 7470
 7471    fn hide_context_menu(
 7472        &mut self,
 7473        window: &mut Window,
 7474        cx: &mut Context<Self>,
 7475    ) -> Option<CodeContextMenu> {
 7476        cx.notify();
 7477        self.completion_tasks.clear();
 7478        let context_menu = self.context_menu.borrow_mut().take();
 7479        self.stale_inline_completion_in_menu.take();
 7480        self.update_visible_inline_completion(window, cx);
 7481        context_menu
 7482    }
 7483
 7484    fn show_snippet_choices(
 7485        &mut self,
 7486        choices: &Vec<String>,
 7487        selection: Range<Anchor>,
 7488        cx: &mut Context<Self>,
 7489    ) {
 7490        if selection.start.buffer_id.is_none() {
 7491            return;
 7492        }
 7493        let buffer_id = selection.start.buffer_id.unwrap();
 7494        let buffer = self.buffer().read(cx).buffer(buffer_id);
 7495        let id = post_inc(&mut self.next_completion_id);
 7496
 7497        if let Some(buffer) = buffer {
 7498            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 7499                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 7500            ));
 7501        }
 7502    }
 7503
 7504    pub fn insert_snippet(
 7505        &mut self,
 7506        insertion_ranges: &[Range<usize>],
 7507        snippet: Snippet,
 7508        window: &mut Window,
 7509        cx: &mut Context<Self>,
 7510    ) -> Result<()> {
 7511        struct Tabstop<T> {
 7512            is_end_tabstop: bool,
 7513            ranges: Vec<Range<T>>,
 7514            choices: Option<Vec<String>>,
 7515        }
 7516
 7517        let tabstops = self.buffer.update(cx, |buffer, cx| {
 7518            let snippet_text: Arc<str> = snippet.text.clone().into();
 7519            let edits = insertion_ranges
 7520                .iter()
 7521                .cloned()
 7522                .map(|range| (range, snippet_text.clone()));
 7523            buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
 7524
 7525            let snapshot = &*buffer.read(cx);
 7526            let snippet = &snippet;
 7527            snippet
 7528                .tabstops
 7529                .iter()
 7530                .map(|tabstop| {
 7531                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 7532                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 7533                    });
 7534                    let mut tabstop_ranges = tabstop
 7535                        .ranges
 7536                        .iter()
 7537                        .flat_map(|tabstop_range| {
 7538                            let mut delta = 0_isize;
 7539                            insertion_ranges.iter().map(move |insertion_range| {
 7540                                let insertion_start = insertion_range.start as isize + delta;
 7541                                delta +=
 7542                                    snippet.text.len() as isize - insertion_range.len() as isize;
 7543
 7544                                let start = ((insertion_start + tabstop_range.start) as usize)
 7545                                    .min(snapshot.len());
 7546                                let end = ((insertion_start + tabstop_range.end) as usize)
 7547                                    .min(snapshot.len());
 7548                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 7549                            })
 7550                        })
 7551                        .collect::<Vec<_>>();
 7552                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 7553
 7554                    Tabstop {
 7555                        is_end_tabstop,
 7556                        ranges: tabstop_ranges,
 7557                        choices: tabstop.choices.clone(),
 7558                    }
 7559                })
 7560                .collect::<Vec<_>>()
 7561        });
 7562        if let Some(tabstop) = tabstops.first() {
 7563            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7564                s.select_ranges(tabstop.ranges.iter().cloned());
 7565            });
 7566
 7567            if let Some(choices) = &tabstop.choices {
 7568                if let Some(selection) = tabstop.ranges.first() {
 7569                    self.show_snippet_choices(choices, selection.clone(), cx)
 7570                }
 7571            }
 7572
 7573            // If we're already at the last tabstop and it's at the end of the snippet,
 7574            // we're done, we don't need to keep the state around.
 7575            if !tabstop.is_end_tabstop {
 7576                let choices = tabstops
 7577                    .iter()
 7578                    .map(|tabstop| tabstop.choices.clone())
 7579                    .collect();
 7580
 7581                let ranges = tabstops
 7582                    .into_iter()
 7583                    .map(|tabstop| tabstop.ranges)
 7584                    .collect::<Vec<_>>();
 7585
 7586                self.snippet_stack.push(SnippetState {
 7587                    active_index: 0,
 7588                    ranges,
 7589                    choices,
 7590                });
 7591            }
 7592
 7593            // Check whether the just-entered snippet ends with an auto-closable bracket.
 7594            if self.autoclose_regions.is_empty() {
 7595                let snapshot = self.buffer.read(cx).snapshot(cx);
 7596                for selection in &mut self.selections.all::<Point>(cx) {
 7597                    let selection_head = selection.head();
 7598                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 7599                        continue;
 7600                    };
 7601
 7602                    let mut bracket_pair = None;
 7603                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 7604                    let prev_chars = snapshot
 7605                        .reversed_chars_at(selection_head)
 7606                        .collect::<String>();
 7607                    for (pair, enabled) in scope.brackets() {
 7608                        if enabled
 7609                            && pair.close
 7610                            && prev_chars.starts_with(pair.start.as_str())
 7611                            && next_chars.starts_with(pair.end.as_str())
 7612                        {
 7613                            bracket_pair = Some(pair.clone());
 7614                            break;
 7615                        }
 7616                    }
 7617                    if let Some(pair) = bracket_pair {
 7618                        let start = snapshot.anchor_after(selection_head);
 7619                        let end = snapshot.anchor_after(selection_head);
 7620                        self.autoclose_regions.push(AutocloseRegion {
 7621                            selection_id: selection.id,
 7622                            range: start..end,
 7623                            pair,
 7624                        });
 7625                    }
 7626                }
 7627            }
 7628        }
 7629        Ok(())
 7630    }
 7631
 7632    pub fn move_to_next_snippet_tabstop(
 7633        &mut self,
 7634        window: &mut Window,
 7635        cx: &mut Context<Self>,
 7636    ) -> bool {
 7637        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 7638    }
 7639
 7640    pub fn move_to_prev_snippet_tabstop(
 7641        &mut self,
 7642        window: &mut Window,
 7643        cx: &mut Context<Self>,
 7644    ) -> bool {
 7645        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 7646    }
 7647
 7648    pub fn move_to_snippet_tabstop(
 7649        &mut self,
 7650        bias: Bias,
 7651        window: &mut Window,
 7652        cx: &mut Context<Self>,
 7653    ) -> bool {
 7654        if let Some(mut snippet) = self.snippet_stack.pop() {
 7655            match bias {
 7656                Bias::Left => {
 7657                    if snippet.active_index > 0 {
 7658                        snippet.active_index -= 1;
 7659                    } else {
 7660                        self.snippet_stack.push(snippet);
 7661                        return false;
 7662                    }
 7663                }
 7664                Bias::Right => {
 7665                    if snippet.active_index + 1 < snippet.ranges.len() {
 7666                        snippet.active_index += 1;
 7667                    } else {
 7668                        self.snippet_stack.push(snippet);
 7669                        return false;
 7670                    }
 7671                }
 7672            }
 7673            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 7674                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7675                    s.select_anchor_ranges(current_ranges.iter().cloned())
 7676                });
 7677
 7678                if let Some(choices) = &snippet.choices[snippet.active_index] {
 7679                    if let Some(selection) = current_ranges.first() {
 7680                        self.show_snippet_choices(&choices, selection.clone(), cx);
 7681                    }
 7682                }
 7683
 7684                // If snippet state is not at the last tabstop, push it back on the stack
 7685                if snippet.active_index + 1 < snippet.ranges.len() {
 7686                    self.snippet_stack.push(snippet);
 7687                }
 7688                return true;
 7689            }
 7690        }
 7691
 7692        false
 7693    }
 7694
 7695    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 7696        self.transact(window, cx, |this, window, cx| {
 7697            this.select_all(&SelectAll, window, cx);
 7698            this.insert("", window, cx);
 7699        });
 7700    }
 7701
 7702    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 7703        self.transact(window, cx, |this, window, cx| {
 7704            this.select_autoclose_pair(window, cx);
 7705            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 7706            if !this.linked_edit_ranges.is_empty() {
 7707                let selections = this.selections.all::<MultiBufferPoint>(cx);
 7708                let snapshot = this.buffer.read(cx).snapshot(cx);
 7709
 7710                for selection in selections.iter() {
 7711                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 7712                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 7713                    if selection_start.buffer_id != selection_end.buffer_id {
 7714                        continue;
 7715                    }
 7716                    if let Some(ranges) =
 7717                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 7718                    {
 7719                        for (buffer, entries) in ranges {
 7720                            linked_ranges.entry(buffer).or_default().extend(entries);
 7721                        }
 7722                    }
 7723                }
 7724            }
 7725
 7726            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 7727            if !this.selections.line_mode {
 7728                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 7729                for selection in &mut selections {
 7730                    if selection.is_empty() {
 7731                        let old_head = selection.head();
 7732                        let mut new_head =
 7733                            movement::left(&display_map, old_head.to_display_point(&display_map))
 7734                                .to_point(&display_map);
 7735                        if let Some((buffer, line_buffer_range)) = display_map
 7736                            .buffer_snapshot
 7737                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 7738                        {
 7739                            let indent_size =
 7740                                buffer.indent_size_for_line(line_buffer_range.start.row);
 7741                            let indent_len = match indent_size.kind {
 7742                                IndentKind::Space => {
 7743                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 7744                                }
 7745                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 7746                            };
 7747                            if old_head.column <= indent_size.len && old_head.column > 0 {
 7748                                let indent_len = indent_len.get();
 7749                                new_head = cmp::min(
 7750                                    new_head,
 7751                                    MultiBufferPoint::new(
 7752                                        old_head.row,
 7753                                        ((old_head.column - 1) / indent_len) * indent_len,
 7754                                    ),
 7755                                );
 7756                            }
 7757                        }
 7758
 7759                        selection.set_head(new_head, SelectionGoal::None);
 7760                    }
 7761                }
 7762            }
 7763
 7764            this.signature_help_state.set_backspace_pressed(true);
 7765            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7766                s.select(selections)
 7767            });
 7768            this.insert("", window, cx);
 7769            let empty_str: Arc<str> = Arc::from("");
 7770            for (buffer, edits) in linked_ranges {
 7771                let snapshot = buffer.read(cx).snapshot();
 7772                use text::ToPoint as TP;
 7773
 7774                let edits = edits
 7775                    .into_iter()
 7776                    .map(|range| {
 7777                        let end_point = TP::to_point(&range.end, &snapshot);
 7778                        let mut start_point = TP::to_point(&range.start, &snapshot);
 7779
 7780                        if end_point == start_point {
 7781                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 7782                                .saturating_sub(1);
 7783                            start_point =
 7784                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 7785                        };
 7786
 7787                        (start_point..end_point, empty_str.clone())
 7788                    })
 7789                    .sorted_by_key(|(range, _)| range.start)
 7790                    .collect::<Vec<_>>();
 7791                buffer.update(cx, |this, cx| {
 7792                    this.edit(edits, None, cx);
 7793                })
 7794            }
 7795            this.refresh_inline_completion(true, false, window, cx);
 7796            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 7797        });
 7798    }
 7799
 7800    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 7801        self.transact(window, cx, |this, window, cx| {
 7802            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7803                let line_mode = s.line_mode;
 7804                s.move_with(|map, selection| {
 7805                    if selection.is_empty() && !line_mode {
 7806                        let cursor = movement::right(map, selection.head());
 7807                        selection.end = cursor;
 7808                        selection.reversed = true;
 7809                        selection.goal = SelectionGoal::None;
 7810                    }
 7811                })
 7812            });
 7813            this.insert("", window, cx);
 7814            this.refresh_inline_completion(true, false, window, cx);
 7815        });
 7816    }
 7817
 7818    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 7819        if self.move_to_prev_snippet_tabstop(window, cx) {
 7820            return;
 7821        }
 7822
 7823        self.outdent(&Outdent, window, cx);
 7824    }
 7825
 7826    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 7827        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 7828            return;
 7829        }
 7830
 7831        let mut selections = self.selections.all_adjusted(cx);
 7832        let buffer = self.buffer.read(cx);
 7833        let snapshot = buffer.snapshot(cx);
 7834        let rows_iter = selections.iter().map(|s| s.head().row);
 7835        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 7836
 7837        let mut edits = Vec::new();
 7838        let mut prev_edited_row = 0;
 7839        let mut row_delta = 0;
 7840        for selection in &mut selections {
 7841            if selection.start.row != prev_edited_row {
 7842                row_delta = 0;
 7843            }
 7844            prev_edited_row = selection.end.row;
 7845
 7846            // If the selection is non-empty, then increase the indentation of the selected lines.
 7847            if !selection.is_empty() {
 7848                row_delta =
 7849                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7850                continue;
 7851            }
 7852
 7853            // If the selection is empty and the cursor is in the leading whitespace before the
 7854            // suggested indentation, then auto-indent the line.
 7855            let cursor = selection.head();
 7856            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 7857            if let Some(suggested_indent) =
 7858                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 7859            {
 7860                if cursor.column < suggested_indent.len
 7861                    && cursor.column <= current_indent.len
 7862                    && current_indent.len <= suggested_indent.len
 7863                {
 7864                    selection.start = Point::new(cursor.row, suggested_indent.len);
 7865                    selection.end = selection.start;
 7866                    if row_delta == 0 {
 7867                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 7868                            cursor.row,
 7869                            current_indent,
 7870                            suggested_indent,
 7871                        ));
 7872                        row_delta = suggested_indent.len - current_indent.len;
 7873                    }
 7874                    continue;
 7875                }
 7876            }
 7877
 7878            // Otherwise, insert a hard or soft tab.
 7879            let settings = buffer.language_settings_at(cursor, cx);
 7880            let tab_size = if settings.hard_tabs {
 7881                IndentSize::tab()
 7882            } else {
 7883                let tab_size = settings.tab_size.get();
 7884                let char_column = snapshot
 7885                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 7886                    .flat_map(str::chars)
 7887                    .count()
 7888                    + row_delta as usize;
 7889                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 7890                IndentSize::spaces(chars_to_next_tab_stop)
 7891            };
 7892            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 7893            selection.end = selection.start;
 7894            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 7895            row_delta += tab_size.len;
 7896        }
 7897
 7898        self.transact(window, cx, |this, window, cx| {
 7899            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7900            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7901                s.select(selections)
 7902            });
 7903            this.refresh_inline_completion(true, false, window, cx);
 7904        });
 7905    }
 7906
 7907    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 7908        if self.read_only(cx) {
 7909            return;
 7910        }
 7911        let mut selections = self.selections.all::<Point>(cx);
 7912        let mut prev_edited_row = 0;
 7913        let mut row_delta = 0;
 7914        let mut edits = Vec::new();
 7915        let buffer = self.buffer.read(cx);
 7916        let snapshot = buffer.snapshot(cx);
 7917        for selection in &mut selections {
 7918            if selection.start.row != prev_edited_row {
 7919                row_delta = 0;
 7920            }
 7921            prev_edited_row = selection.end.row;
 7922
 7923            row_delta =
 7924                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7925        }
 7926
 7927        self.transact(window, cx, |this, window, cx| {
 7928            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7929            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7930                s.select(selections)
 7931            });
 7932        });
 7933    }
 7934
 7935    fn indent_selection(
 7936        buffer: &MultiBuffer,
 7937        snapshot: &MultiBufferSnapshot,
 7938        selection: &mut Selection<Point>,
 7939        edits: &mut Vec<(Range<Point>, String)>,
 7940        delta_for_start_row: u32,
 7941        cx: &App,
 7942    ) -> u32 {
 7943        let settings = buffer.language_settings_at(selection.start, cx);
 7944        let tab_size = settings.tab_size.get();
 7945        let indent_kind = if settings.hard_tabs {
 7946            IndentKind::Tab
 7947        } else {
 7948            IndentKind::Space
 7949        };
 7950        let mut start_row = selection.start.row;
 7951        let mut end_row = selection.end.row + 1;
 7952
 7953        // If a selection ends at the beginning of a line, don't indent
 7954        // that last line.
 7955        if selection.end.column == 0 && selection.end.row > selection.start.row {
 7956            end_row -= 1;
 7957        }
 7958
 7959        // Avoid re-indenting a row that has already been indented by a
 7960        // previous selection, but still update this selection's column
 7961        // to reflect that indentation.
 7962        if delta_for_start_row > 0 {
 7963            start_row += 1;
 7964            selection.start.column += delta_for_start_row;
 7965            if selection.end.row == selection.start.row {
 7966                selection.end.column += delta_for_start_row;
 7967            }
 7968        }
 7969
 7970        let mut delta_for_end_row = 0;
 7971        let has_multiple_rows = start_row + 1 != end_row;
 7972        for row in start_row..end_row {
 7973            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 7974            let indent_delta = match (current_indent.kind, indent_kind) {
 7975                (IndentKind::Space, IndentKind::Space) => {
 7976                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 7977                    IndentSize::spaces(columns_to_next_tab_stop)
 7978                }
 7979                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 7980                (_, IndentKind::Tab) => IndentSize::tab(),
 7981            };
 7982
 7983            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 7984                0
 7985            } else {
 7986                selection.start.column
 7987            };
 7988            let row_start = Point::new(row, start);
 7989            edits.push((
 7990                row_start..row_start,
 7991                indent_delta.chars().collect::<String>(),
 7992            ));
 7993
 7994            // Update this selection's endpoints to reflect the indentation.
 7995            if row == selection.start.row {
 7996                selection.start.column += indent_delta.len;
 7997            }
 7998            if row == selection.end.row {
 7999                selection.end.column += indent_delta.len;
 8000                delta_for_end_row = indent_delta.len;
 8001            }
 8002        }
 8003
 8004        if selection.start.row == selection.end.row {
 8005            delta_for_start_row + delta_for_end_row
 8006        } else {
 8007            delta_for_end_row
 8008        }
 8009    }
 8010
 8011    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 8012        if self.read_only(cx) {
 8013            return;
 8014        }
 8015        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8016        let selections = self.selections.all::<Point>(cx);
 8017        let mut deletion_ranges = Vec::new();
 8018        let mut last_outdent = None;
 8019        {
 8020            let buffer = self.buffer.read(cx);
 8021            let snapshot = buffer.snapshot(cx);
 8022            for selection in &selections {
 8023                let settings = buffer.language_settings_at(selection.start, cx);
 8024                let tab_size = settings.tab_size.get();
 8025                let mut rows = selection.spanned_rows(false, &display_map);
 8026
 8027                // Avoid re-outdenting a row that has already been outdented by a
 8028                // previous selection.
 8029                if let Some(last_row) = last_outdent {
 8030                    if last_row == rows.start {
 8031                        rows.start = rows.start.next_row();
 8032                    }
 8033                }
 8034                let has_multiple_rows = rows.len() > 1;
 8035                for row in rows.iter_rows() {
 8036                    let indent_size = snapshot.indent_size_for_line(row);
 8037                    if indent_size.len > 0 {
 8038                        let deletion_len = match indent_size.kind {
 8039                            IndentKind::Space => {
 8040                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 8041                                if columns_to_prev_tab_stop == 0 {
 8042                                    tab_size
 8043                                } else {
 8044                                    columns_to_prev_tab_stop
 8045                                }
 8046                            }
 8047                            IndentKind::Tab => 1,
 8048                        };
 8049                        let start = if has_multiple_rows
 8050                            || deletion_len > selection.start.column
 8051                            || indent_size.len < selection.start.column
 8052                        {
 8053                            0
 8054                        } else {
 8055                            selection.start.column - deletion_len
 8056                        };
 8057                        deletion_ranges.push(
 8058                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 8059                        );
 8060                        last_outdent = Some(row);
 8061                    }
 8062                }
 8063            }
 8064        }
 8065
 8066        self.transact(window, cx, |this, window, cx| {
 8067            this.buffer.update(cx, |buffer, cx| {
 8068                let empty_str: Arc<str> = Arc::default();
 8069                buffer.edit(
 8070                    deletion_ranges
 8071                        .into_iter()
 8072                        .map(|range| (range, empty_str.clone())),
 8073                    None,
 8074                    cx,
 8075                );
 8076            });
 8077            let selections = this.selections.all::<usize>(cx);
 8078            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8079                s.select(selections)
 8080            });
 8081        });
 8082    }
 8083
 8084    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 8085        if self.read_only(cx) {
 8086            return;
 8087        }
 8088        let selections = self
 8089            .selections
 8090            .all::<usize>(cx)
 8091            .into_iter()
 8092            .map(|s| s.range());
 8093
 8094        self.transact(window, cx, |this, window, cx| {
 8095            this.buffer.update(cx, |buffer, cx| {
 8096                buffer.autoindent_ranges(selections, cx);
 8097            });
 8098            let selections = this.selections.all::<usize>(cx);
 8099            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8100                s.select(selections)
 8101            });
 8102        });
 8103    }
 8104
 8105    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 8106        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8107        let selections = self.selections.all::<Point>(cx);
 8108
 8109        let mut new_cursors = Vec::new();
 8110        let mut edit_ranges = Vec::new();
 8111        let mut selections = selections.iter().peekable();
 8112        while let Some(selection) = selections.next() {
 8113            let mut rows = selection.spanned_rows(false, &display_map);
 8114            let goal_display_column = selection.head().to_display_point(&display_map).column();
 8115
 8116            // Accumulate contiguous regions of rows that we want to delete.
 8117            while let Some(next_selection) = selections.peek() {
 8118                let next_rows = next_selection.spanned_rows(false, &display_map);
 8119                if next_rows.start <= rows.end {
 8120                    rows.end = next_rows.end;
 8121                    selections.next().unwrap();
 8122                } else {
 8123                    break;
 8124                }
 8125            }
 8126
 8127            let buffer = &display_map.buffer_snapshot;
 8128            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 8129            let edit_end;
 8130            let cursor_buffer_row;
 8131            if buffer.max_point().row >= rows.end.0 {
 8132                // If there's a line after the range, delete the \n from the end of the row range
 8133                // and position the cursor on the next line.
 8134                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 8135                cursor_buffer_row = rows.end;
 8136            } else {
 8137                // If there isn't a line after the range, delete the \n from the line before the
 8138                // start of the row range and position the cursor there.
 8139                edit_start = edit_start.saturating_sub(1);
 8140                edit_end = buffer.len();
 8141                cursor_buffer_row = rows.start.previous_row();
 8142            }
 8143
 8144            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 8145            *cursor.column_mut() =
 8146                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 8147
 8148            new_cursors.push((
 8149                selection.id,
 8150                buffer.anchor_after(cursor.to_point(&display_map)),
 8151            ));
 8152            edit_ranges.push(edit_start..edit_end);
 8153        }
 8154
 8155        self.transact(window, cx, |this, window, cx| {
 8156            let buffer = this.buffer.update(cx, |buffer, cx| {
 8157                let empty_str: Arc<str> = Arc::default();
 8158                buffer.edit(
 8159                    edit_ranges
 8160                        .into_iter()
 8161                        .map(|range| (range, empty_str.clone())),
 8162                    None,
 8163                    cx,
 8164                );
 8165                buffer.snapshot(cx)
 8166            });
 8167            let new_selections = new_cursors
 8168                .into_iter()
 8169                .map(|(id, cursor)| {
 8170                    let cursor = cursor.to_point(&buffer);
 8171                    Selection {
 8172                        id,
 8173                        start: cursor,
 8174                        end: cursor,
 8175                        reversed: false,
 8176                        goal: SelectionGoal::None,
 8177                    }
 8178                })
 8179                .collect();
 8180
 8181            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8182                s.select(new_selections);
 8183            });
 8184        });
 8185    }
 8186
 8187    pub fn join_lines_impl(
 8188        &mut self,
 8189        insert_whitespace: bool,
 8190        window: &mut Window,
 8191        cx: &mut Context<Self>,
 8192    ) {
 8193        if self.read_only(cx) {
 8194            return;
 8195        }
 8196        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 8197        for selection in self.selections.all::<Point>(cx) {
 8198            let start = MultiBufferRow(selection.start.row);
 8199            // Treat single line selections as if they include the next line. Otherwise this action
 8200            // would do nothing for single line selections individual cursors.
 8201            let end = if selection.start.row == selection.end.row {
 8202                MultiBufferRow(selection.start.row + 1)
 8203            } else {
 8204                MultiBufferRow(selection.end.row)
 8205            };
 8206
 8207            if let Some(last_row_range) = row_ranges.last_mut() {
 8208                if start <= last_row_range.end {
 8209                    last_row_range.end = end;
 8210                    continue;
 8211                }
 8212            }
 8213            row_ranges.push(start..end);
 8214        }
 8215
 8216        let snapshot = self.buffer.read(cx).snapshot(cx);
 8217        let mut cursor_positions = Vec::new();
 8218        for row_range in &row_ranges {
 8219            let anchor = snapshot.anchor_before(Point::new(
 8220                row_range.end.previous_row().0,
 8221                snapshot.line_len(row_range.end.previous_row()),
 8222            ));
 8223            cursor_positions.push(anchor..anchor);
 8224        }
 8225
 8226        self.transact(window, cx, |this, window, cx| {
 8227            for row_range in row_ranges.into_iter().rev() {
 8228                for row in row_range.iter_rows().rev() {
 8229                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 8230                    let next_line_row = row.next_row();
 8231                    let indent = snapshot.indent_size_for_line(next_line_row);
 8232                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 8233
 8234                    let replace =
 8235                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 8236                            " "
 8237                        } else {
 8238                            ""
 8239                        };
 8240
 8241                    this.buffer.update(cx, |buffer, cx| {
 8242                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 8243                    });
 8244                }
 8245            }
 8246
 8247            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8248                s.select_anchor_ranges(cursor_positions)
 8249            });
 8250        });
 8251    }
 8252
 8253    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 8254        self.join_lines_impl(true, window, cx);
 8255    }
 8256
 8257    pub fn sort_lines_case_sensitive(
 8258        &mut self,
 8259        _: &SortLinesCaseSensitive,
 8260        window: &mut Window,
 8261        cx: &mut Context<Self>,
 8262    ) {
 8263        self.manipulate_lines(window, cx, |lines| lines.sort())
 8264    }
 8265
 8266    pub fn sort_lines_case_insensitive(
 8267        &mut self,
 8268        _: &SortLinesCaseInsensitive,
 8269        window: &mut Window,
 8270        cx: &mut Context<Self>,
 8271    ) {
 8272        self.manipulate_lines(window, cx, |lines| {
 8273            lines.sort_by_key(|line| line.to_lowercase())
 8274        })
 8275    }
 8276
 8277    pub fn unique_lines_case_insensitive(
 8278        &mut self,
 8279        _: &UniqueLinesCaseInsensitive,
 8280        window: &mut Window,
 8281        cx: &mut Context<Self>,
 8282    ) {
 8283        self.manipulate_lines(window, cx, |lines| {
 8284            let mut seen = HashSet::default();
 8285            lines.retain(|line| seen.insert(line.to_lowercase()));
 8286        })
 8287    }
 8288
 8289    pub fn unique_lines_case_sensitive(
 8290        &mut self,
 8291        _: &UniqueLinesCaseSensitive,
 8292        window: &mut Window,
 8293        cx: &mut Context<Self>,
 8294    ) {
 8295        self.manipulate_lines(window, cx, |lines| {
 8296            let mut seen = HashSet::default();
 8297            lines.retain(|line| seen.insert(*line));
 8298        })
 8299    }
 8300
 8301    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 8302        let Some(project) = self.project.clone() else {
 8303            return;
 8304        };
 8305        self.reload(project, window, cx)
 8306            .detach_and_notify_err(window, cx);
 8307    }
 8308
 8309    pub fn restore_file(
 8310        &mut self,
 8311        _: &::git::RestoreFile,
 8312        window: &mut Window,
 8313        cx: &mut Context<Self>,
 8314    ) {
 8315        let mut buffer_ids = HashSet::default();
 8316        let snapshot = self.buffer().read(cx).snapshot(cx);
 8317        for selection in self.selections.all::<usize>(cx) {
 8318            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 8319        }
 8320
 8321        let buffer = self.buffer().read(cx);
 8322        let ranges = buffer_ids
 8323            .into_iter()
 8324            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 8325            .collect::<Vec<_>>();
 8326
 8327        self.restore_hunks_in_ranges(ranges, window, cx);
 8328    }
 8329
 8330    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 8331        let selections = self
 8332            .selections
 8333            .all(cx)
 8334            .into_iter()
 8335            .map(|s| s.range())
 8336            .collect();
 8337        self.restore_hunks_in_ranges(selections, window, cx);
 8338    }
 8339
 8340    fn restore_hunks_in_ranges(
 8341        &mut self,
 8342        ranges: Vec<Range<Point>>,
 8343        window: &mut Window,
 8344        cx: &mut Context<Editor>,
 8345    ) {
 8346        let mut revert_changes = HashMap::default();
 8347        let chunk_by = self
 8348            .snapshot(window, cx)
 8349            .hunks_for_ranges(ranges)
 8350            .into_iter()
 8351            .chunk_by(|hunk| hunk.buffer_id);
 8352        for (buffer_id, hunks) in &chunk_by {
 8353            let hunks = hunks.collect::<Vec<_>>();
 8354            for hunk in &hunks {
 8355                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 8356            }
 8357            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
 8358        }
 8359        drop(chunk_by);
 8360        if !revert_changes.is_empty() {
 8361            self.transact(window, cx, |editor, window, cx| {
 8362                editor.restore(revert_changes, window, cx);
 8363            });
 8364        }
 8365    }
 8366
 8367    pub fn open_active_item_in_terminal(
 8368        &mut self,
 8369        _: &OpenInTerminal,
 8370        window: &mut Window,
 8371        cx: &mut Context<Self>,
 8372    ) {
 8373        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 8374            let project_path = buffer.read(cx).project_path(cx)?;
 8375            let project = self.project.as_ref()?.read(cx);
 8376            let entry = project.entry_for_path(&project_path, cx)?;
 8377            let parent = match &entry.canonical_path {
 8378                Some(canonical_path) => canonical_path.to_path_buf(),
 8379                None => project.absolute_path(&project_path, cx)?,
 8380            }
 8381            .parent()?
 8382            .to_path_buf();
 8383            Some(parent)
 8384        }) {
 8385            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 8386        }
 8387    }
 8388
 8389    fn set_breakpoint_context_menu(
 8390        &mut self,
 8391        row: DisplayRow,
 8392        position: Option<Anchor>,
 8393        kind: Arc<BreakpointKind>,
 8394        clicked_point: gpui::Point<Pixels>,
 8395        window: &mut Window,
 8396        cx: &mut Context<Self>,
 8397    ) {
 8398        if !cx.has_flag::<Debugger>() {
 8399            return;
 8400        }
 8401        let source = self
 8402            .buffer
 8403            .read(cx)
 8404            .snapshot(cx)
 8405            .anchor_before(Point::new(row.0, 0u32));
 8406
 8407        let context_menu =
 8408            self.breakpoint_context_menu(position.unwrap_or(source), kind, window, cx);
 8409
 8410        self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
 8411            self,
 8412            source,
 8413            clicked_point,
 8414            context_menu,
 8415            window,
 8416            cx,
 8417        );
 8418    }
 8419
 8420    fn add_edit_breakpoint_block(
 8421        &mut self,
 8422        anchor: Anchor,
 8423        kind: &BreakpointKind,
 8424        window: &mut Window,
 8425        cx: &mut Context<Self>,
 8426    ) {
 8427        let weak_editor = cx.weak_entity();
 8428        let bp_prompt =
 8429            cx.new(|cx| BreakpointPromptEditor::new(weak_editor, anchor, kind.clone(), window, cx));
 8430
 8431        let height = bp_prompt.update(cx, |this, cx| {
 8432            this.prompt
 8433                .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
 8434        });
 8435        let cloned_prompt = bp_prompt.clone();
 8436        let blocks = vec![BlockProperties {
 8437            style: BlockStyle::Sticky,
 8438            placement: BlockPlacement::Above(anchor),
 8439            height,
 8440            render: Arc::new(move |cx| {
 8441                *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
 8442                cloned_prompt.clone().into_any_element()
 8443            }),
 8444            priority: 0,
 8445        }];
 8446
 8447        let focus_handle = bp_prompt.focus_handle(cx);
 8448        window.focus(&focus_handle);
 8449
 8450        let block_ids = self.insert_blocks(blocks, None, cx);
 8451        bp_prompt.update(cx, |prompt, _| {
 8452            prompt.add_block_ids(block_ids);
 8453        });
 8454    }
 8455
 8456    pub(crate) fn breakpoint_at_cursor_head(
 8457        &self,
 8458        window: &mut Window,
 8459        cx: &mut Context<Self>,
 8460    ) -> Option<(Anchor, Breakpoint)> {
 8461        let cursor_position: Point = self.selections.newest(cx).head();
 8462        let snapshot = self.snapshot(window, cx);
 8463        // We Set the column position to zero so this function interacts correctly
 8464        // between calls by clicking on the gutter & using an action to toggle a
 8465        // breakpoint. Otherwise, toggling a breakpoint through an action wouldn't
 8466        // untoggle a breakpoint that was added through clicking on the gutter
 8467        let cursor_position = snapshot
 8468            .display_snapshot
 8469            .buffer_snapshot
 8470            .anchor_before(Point::new(cursor_position.row, 0));
 8471
 8472        let project = self.project.clone();
 8473
 8474        let buffer_id = cursor_position.text_anchor.buffer_id?;
 8475        let enclosing_excerpt = snapshot
 8476            .buffer_snapshot
 8477            .excerpt_ids_for_range(cursor_position..cursor_position)
 8478            .next()?;
 8479        let buffer = project?.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
 8480        let buffer_snapshot = buffer.read(cx).snapshot();
 8481
 8482        let row = buffer_snapshot
 8483            .summary_for_anchor::<text::PointUtf16>(&cursor_position.text_anchor)
 8484            .row;
 8485
 8486        let bp = self
 8487            .breakpoint_store
 8488            .as_ref()?
 8489            .read_with(cx, |breakpoint_store, cx| {
 8490                breakpoint_store
 8491                    .breakpoints(
 8492                        &buffer,
 8493                        Some(cursor_position.text_anchor..(text::Anchor::MAX)),
 8494                        buffer_snapshot.clone(),
 8495                        cx,
 8496                    )
 8497                    .next()
 8498                    .and_then(move |(anchor, bp)| {
 8499                        let breakpoint_row = buffer_snapshot
 8500                            .summary_for_anchor::<text::PointUtf16>(anchor)
 8501                            .row;
 8502
 8503                        if breakpoint_row == row {
 8504                            snapshot
 8505                                .buffer_snapshot
 8506                                .anchor_in_excerpt(enclosing_excerpt, *anchor)
 8507                                .map(|anchor| (anchor, bp.clone()))
 8508                        } else {
 8509                            None
 8510                        }
 8511                    })
 8512            });
 8513        bp
 8514    }
 8515
 8516    pub fn edit_log_breakpoint(
 8517        &mut self,
 8518        _: &EditLogBreakpoint,
 8519        window: &mut Window,
 8520        cx: &mut Context<Self>,
 8521    ) {
 8522        let (anchor, bp) = self
 8523            .breakpoint_at_cursor_head(window, cx)
 8524            .unwrap_or_else(|| {
 8525                let cursor_position: Point = self.selections.newest(cx).head();
 8526
 8527                let breakpoint_position = self
 8528                    .snapshot(window, cx)
 8529                    .display_snapshot
 8530                    .buffer_snapshot
 8531                    .anchor_before(Point::new(cursor_position.row, 0));
 8532
 8533                (
 8534                    breakpoint_position,
 8535                    Breakpoint {
 8536                        kind: BreakpointKind::Standard,
 8537                    },
 8538                )
 8539            });
 8540
 8541        self.add_edit_breakpoint_block(anchor, &bp.kind, window, cx);
 8542    }
 8543
 8544    pub fn toggle_breakpoint(
 8545        &mut self,
 8546        _: &crate::actions::ToggleBreakpoint,
 8547        window: &mut Window,
 8548        cx: &mut Context<Self>,
 8549    ) {
 8550        let edit_action = BreakpointEditAction::Toggle;
 8551
 8552        if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
 8553            self.edit_breakpoint_at_anchor(anchor, breakpoint.kind, edit_action, cx);
 8554        } else {
 8555            let cursor_position: Point = self.selections.newest(cx).head();
 8556
 8557            let breakpoint_position = self
 8558                .snapshot(window, cx)
 8559                .display_snapshot
 8560                .buffer_snapshot
 8561                .anchor_before(Point::new(cursor_position.row, 0));
 8562
 8563            self.edit_breakpoint_at_anchor(
 8564                breakpoint_position,
 8565                BreakpointKind::Standard,
 8566                edit_action,
 8567                cx,
 8568            );
 8569        }
 8570    }
 8571
 8572    pub fn edit_breakpoint_at_anchor(
 8573        &mut self,
 8574        breakpoint_position: Anchor,
 8575        kind: BreakpointKind,
 8576        edit_action: BreakpointEditAction,
 8577        cx: &mut Context<Self>,
 8578    ) {
 8579        let Some(breakpoint_store) = &self.breakpoint_store else {
 8580            return;
 8581        };
 8582
 8583        let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
 8584            if breakpoint_position == Anchor::min() {
 8585                self.buffer()
 8586                    .read(cx)
 8587                    .excerpt_buffer_ids()
 8588                    .into_iter()
 8589                    .next()
 8590            } else {
 8591                None
 8592            }
 8593        }) else {
 8594            return;
 8595        };
 8596
 8597        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
 8598            return;
 8599        };
 8600
 8601        breakpoint_store.update(cx, |breakpoint_store, cx| {
 8602            breakpoint_store.toggle_breakpoint(
 8603                buffer,
 8604                (breakpoint_position.text_anchor, Breakpoint { kind }),
 8605                edit_action,
 8606                cx,
 8607            );
 8608        });
 8609
 8610        cx.notify();
 8611    }
 8612
 8613    #[cfg(any(test, feature = "test-support"))]
 8614    pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
 8615        self.breakpoint_store.clone()
 8616    }
 8617
 8618    pub fn prepare_restore_change(
 8619        &self,
 8620        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 8621        hunk: &MultiBufferDiffHunk,
 8622        cx: &mut App,
 8623    ) -> Option<()> {
 8624        if hunk.is_created_file() {
 8625            return None;
 8626        }
 8627        let buffer = self.buffer.read(cx);
 8628        let diff = buffer.diff_for(hunk.buffer_id)?;
 8629        let buffer = buffer.buffer(hunk.buffer_id)?;
 8630        let buffer = buffer.read(cx);
 8631        let original_text = diff
 8632            .read(cx)
 8633            .base_text()
 8634            .as_rope()
 8635            .slice(hunk.diff_base_byte_range.clone());
 8636        let buffer_snapshot = buffer.snapshot();
 8637        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 8638        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 8639            probe
 8640                .0
 8641                .start
 8642                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 8643                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 8644        }) {
 8645            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 8646            Some(())
 8647        } else {
 8648            None
 8649        }
 8650    }
 8651
 8652    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 8653        self.manipulate_lines(window, cx, |lines| lines.reverse())
 8654    }
 8655
 8656    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 8657        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 8658    }
 8659
 8660    fn manipulate_lines<Fn>(
 8661        &mut self,
 8662        window: &mut Window,
 8663        cx: &mut Context<Self>,
 8664        mut callback: Fn,
 8665    ) where
 8666        Fn: FnMut(&mut Vec<&str>),
 8667    {
 8668        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8669        let buffer = self.buffer.read(cx).snapshot(cx);
 8670
 8671        let mut edits = Vec::new();
 8672
 8673        let selections = self.selections.all::<Point>(cx);
 8674        let mut selections = selections.iter().peekable();
 8675        let mut contiguous_row_selections = Vec::new();
 8676        let mut new_selections = Vec::new();
 8677        let mut added_lines = 0;
 8678        let mut removed_lines = 0;
 8679
 8680        while let Some(selection) = selections.next() {
 8681            let (start_row, end_row) = consume_contiguous_rows(
 8682                &mut contiguous_row_selections,
 8683                selection,
 8684                &display_map,
 8685                &mut selections,
 8686            );
 8687
 8688            let start_point = Point::new(start_row.0, 0);
 8689            let end_point = Point::new(
 8690                end_row.previous_row().0,
 8691                buffer.line_len(end_row.previous_row()),
 8692            );
 8693            let text = buffer
 8694                .text_for_range(start_point..end_point)
 8695                .collect::<String>();
 8696
 8697            let mut lines = text.split('\n').collect_vec();
 8698
 8699            let lines_before = lines.len();
 8700            callback(&mut lines);
 8701            let lines_after = lines.len();
 8702
 8703            edits.push((start_point..end_point, lines.join("\n")));
 8704
 8705            // Selections must change based on added and removed line count
 8706            let start_row =
 8707                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 8708            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 8709            new_selections.push(Selection {
 8710                id: selection.id,
 8711                start: start_row,
 8712                end: end_row,
 8713                goal: SelectionGoal::None,
 8714                reversed: selection.reversed,
 8715            });
 8716
 8717            if lines_after > lines_before {
 8718                added_lines += lines_after - lines_before;
 8719            } else if lines_before > lines_after {
 8720                removed_lines += lines_before - lines_after;
 8721            }
 8722        }
 8723
 8724        self.transact(window, cx, |this, window, cx| {
 8725            let buffer = this.buffer.update(cx, |buffer, cx| {
 8726                buffer.edit(edits, None, cx);
 8727                buffer.snapshot(cx)
 8728            });
 8729
 8730            // Recalculate offsets on newly edited buffer
 8731            let new_selections = new_selections
 8732                .iter()
 8733                .map(|s| {
 8734                    let start_point = Point::new(s.start.0, 0);
 8735                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 8736                    Selection {
 8737                        id: s.id,
 8738                        start: buffer.point_to_offset(start_point),
 8739                        end: buffer.point_to_offset(end_point),
 8740                        goal: s.goal,
 8741                        reversed: s.reversed,
 8742                    }
 8743                })
 8744                .collect();
 8745
 8746            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8747                s.select(new_selections);
 8748            });
 8749
 8750            this.request_autoscroll(Autoscroll::fit(), cx);
 8751        });
 8752    }
 8753
 8754    pub fn convert_to_upper_case(
 8755        &mut self,
 8756        _: &ConvertToUpperCase,
 8757        window: &mut Window,
 8758        cx: &mut Context<Self>,
 8759    ) {
 8760        self.manipulate_text(window, cx, |text| text.to_uppercase())
 8761    }
 8762
 8763    pub fn convert_to_lower_case(
 8764        &mut self,
 8765        _: &ConvertToLowerCase,
 8766        window: &mut Window,
 8767        cx: &mut Context<Self>,
 8768    ) {
 8769        self.manipulate_text(window, cx, |text| text.to_lowercase())
 8770    }
 8771
 8772    pub fn convert_to_title_case(
 8773        &mut self,
 8774        _: &ConvertToTitleCase,
 8775        window: &mut Window,
 8776        cx: &mut Context<Self>,
 8777    ) {
 8778        self.manipulate_text(window, cx, |text| {
 8779            text.split('\n')
 8780                .map(|line| line.to_case(Case::Title))
 8781                .join("\n")
 8782        })
 8783    }
 8784
 8785    pub fn convert_to_snake_case(
 8786        &mut self,
 8787        _: &ConvertToSnakeCase,
 8788        window: &mut Window,
 8789        cx: &mut Context<Self>,
 8790    ) {
 8791        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 8792    }
 8793
 8794    pub fn convert_to_kebab_case(
 8795        &mut self,
 8796        _: &ConvertToKebabCase,
 8797        window: &mut Window,
 8798        cx: &mut Context<Self>,
 8799    ) {
 8800        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 8801    }
 8802
 8803    pub fn convert_to_upper_camel_case(
 8804        &mut self,
 8805        _: &ConvertToUpperCamelCase,
 8806        window: &mut Window,
 8807        cx: &mut Context<Self>,
 8808    ) {
 8809        self.manipulate_text(window, cx, |text| {
 8810            text.split('\n')
 8811                .map(|line| line.to_case(Case::UpperCamel))
 8812                .join("\n")
 8813        })
 8814    }
 8815
 8816    pub fn convert_to_lower_camel_case(
 8817        &mut self,
 8818        _: &ConvertToLowerCamelCase,
 8819        window: &mut Window,
 8820        cx: &mut Context<Self>,
 8821    ) {
 8822        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 8823    }
 8824
 8825    pub fn convert_to_opposite_case(
 8826        &mut self,
 8827        _: &ConvertToOppositeCase,
 8828        window: &mut Window,
 8829        cx: &mut Context<Self>,
 8830    ) {
 8831        self.manipulate_text(window, cx, |text| {
 8832            text.chars()
 8833                .fold(String::with_capacity(text.len()), |mut t, c| {
 8834                    if c.is_uppercase() {
 8835                        t.extend(c.to_lowercase());
 8836                    } else {
 8837                        t.extend(c.to_uppercase());
 8838                    }
 8839                    t
 8840                })
 8841        })
 8842    }
 8843
 8844    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 8845    where
 8846        Fn: FnMut(&str) -> String,
 8847    {
 8848        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8849        let buffer = self.buffer.read(cx).snapshot(cx);
 8850
 8851        let mut new_selections = Vec::new();
 8852        let mut edits = Vec::new();
 8853        let mut selection_adjustment = 0i32;
 8854
 8855        for selection in self.selections.all::<usize>(cx) {
 8856            let selection_is_empty = selection.is_empty();
 8857
 8858            let (start, end) = if selection_is_empty {
 8859                let word_range = movement::surrounding_word(
 8860                    &display_map,
 8861                    selection.start.to_display_point(&display_map),
 8862                );
 8863                let start = word_range.start.to_offset(&display_map, Bias::Left);
 8864                let end = word_range.end.to_offset(&display_map, Bias::Left);
 8865                (start, end)
 8866            } else {
 8867                (selection.start, selection.end)
 8868            };
 8869
 8870            let text = buffer.text_for_range(start..end).collect::<String>();
 8871            let old_length = text.len() as i32;
 8872            let text = callback(&text);
 8873
 8874            new_selections.push(Selection {
 8875                start: (start as i32 - selection_adjustment) as usize,
 8876                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 8877                goal: SelectionGoal::None,
 8878                ..selection
 8879            });
 8880
 8881            selection_adjustment += old_length - text.len() as i32;
 8882
 8883            edits.push((start..end, text));
 8884        }
 8885
 8886        self.transact(window, cx, |this, window, cx| {
 8887            this.buffer.update(cx, |buffer, cx| {
 8888                buffer.edit(edits, None, cx);
 8889            });
 8890
 8891            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8892                s.select(new_selections);
 8893            });
 8894
 8895            this.request_autoscroll(Autoscroll::fit(), cx);
 8896        });
 8897    }
 8898
 8899    pub fn duplicate(
 8900        &mut self,
 8901        upwards: bool,
 8902        whole_lines: bool,
 8903        window: &mut Window,
 8904        cx: &mut Context<Self>,
 8905    ) {
 8906        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8907        let buffer = &display_map.buffer_snapshot;
 8908        let selections = self.selections.all::<Point>(cx);
 8909
 8910        let mut edits = Vec::new();
 8911        let mut selections_iter = selections.iter().peekable();
 8912        while let Some(selection) = selections_iter.next() {
 8913            let mut rows = selection.spanned_rows(false, &display_map);
 8914            // duplicate line-wise
 8915            if whole_lines || selection.start == selection.end {
 8916                // Avoid duplicating the same lines twice.
 8917                while let Some(next_selection) = selections_iter.peek() {
 8918                    let next_rows = next_selection.spanned_rows(false, &display_map);
 8919                    if next_rows.start < rows.end {
 8920                        rows.end = next_rows.end;
 8921                        selections_iter.next().unwrap();
 8922                    } else {
 8923                        break;
 8924                    }
 8925                }
 8926
 8927                // Copy the text from the selected row region and splice it either at the start
 8928                // or end of the region.
 8929                let start = Point::new(rows.start.0, 0);
 8930                let end = Point::new(
 8931                    rows.end.previous_row().0,
 8932                    buffer.line_len(rows.end.previous_row()),
 8933                );
 8934                let text = buffer
 8935                    .text_for_range(start..end)
 8936                    .chain(Some("\n"))
 8937                    .collect::<String>();
 8938                let insert_location = if upwards {
 8939                    Point::new(rows.end.0, 0)
 8940                } else {
 8941                    start
 8942                };
 8943                edits.push((insert_location..insert_location, text));
 8944            } else {
 8945                // duplicate character-wise
 8946                let start = selection.start;
 8947                let end = selection.end;
 8948                let text = buffer.text_for_range(start..end).collect::<String>();
 8949                edits.push((selection.end..selection.end, text));
 8950            }
 8951        }
 8952
 8953        self.transact(window, cx, |this, _, cx| {
 8954            this.buffer.update(cx, |buffer, cx| {
 8955                buffer.edit(edits, None, cx);
 8956            });
 8957
 8958            this.request_autoscroll(Autoscroll::fit(), cx);
 8959        });
 8960    }
 8961
 8962    pub fn duplicate_line_up(
 8963        &mut self,
 8964        _: &DuplicateLineUp,
 8965        window: &mut Window,
 8966        cx: &mut Context<Self>,
 8967    ) {
 8968        self.duplicate(true, true, window, cx);
 8969    }
 8970
 8971    pub fn duplicate_line_down(
 8972        &mut self,
 8973        _: &DuplicateLineDown,
 8974        window: &mut Window,
 8975        cx: &mut Context<Self>,
 8976    ) {
 8977        self.duplicate(false, true, window, cx);
 8978    }
 8979
 8980    pub fn duplicate_selection(
 8981        &mut self,
 8982        _: &DuplicateSelection,
 8983        window: &mut Window,
 8984        cx: &mut Context<Self>,
 8985    ) {
 8986        self.duplicate(false, false, window, cx);
 8987    }
 8988
 8989    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 8990        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8991        let buffer = self.buffer.read(cx).snapshot(cx);
 8992
 8993        let mut edits = Vec::new();
 8994        let mut unfold_ranges = Vec::new();
 8995        let mut refold_creases = Vec::new();
 8996
 8997        let selections = self.selections.all::<Point>(cx);
 8998        let mut selections = selections.iter().peekable();
 8999        let mut contiguous_row_selections = Vec::new();
 9000        let mut new_selections = Vec::new();
 9001
 9002        while let Some(selection) = selections.next() {
 9003            // Find all the selections that span a contiguous row range
 9004            let (start_row, end_row) = consume_contiguous_rows(
 9005                &mut contiguous_row_selections,
 9006                selection,
 9007                &display_map,
 9008                &mut selections,
 9009            );
 9010
 9011            // Move the text spanned by the row range to be before the line preceding the row range
 9012            if start_row.0 > 0 {
 9013                let range_to_move = Point::new(
 9014                    start_row.previous_row().0,
 9015                    buffer.line_len(start_row.previous_row()),
 9016                )
 9017                    ..Point::new(
 9018                        end_row.previous_row().0,
 9019                        buffer.line_len(end_row.previous_row()),
 9020                    );
 9021                let insertion_point = display_map
 9022                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 9023                    .0;
 9024
 9025                // Don't move lines across excerpts
 9026                if buffer
 9027                    .excerpt_containing(insertion_point..range_to_move.end)
 9028                    .is_some()
 9029                {
 9030                    let text = buffer
 9031                        .text_for_range(range_to_move.clone())
 9032                        .flat_map(|s| s.chars())
 9033                        .skip(1)
 9034                        .chain(['\n'])
 9035                        .collect::<String>();
 9036
 9037                    edits.push((
 9038                        buffer.anchor_after(range_to_move.start)
 9039                            ..buffer.anchor_before(range_to_move.end),
 9040                        String::new(),
 9041                    ));
 9042                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9043                    edits.push((insertion_anchor..insertion_anchor, text));
 9044
 9045                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 9046
 9047                    // Move selections up
 9048                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9049                        |mut selection| {
 9050                            selection.start.row -= row_delta;
 9051                            selection.end.row -= row_delta;
 9052                            selection
 9053                        },
 9054                    ));
 9055
 9056                    // Move folds up
 9057                    unfold_ranges.push(range_to_move.clone());
 9058                    for fold in display_map.folds_in_range(
 9059                        buffer.anchor_before(range_to_move.start)
 9060                            ..buffer.anchor_after(range_to_move.end),
 9061                    ) {
 9062                        let mut start = fold.range.start.to_point(&buffer);
 9063                        let mut end = fold.range.end.to_point(&buffer);
 9064                        start.row -= row_delta;
 9065                        end.row -= row_delta;
 9066                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9067                    }
 9068                }
 9069            }
 9070
 9071            // If we didn't move line(s), preserve the existing selections
 9072            new_selections.append(&mut contiguous_row_selections);
 9073        }
 9074
 9075        self.transact(window, cx, |this, window, cx| {
 9076            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9077            this.buffer.update(cx, |buffer, cx| {
 9078                for (range, text) in edits {
 9079                    buffer.edit([(range, text)], None, cx);
 9080                }
 9081            });
 9082            this.fold_creases(refold_creases, true, window, cx);
 9083            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9084                s.select(new_selections);
 9085            })
 9086        });
 9087    }
 9088
 9089    pub fn move_line_down(
 9090        &mut self,
 9091        _: &MoveLineDown,
 9092        window: &mut Window,
 9093        cx: &mut Context<Self>,
 9094    ) {
 9095        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9096        let buffer = self.buffer.read(cx).snapshot(cx);
 9097
 9098        let mut edits = Vec::new();
 9099        let mut unfold_ranges = Vec::new();
 9100        let mut refold_creases = Vec::new();
 9101
 9102        let selections = self.selections.all::<Point>(cx);
 9103        let mut selections = selections.iter().peekable();
 9104        let mut contiguous_row_selections = Vec::new();
 9105        let mut new_selections = Vec::new();
 9106
 9107        while let Some(selection) = selections.next() {
 9108            // Find all the selections that span a contiguous row range
 9109            let (start_row, end_row) = consume_contiguous_rows(
 9110                &mut contiguous_row_selections,
 9111                selection,
 9112                &display_map,
 9113                &mut selections,
 9114            );
 9115
 9116            // Move the text spanned by the row range to be after the last line of the row range
 9117            if end_row.0 <= buffer.max_point().row {
 9118                let range_to_move =
 9119                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 9120                let insertion_point = display_map
 9121                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 9122                    .0;
 9123
 9124                // Don't move lines across excerpt boundaries
 9125                if buffer
 9126                    .excerpt_containing(range_to_move.start..insertion_point)
 9127                    .is_some()
 9128                {
 9129                    let mut text = String::from("\n");
 9130                    text.extend(buffer.text_for_range(range_to_move.clone()));
 9131                    text.pop(); // Drop trailing newline
 9132                    edits.push((
 9133                        buffer.anchor_after(range_to_move.start)
 9134                            ..buffer.anchor_before(range_to_move.end),
 9135                        String::new(),
 9136                    ));
 9137                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9138                    edits.push((insertion_anchor..insertion_anchor, text));
 9139
 9140                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 9141
 9142                    // Move selections down
 9143                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9144                        |mut selection| {
 9145                            selection.start.row += row_delta;
 9146                            selection.end.row += row_delta;
 9147                            selection
 9148                        },
 9149                    ));
 9150
 9151                    // Move folds down
 9152                    unfold_ranges.push(range_to_move.clone());
 9153                    for fold in display_map.folds_in_range(
 9154                        buffer.anchor_before(range_to_move.start)
 9155                            ..buffer.anchor_after(range_to_move.end),
 9156                    ) {
 9157                        let mut start = fold.range.start.to_point(&buffer);
 9158                        let mut end = fold.range.end.to_point(&buffer);
 9159                        start.row += row_delta;
 9160                        end.row += row_delta;
 9161                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9162                    }
 9163                }
 9164            }
 9165
 9166            // If we didn't move line(s), preserve the existing selections
 9167            new_selections.append(&mut contiguous_row_selections);
 9168        }
 9169
 9170        self.transact(window, cx, |this, window, cx| {
 9171            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9172            this.buffer.update(cx, |buffer, cx| {
 9173                for (range, text) in edits {
 9174                    buffer.edit([(range, text)], None, cx);
 9175                }
 9176            });
 9177            this.fold_creases(refold_creases, true, window, cx);
 9178            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9179                s.select(new_selections)
 9180            });
 9181        });
 9182    }
 9183
 9184    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 9185        let text_layout_details = &self.text_layout_details(window);
 9186        self.transact(window, cx, |this, window, cx| {
 9187            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9188                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 9189                let line_mode = s.line_mode;
 9190                s.move_with(|display_map, selection| {
 9191                    if !selection.is_empty() || line_mode {
 9192                        return;
 9193                    }
 9194
 9195                    let mut head = selection.head();
 9196                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 9197                    if head.column() == display_map.line_len(head.row()) {
 9198                        transpose_offset = display_map
 9199                            .buffer_snapshot
 9200                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9201                    }
 9202
 9203                    if transpose_offset == 0 {
 9204                        return;
 9205                    }
 9206
 9207                    *head.column_mut() += 1;
 9208                    head = display_map.clip_point(head, Bias::Right);
 9209                    let goal = SelectionGoal::HorizontalPosition(
 9210                        display_map
 9211                            .x_for_display_point(head, text_layout_details)
 9212                            .into(),
 9213                    );
 9214                    selection.collapse_to(head, goal);
 9215
 9216                    let transpose_start = display_map
 9217                        .buffer_snapshot
 9218                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9219                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 9220                        let transpose_end = display_map
 9221                            .buffer_snapshot
 9222                            .clip_offset(transpose_offset + 1, Bias::Right);
 9223                        if let Some(ch) =
 9224                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 9225                        {
 9226                            edits.push((transpose_start..transpose_offset, String::new()));
 9227                            edits.push((transpose_end..transpose_end, ch.to_string()));
 9228                        }
 9229                    }
 9230                });
 9231                edits
 9232            });
 9233            this.buffer
 9234                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 9235            let selections = this.selections.all::<usize>(cx);
 9236            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9237                s.select(selections);
 9238            });
 9239        });
 9240    }
 9241
 9242    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 9243        self.rewrap_impl(RewrapOptions::default(), cx)
 9244    }
 9245
 9246    pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
 9247        let buffer = self.buffer.read(cx).snapshot(cx);
 9248        let selections = self.selections.all::<Point>(cx);
 9249        let mut selections = selections.iter().peekable();
 9250
 9251        let mut edits = Vec::new();
 9252        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 9253
 9254        while let Some(selection) = selections.next() {
 9255            let mut start_row = selection.start.row;
 9256            let mut end_row = selection.end.row;
 9257
 9258            // Skip selections that overlap with a range that has already been rewrapped.
 9259            let selection_range = start_row..end_row;
 9260            if rewrapped_row_ranges
 9261                .iter()
 9262                .any(|range| range.overlaps(&selection_range))
 9263            {
 9264                continue;
 9265            }
 9266
 9267            let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
 9268
 9269            // Since not all lines in the selection may be at the same indent
 9270            // level, choose the indent size that is the most common between all
 9271            // of the lines.
 9272            //
 9273            // If there is a tie, we use the deepest indent.
 9274            let (indent_size, indent_end) = {
 9275                let mut indent_size_occurrences = HashMap::default();
 9276                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 9277
 9278                for row in start_row..=end_row {
 9279                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 9280                    rows_by_indent_size.entry(indent).or_default().push(row);
 9281                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 9282                }
 9283
 9284                let indent_size = indent_size_occurrences
 9285                    .into_iter()
 9286                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 9287                    .map(|(indent, _)| indent)
 9288                    .unwrap_or_default();
 9289                let row = rows_by_indent_size[&indent_size][0];
 9290                let indent_end = Point::new(row, indent_size.len);
 9291
 9292                (indent_size, indent_end)
 9293            };
 9294
 9295            let mut line_prefix = indent_size.chars().collect::<String>();
 9296
 9297            let mut inside_comment = false;
 9298            if let Some(comment_prefix) =
 9299                buffer
 9300                    .language_scope_at(selection.head())
 9301                    .and_then(|language| {
 9302                        language
 9303                            .line_comment_prefixes()
 9304                            .iter()
 9305                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 9306                            .cloned()
 9307                    })
 9308            {
 9309                line_prefix.push_str(&comment_prefix);
 9310                inside_comment = true;
 9311            }
 9312
 9313            let language_settings = buffer.language_settings_at(selection.head(), cx);
 9314            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 9315                RewrapBehavior::InComments => inside_comment,
 9316                RewrapBehavior::InSelections => !selection.is_empty(),
 9317                RewrapBehavior::Anywhere => true,
 9318            };
 9319
 9320            let should_rewrap = options.override_language_settings
 9321                || allow_rewrap_based_on_language
 9322                || self.hard_wrap.is_some();
 9323            if !should_rewrap {
 9324                continue;
 9325            }
 9326
 9327            if selection.is_empty() {
 9328                'expand_upwards: while start_row > 0 {
 9329                    let prev_row = start_row - 1;
 9330                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 9331                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 9332                    {
 9333                        start_row = prev_row;
 9334                    } else {
 9335                        break 'expand_upwards;
 9336                    }
 9337                }
 9338
 9339                'expand_downwards: while end_row < buffer.max_point().row {
 9340                    let next_row = end_row + 1;
 9341                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 9342                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 9343                    {
 9344                        end_row = next_row;
 9345                    } else {
 9346                        break 'expand_downwards;
 9347                    }
 9348                }
 9349            }
 9350
 9351            let start = Point::new(start_row, 0);
 9352            let start_offset = start.to_offset(&buffer);
 9353            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 9354            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 9355            let Some(lines_without_prefixes) = selection_text
 9356                .lines()
 9357                .map(|line| {
 9358                    line.strip_prefix(&line_prefix)
 9359                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 9360                        .ok_or_else(|| {
 9361                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 9362                        })
 9363                })
 9364                .collect::<Result<Vec<_>, _>>()
 9365                .log_err()
 9366            else {
 9367                continue;
 9368            };
 9369
 9370            let wrap_column = self.hard_wrap.unwrap_or_else(|| {
 9371                buffer
 9372                    .language_settings_at(Point::new(start_row, 0), cx)
 9373                    .preferred_line_length as usize
 9374            });
 9375            let wrapped_text = wrap_with_prefix(
 9376                line_prefix,
 9377                lines_without_prefixes.join("\n"),
 9378                wrap_column,
 9379                tab_size,
 9380                options.preserve_existing_whitespace,
 9381            );
 9382
 9383            // TODO: should always use char-based diff while still supporting cursor behavior that
 9384            // matches vim.
 9385            let mut diff_options = DiffOptions::default();
 9386            if options.override_language_settings {
 9387                diff_options.max_word_diff_len = 0;
 9388                diff_options.max_word_diff_line_count = 0;
 9389            } else {
 9390                diff_options.max_word_diff_len = usize::MAX;
 9391                diff_options.max_word_diff_line_count = usize::MAX;
 9392            }
 9393
 9394            for (old_range, new_text) in
 9395                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
 9396            {
 9397                let edit_start = buffer.anchor_after(start_offset + old_range.start);
 9398                let edit_end = buffer.anchor_after(start_offset + old_range.end);
 9399                edits.push((edit_start..edit_end, new_text));
 9400            }
 9401
 9402            rewrapped_row_ranges.push(start_row..=end_row);
 9403        }
 9404
 9405        self.buffer
 9406            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 9407    }
 9408
 9409    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 9410        let mut text = String::new();
 9411        let buffer = self.buffer.read(cx).snapshot(cx);
 9412        let mut selections = self.selections.all::<Point>(cx);
 9413        let mut clipboard_selections = Vec::with_capacity(selections.len());
 9414        {
 9415            let max_point = buffer.max_point();
 9416            let mut is_first = true;
 9417            for selection in &mut selections {
 9418                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 9419                if is_entire_line {
 9420                    selection.start = Point::new(selection.start.row, 0);
 9421                    if !selection.is_empty() && selection.end.column == 0 {
 9422                        selection.end = cmp::min(max_point, selection.end);
 9423                    } else {
 9424                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 9425                    }
 9426                    selection.goal = SelectionGoal::None;
 9427                }
 9428                if is_first {
 9429                    is_first = false;
 9430                } else {
 9431                    text += "\n";
 9432                }
 9433                let mut len = 0;
 9434                for chunk in buffer.text_for_range(selection.start..selection.end) {
 9435                    text.push_str(chunk);
 9436                    len += chunk.len();
 9437                }
 9438                clipboard_selections.push(ClipboardSelection {
 9439                    len,
 9440                    is_entire_line,
 9441                    first_line_indent: buffer
 9442                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 9443                        .len,
 9444                });
 9445            }
 9446        }
 9447
 9448        self.transact(window, cx, |this, window, cx| {
 9449            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9450                s.select(selections);
 9451            });
 9452            this.insert("", window, cx);
 9453        });
 9454        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 9455    }
 9456
 9457    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 9458        let item = self.cut_common(window, cx);
 9459        cx.write_to_clipboard(item);
 9460    }
 9461
 9462    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 9463        self.change_selections(None, window, cx, |s| {
 9464            s.move_with(|snapshot, sel| {
 9465                if sel.is_empty() {
 9466                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 9467                }
 9468            });
 9469        });
 9470        let item = self.cut_common(window, cx);
 9471        cx.set_global(KillRing(item))
 9472    }
 9473
 9474    pub fn kill_ring_yank(
 9475        &mut self,
 9476        _: &KillRingYank,
 9477        window: &mut Window,
 9478        cx: &mut Context<Self>,
 9479    ) {
 9480        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 9481            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 9482                (kill_ring.text().to_string(), kill_ring.metadata_json())
 9483            } else {
 9484                return;
 9485            }
 9486        } else {
 9487            return;
 9488        };
 9489        self.do_paste(&text, metadata, false, window, cx);
 9490    }
 9491
 9492    pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
 9493        self.do_copy(true, cx);
 9494    }
 9495
 9496    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 9497        self.do_copy(false, cx);
 9498    }
 9499
 9500    fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
 9501        let selections = self.selections.all::<Point>(cx);
 9502        let buffer = self.buffer.read(cx).read(cx);
 9503        let mut text = String::new();
 9504
 9505        let mut clipboard_selections = Vec::with_capacity(selections.len());
 9506        {
 9507            let max_point = buffer.max_point();
 9508            let mut is_first = true;
 9509            for selection in &selections {
 9510                let mut start = selection.start;
 9511                let mut end = selection.end;
 9512                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 9513                if is_entire_line {
 9514                    start = Point::new(start.row, 0);
 9515                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 9516                }
 9517
 9518                let mut trimmed_selections = Vec::new();
 9519                if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
 9520                    let row = MultiBufferRow(start.row);
 9521                    let first_indent = buffer.indent_size_for_line(row);
 9522                    if first_indent.len == 0 || start.column > first_indent.len {
 9523                        trimmed_selections.push(start..end);
 9524                    } else {
 9525                        trimmed_selections.push(
 9526                            Point::new(row.0, first_indent.len)
 9527                                ..Point::new(row.0, buffer.line_len(row)),
 9528                        );
 9529                        for row in start.row + 1..=end.row {
 9530                            let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
 9531                            if row_indent_size.len >= first_indent.len {
 9532                                trimmed_selections.push(
 9533                                    Point::new(row, first_indent.len)
 9534                                        ..Point::new(row, buffer.line_len(MultiBufferRow(row))),
 9535                                );
 9536                            } else {
 9537                                trimmed_selections.clear();
 9538                                trimmed_selections.push(start..end);
 9539                                break;
 9540                            }
 9541                        }
 9542                    }
 9543                } else {
 9544                    trimmed_selections.push(start..end);
 9545                }
 9546
 9547                for trimmed_range in trimmed_selections {
 9548                    if is_first {
 9549                        is_first = false;
 9550                    } else {
 9551                        text += "\n";
 9552                    }
 9553                    let mut len = 0;
 9554                    for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
 9555                        text.push_str(chunk);
 9556                        len += chunk.len();
 9557                    }
 9558                    clipboard_selections.push(ClipboardSelection {
 9559                        len,
 9560                        is_entire_line,
 9561                        first_line_indent: buffer
 9562                            .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
 9563                            .len,
 9564                    });
 9565                }
 9566            }
 9567        }
 9568
 9569        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 9570            text,
 9571            clipboard_selections,
 9572        ));
 9573    }
 9574
 9575    pub fn do_paste(
 9576        &mut self,
 9577        text: &String,
 9578        clipboard_selections: Option<Vec<ClipboardSelection>>,
 9579        handle_entire_lines: bool,
 9580        window: &mut Window,
 9581        cx: &mut Context<Self>,
 9582    ) {
 9583        if self.read_only(cx) {
 9584            return;
 9585        }
 9586
 9587        let clipboard_text = Cow::Borrowed(text);
 9588
 9589        self.transact(window, cx, |this, window, cx| {
 9590            if let Some(mut clipboard_selections) = clipboard_selections {
 9591                let old_selections = this.selections.all::<usize>(cx);
 9592                let all_selections_were_entire_line =
 9593                    clipboard_selections.iter().all(|s| s.is_entire_line);
 9594                let first_selection_indent_column =
 9595                    clipboard_selections.first().map(|s| s.first_line_indent);
 9596                if clipboard_selections.len() != old_selections.len() {
 9597                    clipboard_selections.drain(..);
 9598                }
 9599                let cursor_offset = this.selections.last::<usize>(cx).head();
 9600                let mut auto_indent_on_paste = true;
 9601
 9602                this.buffer.update(cx, |buffer, cx| {
 9603                    let snapshot = buffer.read(cx);
 9604                    auto_indent_on_paste = snapshot
 9605                        .language_settings_at(cursor_offset, cx)
 9606                        .auto_indent_on_paste;
 9607
 9608                    let mut start_offset = 0;
 9609                    let mut edits = Vec::new();
 9610                    let mut original_indent_columns = Vec::new();
 9611                    for (ix, selection) in old_selections.iter().enumerate() {
 9612                        let to_insert;
 9613                        let entire_line;
 9614                        let original_indent_column;
 9615                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 9616                            let end_offset = start_offset + clipboard_selection.len;
 9617                            to_insert = &clipboard_text[start_offset..end_offset];
 9618                            entire_line = clipboard_selection.is_entire_line;
 9619                            start_offset = end_offset + 1;
 9620                            original_indent_column = Some(clipboard_selection.first_line_indent);
 9621                        } else {
 9622                            to_insert = clipboard_text.as_str();
 9623                            entire_line = all_selections_were_entire_line;
 9624                            original_indent_column = first_selection_indent_column
 9625                        }
 9626
 9627                        // If the corresponding selection was empty when this slice of the
 9628                        // clipboard text was written, then the entire line containing the
 9629                        // selection was copied. If this selection is also currently empty,
 9630                        // then paste the line before the current line of the buffer.
 9631                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 9632                            let column = selection.start.to_point(&snapshot).column as usize;
 9633                            let line_start = selection.start - column;
 9634                            line_start..line_start
 9635                        } else {
 9636                            selection.range()
 9637                        };
 9638
 9639                        edits.push((range, to_insert));
 9640                        original_indent_columns.push(original_indent_column);
 9641                    }
 9642                    drop(snapshot);
 9643
 9644                    buffer.edit(
 9645                        edits,
 9646                        if auto_indent_on_paste {
 9647                            Some(AutoindentMode::Block {
 9648                                original_indent_columns,
 9649                            })
 9650                        } else {
 9651                            None
 9652                        },
 9653                        cx,
 9654                    );
 9655                });
 9656
 9657                let selections = this.selections.all::<usize>(cx);
 9658                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9659                    s.select(selections)
 9660                });
 9661            } else {
 9662                this.insert(&clipboard_text, window, cx);
 9663            }
 9664        });
 9665    }
 9666
 9667    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 9668        if let Some(item) = cx.read_from_clipboard() {
 9669            let entries = item.entries();
 9670
 9671            match entries.first() {
 9672                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 9673                // of all the pasted entries.
 9674                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 9675                    .do_paste(
 9676                        clipboard_string.text(),
 9677                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 9678                        true,
 9679                        window,
 9680                        cx,
 9681                    ),
 9682                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 9683            }
 9684        }
 9685    }
 9686
 9687    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 9688        if self.read_only(cx) {
 9689            return;
 9690        }
 9691
 9692        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 9693            if let Some((selections, _)) =
 9694                self.selection_history.transaction(transaction_id).cloned()
 9695            {
 9696                self.change_selections(None, window, cx, |s| {
 9697                    s.select_anchors(selections.to_vec());
 9698                });
 9699            } else {
 9700                log::error!(
 9701                    "No entry in selection_history found for undo. \
 9702                     This may correspond to a bug where undo does not update the selection. \
 9703                     If this is occurring, please add details to \
 9704                     https://github.com/zed-industries/zed/issues/22692"
 9705                );
 9706            }
 9707            self.request_autoscroll(Autoscroll::fit(), cx);
 9708            self.unmark_text(window, cx);
 9709            self.refresh_inline_completion(true, false, window, cx);
 9710            cx.emit(EditorEvent::Edited { transaction_id });
 9711            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 9712        }
 9713    }
 9714
 9715    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 9716        if self.read_only(cx) {
 9717            return;
 9718        }
 9719
 9720        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 9721            if let Some((_, Some(selections))) =
 9722                self.selection_history.transaction(transaction_id).cloned()
 9723            {
 9724                self.change_selections(None, window, cx, |s| {
 9725                    s.select_anchors(selections.to_vec());
 9726                });
 9727            } else {
 9728                log::error!(
 9729                    "No entry in selection_history found for redo. \
 9730                     This may correspond to a bug where undo does not update the selection. \
 9731                     If this is occurring, please add details to \
 9732                     https://github.com/zed-industries/zed/issues/22692"
 9733                );
 9734            }
 9735            self.request_autoscroll(Autoscroll::fit(), cx);
 9736            self.unmark_text(window, cx);
 9737            self.refresh_inline_completion(true, false, window, cx);
 9738            cx.emit(EditorEvent::Edited { transaction_id });
 9739        }
 9740    }
 9741
 9742    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 9743        self.buffer
 9744            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 9745    }
 9746
 9747    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 9748        self.buffer
 9749            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 9750    }
 9751
 9752    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 9753        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9754            let line_mode = s.line_mode;
 9755            s.move_with(|map, selection| {
 9756                let cursor = if selection.is_empty() && !line_mode {
 9757                    movement::left(map, selection.start)
 9758                } else {
 9759                    selection.start
 9760                };
 9761                selection.collapse_to(cursor, SelectionGoal::None);
 9762            });
 9763        })
 9764    }
 9765
 9766    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 9767        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9768            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 9769        })
 9770    }
 9771
 9772    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 9773        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9774            let line_mode = s.line_mode;
 9775            s.move_with(|map, selection| {
 9776                let cursor = if selection.is_empty() && !line_mode {
 9777                    movement::right(map, selection.end)
 9778                } else {
 9779                    selection.end
 9780                };
 9781                selection.collapse_to(cursor, SelectionGoal::None)
 9782            });
 9783        })
 9784    }
 9785
 9786    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 9787        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9788            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 9789        })
 9790    }
 9791
 9792    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 9793        if self.take_rename(true, window, cx).is_some() {
 9794            return;
 9795        }
 9796
 9797        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9798            cx.propagate();
 9799            return;
 9800        }
 9801
 9802        let text_layout_details = &self.text_layout_details(window);
 9803        let selection_count = self.selections.count();
 9804        let first_selection = self.selections.first_anchor();
 9805
 9806        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9807            let line_mode = s.line_mode;
 9808            s.move_with(|map, selection| {
 9809                if !selection.is_empty() && !line_mode {
 9810                    selection.goal = SelectionGoal::None;
 9811                }
 9812                let (cursor, goal) = movement::up(
 9813                    map,
 9814                    selection.start,
 9815                    selection.goal,
 9816                    false,
 9817                    text_layout_details,
 9818                );
 9819                selection.collapse_to(cursor, goal);
 9820            });
 9821        });
 9822
 9823        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 9824        {
 9825            cx.propagate();
 9826        }
 9827    }
 9828
 9829    pub fn move_up_by_lines(
 9830        &mut self,
 9831        action: &MoveUpByLines,
 9832        window: &mut Window,
 9833        cx: &mut Context<Self>,
 9834    ) {
 9835        if self.take_rename(true, window, cx).is_some() {
 9836            return;
 9837        }
 9838
 9839        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9840            cx.propagate();
 9841            return;
 9842        }
 9843
 9844        let text_layout_details = &self.text_layout_details(window);
 9845
 9846        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9847            let line_mode = s.line_mode;
 9848            s.move_with(|map, selection| {
 9849                if !selection.is_empty() && !line_mode {
 9850                    selection.goal = SelectionGoal::None;
 9851                }
 9852                let (cursor, goal) = movement::up_by_rows(
 9853                    map,
 9854                    selection.start,
 9855                    action.lines,
 9856                    selection.goal,
 9857                    false,
 9858                    text_layout_details,
 9859                );
 9860                selection.collapse_to(cursor, goal);
 9861            });
 9862        })
 9863    }
 9864
 9865    pub fn move_down_by_lines(
 9866        &mut self,
 9867        action: &MoveDownByLines,
 9868        window: &mut Window,
 9869        cx: &mut Context<Self>,
 9870    ) {
 9871        if self.take_rename(true, window, cx).is_some() {
 9872            return;
 9873        }
 9874
 9875        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9876            cx.propagate();
 9877            return;
 9878        }
 9879
 9880        let text_layout_details = &self.text_layout_details(window);
 9881
 9882        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9883            let line_mode = s.line_mode;
 9884            s.move_with(|map, selection| {
 9885                if !selection.is_empty() && !line_mode {
 9886                    selection.goal = SelectionGoal::None;
 9887                }
 9888                let (cursor, goal) = movement::down_by_rows(
 9889                    map,
 9890                    selection.start,
 9891                    action.lines,
 9892                    selection.goal,
 9893                    false,
 9894                    text_layout_details,
 9895                );
 9896                selection.collapse_to(cursor, goal);
 9897            });
 9898        })
 9899    }
 9900
 9901    pub fn select_down_by_lines(
 9902        &mut self,
 9903        action: &SelectDownByLines,
 9904        window: &mut Window,
 9905        cx: &mut Context<Self>,
 9906    ) {
 9907        let text_layout_details = &self.text_layout_details(window);
 9908        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9909            s.move_heads_with(|map, head, goal| {
 9910                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 9911            })
 9912        })
 9913    }
 9914
 9915    pub fn select_up_by_lines(
 9916        &mut self,
 9917        action: &SelectUpByLines,
 9918        window: &mut Window,
 9919        cx: &mut Context<Self>,
 9920    ) {
 9921        let text_layout_details = &self.text_layout_details(window);
 9922        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9923            s.move_heads_with(|map, head, goal| {
 9924                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 9925            })
 9926        })
 9927    }
 9928
 9929    pub fn select_page_up(
 9930        &mut self,
 9931        _: &SelectPageUp,
 9932        window: &mut Window,
 9933        cx: &mut Context<Self>,
 9934    ) {
 9935        let Some(row_count) = self.visible_row_count() else {
 9936            return;
 9937        };
 9938
 9939        let text_layout_details = &self.text_layout_details(window);
 9940
 9941        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9942            s.move_heads_with(|map, head, goal| {
 9943                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 9944            })
 9945        })
 9946    }
 9947
 9948    pub fn move_page_up(
 9949        &mut self,
 9950        action: &MovePageUp,
 9951        window: &mut Window,
 9952        cx: &mut Context<Self>,
 9953    ) {
 9954        if self.take_rename(true, window, cx).is_some() {
 9955            return;
 9956        }
 9957
 9958        if self
 9959            .context_menu
 9960            .borrow_mut()
 9961            .as_mut()
 9962            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 9963            .unwrap_or(false)
 9964        {
 9965            return;
 9966        }
 9967
 9968        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9969            cx.propagate();
 9970            return;
 9971        }
 9972
 9973        let Some(row_count) = self.visible_row_count() else {
 9974            return;
 9975        };
 9976
 9977        let autoscroll = if action.center_cursor {
 9978            Autoscroll::center()
 9979        } else {
 9980            Autoscroll::fit()
 9981        };
 9982
 9983        let text_layout_details = &self.text_layout_details(window);
 9984
 9985        self.change_selections(Some(autoscroll), window, cx, |s| {
 9986            let line_mode = s.line_mode;
 9987            s.move_with(|map, selection| {
 9988                if !selection.is_empty() && !line_mode {
 9989                    selection.goal = SelectionGoal::None;
 9990                }
 9991                let (cursor, goal) = movement::up_by_rows(
 9992                    map,
 9993                    selection.end,
 9994                    row_count,
 9995                    selection.goal,
 9996                    false,
 9997                    text_layout_details,
 9998                );
 9999                selection.collapse_to(cursor, goal);
10000            });
10001        });
10002    }
10003
10004    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10005        let text_layout_details = &self.text_layout_details(window);
10006        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10007            s.move_heads_with(|map, head, goal| {
10008                movement::up(map, head, goal, false, text_layout_details)
10009            })
10010        })
10011    }
10012
10013    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10014        self.take_rename(true, window, cx);
10015
10016        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10017            cx.propagate();
10018            return;
10019        }
10020
10021        let text_layout_details = &self.text_layout_details(window);
10022        let selection_count = self.selections.count();
10023        let first_selection = self.selections.first_anchor();
10024
10025        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10026            let line_mode = s.line_mode;
10027            s.move_with(|map, selection| {
10028                if !selection.is_empty() && !line_mode {
10029                    selection.goal = SelectionGoal::None;
10030                }
10031                let (cursor, goal) = movement::down(
10032                    map,
10033                    selection.end,
10034                    selection.goal,
10035                    false,
10036                    text_layout_details,
10037                );
10038                selection.collapse_to(cursor, goal);
10039            });
10040        });
10041
10042        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10043        {
10044            cx.propagate();
10045        }
10046    }
10047
10048    pub fn select_page_down(
10049        &mut self,
10050        _: &SelectPageDown,
10051        window: &mut Window,
10052        cx: &mut Context<Self>,
10053    ) {
10054        let Some(row_count) = self.visible_row_count() else {
10055            return;
10056        };
10057
10058        let text_layout_details = &self.text_layout_details(window);
10059
10060        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10061            s.move_heads_with(|map, head, goal| {
10062                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10063            })
10064        })
10065    }
10066
10067    pub fn move_page_down(
10068        &mut self,
10069        action: &MovePageDown,
10070        window: &mut Window,
10071        cx: &mut Context<Self>,
10072    ) {
10073        if self.take_rename(true, window, cx).is_some() {
10074            return;
10075        }
10076
10077        if self
10078            .context_menu
10079            .borrow_mut()
10080            .as_mut()
10081            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10082            .unwrap_or(false)
10083        {
10084            return;
10085        }
10086
10087        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10088            cx.propagate();
10089            return;
10090        }
10091
10092        let Some(row_count) = self.visible_row_count() else {
10093            return;
10094        };
10095
10096        let autoscroll = if action.center_cursor {
10097            Autoscroll::center()
10098        } else {
10099            Autoscroll::fit()
10100        };
10101
10102        let text_layout_details = &self.text_layout_details(window);
10103        self.change_selections(Some(autoscroll), window, cx, |s| {
10104            let line_mode = s.line_mode;
10105            s.move_with(|map, selection| {
10106                if !selection.is_empty() && !line_mode {
10107                    selection.goal = SelectionGoal::None;
10108                }
10109                let (cursor, goal) = movement::down_by_rows(
10110                    map,
10111                    selection.end,
10112                    row_count,
10113                    selection.goal,
10114                    false,
10115                    text_layout_details,
10116                );
10117                selection.collapse_to(cursor, goal);
10118            });
10119        });
10120    }
10121
10122    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10123        let text_layout_details = &self.text_layout_details(window);
10124        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10125            s.move_heads_with(|map, head, goal| {
10126                movement::down(map, head, goal, false, text_layout_details)
10127            })
10128        });
10129    }
10130
10131    pub fn context_menu_first(
10132        &mut self,
10133        _: &ContextMenuFirst,
10134        _window: &mut Window,
10135        cx: &mut Context<Self>,
10136    ) {
10137        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10138            context_menu.select_first(self.completion_provider.as_deref(), cx);
10139        }
10140    }
10141
10142    pub fn context_menu_prev(
10143        &mut self,
10144        _: &ContextMenuPrevious,
10145        _window: &mut Window,
10146        cx: &mut Context<Self>,
10147    ) {
10148        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10149            context_menu.select_prev(self.completion_provider.as_deref(), cx);
10150        }
10151    }
10152
10153    pub fn context_menu_next(
10154        &mut self,
10155        _: &ContextMenuNext,
10156        _window: &mut Window,
10157        cx: &mut Context<Self>,
10158    ) {
10159        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10160            context_menu.select_next(self.completion_provider.as_deref(), cx);
10161        }
10162    }
10163
10164    pub fn context_menu_last(
10165        &mut self,
10166        _: &ContextMenuLast,
10167        _window: &mut Window,
10168        cx: &mut Context<Self>,
10169    ) {
10170        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10171            context_menu.select_last(self.completion_provider.as_deref(), cx);
10172        }
10173    }
10174
10175    pub fn move_to_previous_word_start(
10176        &mut self,
10177        _: &MoveToPreviousWordStart,
10178        window: &mut Window,
10179        cx: &mut Context<Self>,
10180    ) {
10181        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10182            s.move_cursors_with(|map, head, _| {
10183                (
10184                    movement::previous_word_start(map, head),
10185                    SelectionGoal::None,
10186                )
10187            });
10188        })
10189    }
10190
10191    pub fn move_to_previous_subword_start(
10192        &mut self,
10193        _: &MoveToPreviousSubwordStart,
10194        window: &mut Window,
10195        cx: &mut Context<Self>,
10196    ) {
10197        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10198            s.move_cursors_with(|map, head, _| {
10199                (
10200                    movement::previous_subword_start(map, head),
10201                    SelectionGoal::None,
10202                )
10203            });
10204        })
10205    }
10206
10207    pub fn select_to_previous_word_start(
10208        &mut self,
10209        _: &SelectToPreviousWordStart,
10210        window: &mut Window,
10211        cx: &mut Context<Self>,
10212    ) {
10213        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10214            s.move_heads_with(|map, head, _| {
10215                (
10216                    movement::previous_word_start(map, head),
10217                    SelectionGoal::None,
10218                )
10219            });
10220        })
10221    }
10222
10223    pub fn select_to_previous_subword_start(
10224        &mut self,
10225        _: &SelectToPreviousSubwordStart,
10226        window: &mut Window,
10227        cx: &mut Context<Self>,
10228    ) {
10229        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10230            s.move_heads_with(|map, head, _| {
10231                (
10232                    movement::previous_subword_start(map, head),
10233                    SelectionGoal::None,
10234                )
10235            });
10236        })
10237    }
10238
10239    pub fn delete_to_previous_word_start(
10240        &mut self,
10241        action: &DeleteToPreviousWordStart,
10242        window: &mut Window,
10243        cx: &mut Context<Self>,
10244    ) {
10245        self.transact(window, cx, |this, window, cx| {
10246            this.select_autoclose_pair(window, cx);
10247            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10248                let line_mode = s.line_mode;
10249                s.move_with(|map, selection| {
10250                    if selection.is_empty() && !line_mode {
10251                        let cursor = if action.ignore_newlines {
10252                            movement::previous_word_start(map, selection.head())
10253                        } else {
10254                            movement::previous_word_start_or_newline(map, selection.head())
10255                        };
10256                        selection.set_head(cursor, SelectionGoal::None);
10257                    }
10258                });
10259            });
10260            this.insert("", window, cx);
10261        });
10262    }
10263
10264    pub fn delete_to_previous_subword_start(
10265        &mut self,
10266        _: &DeleteToPreviousSubwordStart,
10267        window: &mut Window,
10268        cx: &mut Context<Self>,
10269    ) {
10270        self.transact(window, cx, |this, window, cx| {
10271            this.select_autoclose_pair(window, cx);
10272            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10273                let line_mode = s.line_mode;
10274                s.move_with(|map, selection| {
10275                    if selection.is_empty() && !line_mode {
10276                        let cursor = movement::previous_subword_start(map, selection.head());
10277                        selection.set_head(cursor, SelectionGoal::None);
10278                    }
10279                });
10280            });
10281            this.insert("", window, cx);
10282        });
10283    }
10284
10285    pub fn move_to_next_word_end(
10286        &mut self,
10287        _: &MoveToNextWordEnd,
10288        window: &mut Window,
10289        cx: &mut Context<Self>,
10290    ) {
10291        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10292            s.move_cursors_with(|map, head, _| {
10293                (movement::next_word_end(map, head), SelectionGoal::None)
10294            });
10295        })
10296    }
10297
10298    pub fn move_to_next_subword_end(
10299        &mut self,
10300        _: &MoveToNextSubwordEnd,
10301        window: &mut Window,
10302        cx: &mut Context<Self>,
10303    ) {
10304        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10305            s.move_cursors_with(|map, head, _| {
10306                (movement::next_subword_end(map, head), SelectionGoal::None)
10307            });
10308        })
10309    }
10310
10311    pub fn select_to_next_word_end(
10312        &mut self,
10313        _: &SelectToNextWordEnd,
10314        window: &mut Window,
10315        cx: &mut Context<Self>,
10316    ) {
10317        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10318            s.move_heads_with(|map, head, _| {
10319                (movement::next_word_end(map, head), SelectionGoal::None)
10320            });
10321        })
10322    }
10323
10324    pub fn select_to_next_subword_end(
10325        &mut self,
10326        _: &SelectToNextSubwordEnd,
10327        window: &mut Window,
10328        cx: &mut Context<Self>,
10329    ) {
10330        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10331            s.move_heads_with(|map, head, _| {
10332                (movement::next_subword_end(map, head), SelectionGoal::None)
10333            });
10334        })
10335    }
10336
10337    pub fn delete_to_next_word_end(
10338        &mut self,
10339        action: &DeleteToNextWordEnd,
10340        window: &mut Window,
10341        cx: &mut Context<Self>,
10342    ) {
10343        self.transact(window, cx, |this, window, cx| {
10344            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10345                let line_mode = s.line_mode;
10346                s.move_with(|map, selection| {
10347                    if selection.is_empty() && !line_mode {
10348                        let cursor = if action.ignore_newlines {
10349                            movement::next_word_end(map, selection.head())
10350                        } else {
10351                            movement::next_word_end_or_newline(map, selection.head())
10352                        };
10353                        selection.set_head(cursor, SelectionGoal::None);
10354                    }
10355                });
10356            });
10357            this.insert("", window, cx);
10358        });
10359    }
10360
10361    pub fn delete_to_next_subword_end(
10362        &mut self,
10363        _: &DeleteToNextSubwordEnd,
10364        window: &mut Window,
10365        cx: &mut Context<Self>,
10366    ) {
10367        self.transact(window, cx, |this, window, cx| {
10368            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10369                s.move_with(|map, selection| {
10370                    if selection.is_empty() {
10371                        let cursor = movement::next_subword_end(map, selection.head());
10372                        selection.set_head(cursor, SelectionGoal::None);
10373                    }
10374                });
10375            });
10376            this.insert("", window, cx);
10377        });
10378    }
10379
10380    pub fn move_to_beginning_of_line(
10381        &mut self,
10382        action: &MoveToBeginningOfLine,
10383        window: &mut Window,
10384        cx: &mut Context<Self>,
10385    ) {
10386        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10387            s.move_cursors_with(|map, head, _| {
10388                (
10389                    movement::indented_line_beginning(
10390                        map,
10391                        head,
10392                        action.stop_at_soft_wraps,
10393                        action.stop_at_indent,
10394                    ),
10395                    SelectionGoal::None,
10396                )
10397            });
10398        })
10399    }
10400
10401    pub fn select_to_beginning_of_line(
10402        &mut self,
10403        action: &SelectToBeginningOfLine,
10404        window: &mut Window,
10405        cx: &mut Context<Self>,
10406    ) {
10407        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10408            s.move_heads_with(|map, head, _| {
10409                (
10410                    movement::indented_line_beginning(
10411                        map,
10412                        head,
10413                        action.stop_at_soft_wraps,
10414                        action.stop_at_indent,
10415                    ),
10416                    SelectionGoal::None,
10417                )
10418            });
10419        });
10420    }
10421
10422    pub fn delete_to_beginning_of_line(
10423        &mut self,
10424        action: &DeleteToBeginningOfLine,
10425        window: &mut Window,
10426        cx: &mut Context<Self>,
10427    ) {
10428        self.transact(window, cx, |this, window, cx| {
10429            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10430                s.move_with(|_, selection| {
10431                    selection.reversed = true;
10432                });
10433            });
10434
10435            this.select_to_beginning_of_line(
10436                &SelectToBeginningOfLine {
10437                    stop_at_soft_wraps: false,
10438                    stop_at_indent: action.stop_at_indent,
10439                },
10440                window,
10441                cx,
10442            );
10443            this.backspace(&Backspace, window, cx);
10444        });
10445    }
10446
10447    pub fn move_to_end_of_line(
10448        &mut self,
10449        action: &MoveToEndOfLine,
10450        window: &mut Window,
10451        cx: &mut Context<Self>,
10452    ) {
10453        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10454            s.move_cursors_with(|map, head, _| {
10455                (
10456                    movement::line_end(map, head, action.stop_at_soft_wraps),
10457                    SelectionGoal::None,
10458                )
10459            });
10460        })
10461    }
10462
10463    pub fn select_to_end_of_line(
10464        &mut self,
10465        action: &SelectToEndOfLine,
10466        window: &mut Window,
10467        cx: &mut Context<Self>,
10468    ) {
10469        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10470            s.move_heads_with(|map, head, _| {
10471                (
10472                    movement::line_end(map, head, action.stop_at_soft_wraps),
10473                    SelectionGoal::None,
10474                )
10475            });
10476        })
10477    }
10478
10479    pub fn delete_to_end_of_line(
10480        &mut self,
10481        _: &DeleteToEndOfLine,
10482        window: &mut Window,
10483        cx: &mut Context<Self>,
10484    ) {
10485        self.transact(window, cx, |this, window, cx| {
10486            this.select_to_end_of_line(
10487                &SelectToEndOfLine {
10488                    stop_at_soft_wraps: false,
10489                },
10490                window,
10491                cx,
10492            );
10493            this.delete(&Delete, window, cx);
10494        });
10495    }
10496
10497    pub fn cut_to_end_of_line(
10498        &mut self,
10499        _: &CutToEndOfLine,
10500        window: &mut Window,
10501        cx: &mut Context<Self>,
10502    ) {
10503        self.transact(window, cx, |this, window, cx| {
10504            this.select_to_end_of_line(
10505                &SelectToEndOfLine {
10506                    stop_at_soft_wraps: false,
10507                },
10508                window,
10509                cx,
10510            );
10511            this.cut(&Cut, window, cx);
10512        });
10513    }
10514
10515    pub fn move_to_start_of_paragraph(
10516        &mut self,
10517        _: &MoveToStartOfParagraph,
10518        window: &mut Window,
10519        cx: &mut Context<Self>,
10520    ) {
10521        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10522            cx.propagate();
10523            return;
10524        }
10525
10526        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10527            s.move_with(|map, selection| {
10528                selection.collapse_to(
10529                    movement::start_of_paragraph(map, selection.head(), 1),
10530                    SelectionGoal::None,
10531                )
10532            });
10533        })
10534    }
10535
10536    pub fn move_to_end_of_paragraph(
10537        &mut self,
10538        _: &MoveToEndOfParagraph,
10539        window: &mut Window,
10540        cx: &mut Context<Self>,
10541    ) {
10542        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10543            cx.propagate();
10544            return;
10545        }
10546
10547        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10548            s.move_with(|map, selection| {
10549                selection.collapse_to(
10550                    movement::end_of_paragraph(map, selection.head(), 1),
10551                    SelectionGoal::None,
10552                )
10553            });
10554        })
10555    }
10556
10557    pub fn select_to_start_of_paragraph(
10558        &mut self,
10559        _: &SelectToStartOfParagraph,
10560        window: &mut Window,
10561        cx: &mut Context<Self>,
10562    ) {
10563        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10564            cx.propagate();
10565            return;
10566        }
10567
10568        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10569            s.move_heads_with(|map, head, _| {
10570                (
10571                    movement::start_of_paragraph(map, head, 1),
10572                    SelectionGoal::None,
10573                )
10574            });
10575        })
10576    }
10577
10578    pub fn select_to_end_of_paragraph(
10579        &mut self,
10580        _: &SelectToEndOfParagraph,
10581        window: &mut Window,
10582        cx: &mut Context<Self>,
10583    ) {
10584        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10585            cx.propagate();
10586            return;
10587        }
10588
10589        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10590            s.move_heads_with(|map, head, _| {
10591                (
10592                    movement::end_of_paragraph(map, head, 1),
10593                    SelectionGoal::None,
10594                )
10595            });
10596        })
10597    }
10598
10599    pub fn move_to_start_of_excerpt(
10600        &mut self,
10601        _: &MoveToStartOfExcerpt,
10602        window: &mut Window,
10603        cx: &mut Context<Self>,
10604    ) {
10605        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10606            cx.propagate();
10607            return;
10608        }
10609
10610        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10611            s.move_with(|map, selection| {
10612                selection.collapse_to(
10613                    movement::start_of_excerpt(
10614                        map,
10615                        selection.head(),
10616                        workspace::searchable::Direction::Prev,
10617                    ),
10618                    SelectionGoal::None,
10619                )
10620            });
10621        })
10622    }
10623
10624    pub fn move_to_start_of_next_excerpt(
10625        &mut self,
10626        _: &MoveToStartOfNextExcerpt,
10627        window: &mut Window,
10628        cx: &mut Context<Self>,
10629    ) {
10630        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10631            cx.propagate();
10632            return;
10633        }
10634
10635        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10636            s.move_with(|map, selection| {
10637                selection.collapse_to(
10638                    movement::start_of_excerpt(
10639                        map,
10640                        selection.head(),
10641                        workspace::searchable::Direction::Next,
10642                    ),
10643                    SelectionGoal::None,
10644                )
10645            });
10646        })
10647    }
10648
10649    pub fn move_to_end_of_excerpt(
10650        &mut self,
10651        _: &MoveToEndOfExcerpt,
10652        window: &mut Window,
10653        cx: &mut Context<Self>,
10654    ) {
10655        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10656            cx.propagate();
10657            return;
10658        }
10659
10660        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10661            s.move_with(|map, selection| {
10662                selection.collapse_to(
10663                    movement::end_of_excerpt(
10664                        map,
10665                        selection.head(),
10666                        workspace::searchable::Direction::Next,
10667                    ),
10668                    SelectionGoal::None,
10669                )
10670            });
10671        })
10672    }
10673
10674    pub fn move_to_end_of_previous_excerpt(
10675        &mut self,
10676        _: &MoveToEndOfPreviousExcerpt,
10677        window: &mut Window,
10678        cx: &mut Context<Self>,
10679    ) {
10680        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10681            cx.propagate();
10682            return;
10683        }
10684
10685        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10686            s.move_with(|map, selection| {
10687                selection.collapse_to(
10688                    movement::end_of_excerpt(
10689                        map,
10690                        selection.head(),
10691                        workspace::searchable::Direction::Prev,
10692                    ),
10693                    SelectionGoal::None,
10694                )
10695            });
10696        })
10697    }
10698
10699    pub fn select_to_start_of_excerpt(
10700        &mut self,
10701        _: &SelectToStartOfExcerpt,
10702        window: &mut Window,
10703        cx: &mut Context<Self>,
10704    ) {
10705        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10706            cx.propagate();
10707            return;
10708        }
10709
10710        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10711            s.move_heads_with(|map, head, _| {
10712                (
10713                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
10714                    SelectionGoal::None,
10715                )
10716            });
10717        })
10718    }
10719
10720    pub fn select_to_start_of_next_excerpt(
10721        &mut self,
10722        _: &SelectToStartOfNextExcerpt,
10723        window: &mut Window,
10724        cx: &mut Context<Self>,
10725    ) {
10726        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10727            cx.propagate();
10728            return;
10729        }
10730
10731        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10732            s.move_heads_with(|map, head, _| {
10733                (
10734                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
10735                    SelectionGoal::None,
10736                )
10737            });
10738        })
10739    }
10740
10741    pub fn select_to_end_of_excerpt(
10742        &mut self,
10743        _: &SelectToEndOfExcerpt,
10744        window: &mut Window,
10745        cx: &mut Context<Self>,
10746    ) {
10747        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10748            cx.propagate();
10749            return;
10750        }
10751
10752        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10753            s.move_heads_with(|map, head, _| {
10754                (
10755                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
10756                    SelectionGoal::None,
10757                )
10758            });
10759        })
10760    }
10761
10762    pub fn select_to_end_of_previous_excerpt(
10763        &mut self,
10764        _: &SelectToEndOfPreviousExcerpt,
10765        window: &mut Window,
10766        cx: &mut Context<Self>,
10767    ) {
10768        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10769            cx.propagate();
10770            return;
10771        }
10772
10773        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10774            s.move_heads_with(|map, head, _| {
10775                (
10776                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
10777                    SelectionGoal::None,
10778                )
10779            });
10780        })
10781    }
10782
10783    pub fn move_to_beginning(
10784        &mut self,
10785        _: &MoveToBeginning,
10786        window: &mut Window,
10787        cx: &mut Context<Self>,
10788    ) {
10789        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10790            cx.propagate();
10791            return;
10792        }
10793
10794        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10795            s.select_ranges(vec![0..0]);
10796        });
10797    }
10798
10799    pub fn select_to_beginning(
10800        &mut self,
10801        _: &SelectToBeginning,
10802        window: &mut Window,
10803        cx: &mut Context<Self>,
10804    ) {
10805        let mut selection = self.selections.last::<Point>(cx);
10806        selection.set_head(Point::zero(), SelectionGoal::None);
10807
10808        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10809            s.select(vec![selection]);
10810        });
10811    }
10812
10813    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
10814        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10815            cx.propagate();
10816            return;
10817        }
10818
10819        let cursor = self.buffer.read(cx).read(cx).len();
10820        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10821            s.select_ranges(vec![cursor..cursor])
10822        });
10823    }
10824
10825    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
10826        self.nav_history = nav_history;
10827    }
10828
10829    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
10830        self.nav_history.as_ref()
10831    }
10832
10833    pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
10834        self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
10835    }
10836
10837    fn push_to_nav_history(
10838        &mut self,
10839        cursor_anchor: Anchor,
10840        new_position: Option<Point>,
10841        is_deactivate: bool,
10842        cx: &mut Context<Self>,
10843    ) {
10844        if let Some(nav_history) = self.nav_history.as_mut() {
10845            let buffer = self.buffer.read(cx).read(cx);
10846            let cursor_position = cursor_anchor.to_point(&buffer);
10847            let scroll_state = self.scroll_manager.anchor();
10848            let scroll_top_row = scroll_state.top_row(&buffer);
10849            drop(buffer);
10850
10851            if let Some(new_position) = new_position {
10852                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
10853                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
10854                    return;
10855                }
10856            }
10857
10858            nav_history.push(
10859                Some(NavigationData {
10860                    cursor_anchor,
10861                    cursor_position,
10862                    scroll_anchor: scroll_state,
10863                    scroll_top_row,
10864                }),
10865                cx,
10866            );
10867            cx.emit(EditorEvent::PushedToNavHistory {
10868                anchor: cursor_anchor,
10869                is_deactivate,
10870            })
10871        }
10872    }
10873
10874    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
10875        let buffer = self.buffer.read(cx).snapshot(cx);
10876        let mut selection = self.selections.first::<usize>(cx);
10877        selection.set_head(buffer.len(), SelectionGoal::None);
10878        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10879            s.select(vec![selection]);
10880        });
10881    }
10882
10883    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
10884        let end = self.buffer.read(cx).read(cx).len();
10885        self.change_selections(None, window, cx, |s| {
10886            s.select_ranges(vec![0..end]);
10887        });
10888    }
10889
10890    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
10891        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10892        let mut selections = self.selections.all::<Point>(cx);
10893        let max_point = display_map.buffer_snapshot.max_point();
10894        for selection in &mut selections {
10895            let rows = selection.spanned_rows(true, &display_map);
10896            selection.start = Point::new(rows.start.0, 0);
10897            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
10898            selection.reversed = false;
10899        }
10900        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10901            s.select(selections);
10902        });
10903    }
10904
10905    pub fn split_selection_into_lines(
10906        &mut self,
10907        _: &SplitSelectionIntoLines,
10908        window: &mut Window,
10909        cx: &mut Context<Self>,
10910    ) {
10911        let selections = self
10912            .selections
10913            .all::<Point>(cx)
10914            .into_iter()
10915            .map(|selection| selection.start..selection.end)
10916            .collect::<Vec<_>>();
10917        self.unfold_ranges(&selections, true, true, cx);
10918
10919        let mut new_selection_ranges = Vec::new();
10920        {
10921            let buffer = self.buffer.read(cx).read(cx);
10922            for selection in selections {
10923                for row in selection.start.row..selection.end.row {
10924                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
10925                    new_selection_ranges.push(cursor..cursor);
10926                }
10927
10928                let is_multiline_selection = selection.start.row != selection.end.row;
10929                // Don't insert last one if it's a multi-line selection ending at the start of a line,
10930                // so this action feels more ergonomic when paired with other selection operations
10931                let should_skip_last = is_multiline_selection && selection.end.column == 0;
10932                if !should_skip_last {
10933                    new_selection_ranges.push(selection.end..selection.end);
10934                }
10935            }
10936        }
10937        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10938            s.select_ranges(new_selection_ranges);
10939        });
10940    }
10941
10942    pub fn add_selection_above(
10943        &mut self,
10944        _: &AddSelectionAbove,
10945        window: &mut Window,
10946        cx: &mut Context<Self>,
10947    ) {
10948        self.add_selection(true, window, cx);
10949    }
10950
10951    pub fn add_selection_below(
10952        &mut self,
10953        _: &AddSelectionBelow,
10954        window: &mut Window,
10955        cx: &mut Context<Self>,
10956    ) {
10957        self.add_selection(false, window, cx);
10958    }
10959
10960    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
10961        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10962        let mut selections = self.selections.all::<Point>(cx);
10963        let text_layout_details = self.text_layout_details(window);
10964        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
10965            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
10966            let range = oldest_selection.display_range(&display_map).sorted();
10967
10968            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
10969            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
10970            let positions = start_x.min(end_x)..start_x.max(end_x);
10971
10972            selections.clear();
10973            let mut stack = Vec::new();
10974            for row in range.start.row().0..=range.end.row().0 {
10975                if let Some(selection) = self.selections.build_columnar_selection(
10976                    &display_map,
10977                    DisplayRow(row),
10978                    &positions,
10979                    oldest_selection.reversed,
10980                    &text_layout_details,
10981                ) {
10982                    stack.push(selection.id);
10983                    selections.push(selection);
10984                }
10985            }
10986
10987            if above {
10988                stack.reverse();
10989            }
10990
10991            AddSelectionsState { above, stack }
10992        });
10993
10994        let last_added_selection = *state.stack.last().unwrap();
10995        let mut new_selections = Vec::new();
10996        if above == state.above {
10997            let end_row = if above {
10998                DisplayRow(0)
10999            } else {
11000                display_map.max_point().row()
11001            };
11002
11003            'outer: for selection in selections {
11004                if selection.id == last_added_selection {
11005                    let range = selection.display_range(&display_map).sorted();
11006                    debug_assert_eq!(range.start.row(), range.end.row());
11007                    let mut row = range.start.row();
11008                    let positions =
11009                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11010                            px(start)..px(end)
11011                        } else {
11012                            let start_x =
11013                                display_map.x_for_display_point(range.start, &text_layout_details);
11014                            let end_x =
11015                                display_map.x_for_display_point(range.end, &text_layout_details);
11016                            start_x.min(end_x)..start_x.max(end_x)
11017                        };
11018
11019                    while row != end_row {
11020                        if above {
11021                            row.0 -= 1;
11022                        } else {
11023                            row.0 += 1;
11024                        }
11025
11026                        if let Some(new_selection) = self.selections.build_columnar_selection(
11027                            &display_map,
11028                            row,
11029                            &positions,
11030                            selection.reversed,
11031                            &text_layout_details,
11032                        ) {
11033                            state.stack.push(new_selection.id);
11034                            if above {
11035                                new_selections.push(new_selection);
11036                                new_selections.push(selection);
11037                            } else {
11038                                new_selections.push(selection);
11039                                new_selections.push(new_selection);
11040                            }
11041
11042                            continue 'outer;
11043                        }
11044                    }
11045                }
11046
11047                new_selections.push(selection);
11048            }
11049        } else {
11050            new_selections = selections;
11051            new_selections.retain(|s| s.id != last_added_selection);
11052            state.stack.pop();
11053        }
11054
11055        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11056            s.select(new_selections);
11057        });
11058        if state.stack.len() > 1 {
11059            self.add_selections_state = Some(state);
11060        }
11061    }
11062
11063    pub fn select_next_match_internal(
11064        &mut self,
11065        display_map: &DisplaySnapshot,
11066        replace_newest: bool,
11067        autoscroll: Option<Autoscroll>,
11068        window: &mut Window,
11069        cx: &mut Context<Self>,
11070    ) -> Result<()> {
11071        fn select_next_match_ranges(
11072            this: &mut Editor,
11073            range: Range<usize>,
11074            replace_newest: bool,
11075            auto_scroll: Option<Autoscroll>,
11076            window: &mut Window,
11077            cx: &mut Context<Editor>,
11078        ) {
11079            this.unfold_ranges(&[range.clone()], false, true, cx);
11080            this.change_selections(auto_scroll, window, cx, |s| {
11081                if replace_newest {
11082                    s.delete(s.newest_anchor().id);
11083                }
11084                s.insert_range(range.clone());
11085            });
11086        }
11087
11088        let buffer = &display_map.buffer_snapshot;
11089        let mut selections = self.selections.all::<usize>(cx);
11090        if let Some(mut select_next_state) = self.select_next_state.take() {
11091            let query = &select_next_state.query;
11092            if !select_next_state.done {
11093                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11094                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11095                let mut next_selected_range = None;
11096
11097                let bytes_after_last_selection =
11098                    buffer.bytes_in_range(last_selection.end..buffer.len());
11099                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11100                let query_matches = query
11101                    .stream_find_iter(bytes_after_last_selection)
11102                    .map(|result| (last_selection.end, result))
11103                    .chain(
11104                        query
11105                            .stream_find_iter(bytes_before_first_selection)
11106                            .map(|result| (0, result)),
11107                    );
11108
11109                for (start_offset, query_match) in query_matches {
11110                    let query_match = query_match.unwrap(); // can only fail due to I/O
11111                    let offset_range =
11112                        start_offset + query_match.start()..start_offset + query_match.end();
11113                    let display_range = offset_range.start.to_display_point(display_map)
11114                        ..offset_range.end.to_display_point(display_map);
11115
11116                    if !select_next_state.wordwise
11117                        || (!movement::is_inside_word(display_map, display_range.start)
11118                            && !movement::is_inside_word(display_map, display_range.end))
11119                    {
11120                        // TODO: This is n^2, because we might check all the selections
11121                        if !selections
11122                            .iter()
11123                            .any(|selection| selection.range().overlaps(&offset_range))
11124                        {
11125                            next_selected_range = Some(offset_range);
11126                            break;
11127                        }
11128                    }
11129                }
11130
11131                if let Some(next_selected_range) = next_selected_range {
11132                    select_next_match_ranges(
11133                        self,
11134                        next_selected_range,
11135                        replace_newest,
11136                        autoscroll,
11137                        window,
11138                        cx,
11139                    );
11140                } else {
11141                    select_next_state.done = true;
11142                }
11143            }
11144
11145            self.select_next_state = Some(select_next_state);
11146        } else {
11147            let mut only_carets = true;
11148            let mut same_text_selected = true;
11149            let mut selected_text = None;
11150
11151            let mut selections_iter = selections.iter().peekable();
11152            while let Some(selection) = selections_iter.next() {
11153                if selection.start != selection.end {
11154                    only_carets = false;
11155                }
11156
11157                if same_text_selected {
11158                    if selected_text.is_none() {
11159                        selected_text =
11160                            Some(buffer.text_for_range(selection.range()).collect::<String>());
11161                    }
11162
11163                    if let Some(next_selection) = selections_iter.peek() {
11164                        if next_selection.range().len() == selection.range().len() {
11165                            let next_selected_text = buffer
11166                                .text_for_range(next_selection.range())
11167                                .collect::<String>();
11168                            if Some(next_selected_text) != selected_text {
11169                                same_text_selected = false;
11170                                selected_text = None;
11171                            }
11172                        } else {
11173                            same_text_selected = false;
11174                            selected_text = None;
11175                        }
11176                    }
11177                }
11178            }
11179
11180            if only_carets {
11181                for selection in &mut selections {
11182                    let word_range = movement::surrounding_word(
11183                        display_map,
11184                        selection.start.to_display_point(display_map),
11185                    );
11186                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
11187                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
11188                    selection.goal = SelectionGoal::None;
11189                    selection.reversed = false;
11190                    select_next_match_ranges(
11191                        self,
11192                        selection.start..selection.end,
11193                        replace_newest,
11194                        autoscroll,
11195                        window,
11196                        cx,
11197                    );
11198                }
11199
11200                if selections.len() == 1 {
11201                    let selection = selections
11202                        .last()
11203                        .expect("ensured that there's only one selection");
11204                    let query = buffer
11205                        .text_for_range(selection.start..selection.end)
11206                        .collect::<String>();
11207                    let is_empty = query.is_empty();
11208                    let select_state = SelectNextState {
11209                        query: AhoCorasick::new(&[query])?,
11210                        wordwise: true,
11211                        done: is_empty,
11212                    };
11213                    self.select_next_state = Some(select_state);
11214                } else {
11215                    self.select_next_state = None;
11216                }
11217            } else if let Some(selected_text) = selected_text {
11218                self.select_next_state = Some(SelectNextState {
11219                    query: AhoCorasick::new(&[selected_text])?,
11220                    wordwise: false,
11221                    done: false,
11222                });
11223                self.select_next_match_internal(
11224                    display_map,
11225                    replace_newest,
11226                    autoscroll,
11227                    window,
11228                    cx,
11229                )?;
11230            }
11231        }
11232        Ok(())
11233    }
11234
11235    pub fn select_all_matches(
11236        &mut self,
11237        _action: &SelectAllMatches,
11238        window: &mut Window,
11239        cx: &mut Context<Self>,
11240    ) -> Result<()> {
11241        self.push_to_selection_history();
11242        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11243
11244        self.select_next_match_internal(&display_map, false, None, window, cx)?;
11245        let Some(select_next_state) = self.select_next_state.as_mut() else {
11246            return Ok(());
11247        };
11248        if select_next_state.done {
11249            return Ok(());
11250        }
11251
11252        let mut new_selections = self.selections.all::<usize>(cx);
11253
11254        let buffer = &display_map.buffer_snapshot;
11255        let query_matches = select_next_state
11256            .query
11257            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11258
11259        for query_match in query_matches {
11260            let query_match = query_match.unwrap(); // can only fail due to I/O
11261            let offset_range = query_match.start()..query_match.end();
11262            let display_range = offset_range.start.to_display_point(&display_map)
11263                ..offset_range.end.to_display_point(&display_map);
11264
11265            if !select_next_state.wordwise
11266                || (!movement::is_inside_word(&display_map, display_range.start)
11267                    && !movement::is_inside_word(&display_map, display_range.end))
11268            {
11269                self.selections.change_with(cx, |selections| {
11270                    new_selections.push(Selection {
11271                        id: selections.new_selection_id(),
11272                        start: offset_range.start,
11273                        end: offset_range.end,
11274                        reversed: false,
11275                        goal: SelectionGoal::None,
11276                    });
11277                });
11278            }
11279        }
11280
11281        new_selections.sort_by_key(|selection| selection.start);
11282        let mut ix = 0;
11283        while ix + 1 < new_selections.len() {
11284            let current_selection = &new_selections[ix];
11285            let next_selection = &new_selections[ix + 1];
11286            if current_selection.range().overlaps(&next_selection.range()) {
11287                if current_selection.id < next_selection.id {
11288                    new_selections.remove(ix + 1);
11289                } else {
11290                    new_selections.remove(ix);
11291                }
11292            } else {
11293                ix += 1;
11294            }
11295        }
11296
11297        let reversed = self.selections.oldest::<usize>(cx).reversed;
11298
11299        for selection in new_selections.iter_mut() {
11300            selection.reversed = reversed;
11301        }
11302
11303        select_next_state.done = true;
11304        self.unfold_ranges(
11305            &new_selections
11306                .iter()
11307                .map(|selection| selection.range())
11308                .collect::<Vec<_>>(),
11309            false,
11310            false,
11311            cx,
11312        );
11313        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
11314            selections.select(new_selections)
11315        });
11316
11317        Ok(())
11318    }
11319
11320    pub fn select_next(
11321        &mut self,
11322        action: &SelectNext,
11323        window: &mut Window,
11324        cx: &mut Context<Self>,
11325    ) -> Result<()> {
11326        self.push_to_selection_history();
11327        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11328        self.select_next_match_internal(
11329            &display_map,
11330            action.replace_newest,
11331            Some(Autoscroll::newest()),
11332            window,
11333            cx,
11334        )?;
11335        Ok(())
11336    }
11337
11338    pub fn select_previous(
11339        &mut self,
11340        action: &SelectPrevious,
11341        window: &mut Window,
11342        cx: &mut Context<Self>,
11343    ) -> Result<()> {
11344        self.push_to_selection_history();
11345        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11346        let buffer = &display_map.buffer_snapshot;
11347        let mut selections = self.selections.all::<usize>(cx);
11348        if let Some(mut select_prev_state) = self.select_prev_state.take() {
11349            let query = &select_prev_state.query;
11350            if !select_prev_state.done {
11351                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11352                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11353                let mut next_selected_range = None;
11354                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
11355                let bytes_before_last_selection =
11356                    buffer.reversed_bytes_in_range(0..last_selection.start);
11357                let bytes_after_first_selection =
11358                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
11359                let query_matches = query
11360                    .stream_find_iter(bytes_before_last_selection)
11361                    .map(|result| (last_selection.start, result))
11362                    .chain(
11363                        query
11364                            .stream_find_iter(bytes_after_first_selection)
11365                            .map(|result| (buffer.len(), result)),
11366                    );
11367                for (end_offset, query_match) in query_matches {
11368                    let query_match = query_match.unwrap(); // can only fail due to I/O
11369                    let offset_range =
11370                        end_offset - query_match.end()..end_offset - query_match.start();
11371                    let display_range = offset_range.start.to_display_point(&display_map)
11372                        ..offset_range.end.to_display_point(&display_map);
11373
11374                    if !select_prev_state.wordwise
11375                        || (!movement::is_inside_word(&display_map, display_range.start)
11376                            && !movement::is_inside_word(&display_map, display_range.end))
11377                    {
11378                        next_selected_range = Some(offset_range);
11379                        break;
11380                    }
11381                }
11382
11383                if let Some(next_selected_range) = next_selected_range {
11384                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
11385                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11386                        if action.replace_newest {
11387                            s.delete(s.newest_anchor().id);
11388                        }
11389                        s.insert_range(next_selected_range);
11390                    });
11391                } else {
11392                    select_prev_state.done = true;
11393                }
11394            }
11395
11396            self.select_prev_state = Some(select_prev_state);
11397        } else {
11398            let mut only_carets = true;
11399            let mut same_text_selected = true;
11400            let mut selected_text = None;
11401
11402            let mut selections_iter = selections.iter().peekable();
11403            while let Some(selection) = selections_iter.next() {
11404                if selection.start != selection.end {
11405                    only_carets = false;
11406                }
11407
11408                if same_text_selected {
11409                    if selected_text.is_none() {
11410                        selected_text =
11411                            Some(buffer.text_for_range(selection.range()).collect::<String>());
11412                    }
11413
11414                    if let Some(next_selection) = selections_iter.peek() {
11415                        if next_selection.range().len() == selection.range().len() {
11416                            let next_selected_text = buffer
11417                                .text_for_range(next_selection.range())
11418                                .collect::<String>();
11419                            if Some(next_selected_text) != selected_text {
11420                                same_text_selected = false;
11421                                selected_text = None;
11422                            }
11423                        } else {
11424                            same_text_selected = false;
11425                            selected_text = None;
11426                        }
11427                    }
11428                }
11429            }
11430
11431            if only_carets {
11432                for selection in &mut selections {
11433                    let word_range = movement::surrounding_word(
11434                        &display_map,
11435                        selection.start.to_display_point(&display_map),
11436                    );
11437                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
11438                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
11439                    selection.goal = SelectionGoal::None;
11440                    selection.reversed = false;
11441                }
11442                if selections.len() == 1 {
11443                    let selection = selections
11444                        .last()
11445                        .expect("ensured that there's only one selection");
11446                    let query = buffer
11447                        .text_for_range(selection.start..selection.end)
11448                        .collect::<String>();
11449                    let is_empty = query.is_empty();
11450                    let select_state = SelectNextState {
11451                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
11452                        wordwise: true,
11453                        done: is_empty,
11454                    };
11455                    self.select_prev_state = Some(select_state);
11456                } else {
11457                    self.select_prev_state = None;
11458                }
11459
11460                self.unfold_ranges(
11461                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
11462                    false,
11463                    true,
11464                    cx,
11465                );
11466                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11467                    s.select(selections);
11468                });
11469            } else if let Some(selected_text) = selected_text {
11470                self.select_prev_state = Some(SelectNextState {
11471                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
11472                    wordwise: false,
11473                    done: false,
11474                });
11475                self.select_previous(action, window, cx)?;
11476            }
11477        }
11478        Ok(())
11479    }
11480
11481    pub fn toggle_comments(
11482        &mut self,
11483        action: &ToggleComments,
11484        window: &mut Window,
11485        cx: &mut Context<Self>,
11486    ) {
11487        if self.read_only(cx) {
11488            return;
11489        }
11490        let text_layout_details = &self.text_layout_details(window);
11491        self.transact(window, cx, |this, window, cx| {
11492            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
11493            let mut edits = Vec::new();
11494            let mut selection_edit_ranges = Vec::new();
11495            let mut last_toggled_row = None;
11496            let snapshot = this.buffer.read(cx).read(cx);
11497            let empty_str: Arc<str> = Arc::default();
11498            let mut suffixes_inserted = Vec::new();
11499            let ignore_indent = action.ignore_indent;
11500
11501            fn comment_prefix_range(
11502                snapshot: &MultiBufferSnapshot,
11503                row: MultiBufferRow,
11504                comment_prefix: &str,
11505                comment_prefix_whitespace: &str,
11506                ignore_indent: bool,
11507            ) -> Range<Point> {
11508                let indent_size = if ignore_indent {
11509                    0
11510                } else {
11511                    snapshot.indent_size_for_line(row).len
11512                };
11513
11514                let start = Point::new(row.0, indent_size);
11515
11516                let mut line_bytes = snapshot
11517                    .bytes_in_range(start..snapshot.max_point())
11518                    .flatten()
11519                    .copied();
11520
11521                // If this line currently begins with the line comment prefix, then record
11522                // the range containing the prefix.
11523                if line_bytes
11524                    .by_ref()
11525                    .take(comment_prefix.len())
11526                    .eq(comment_prefix.bytes())
11527                {
11528                    // Include any whitespace that matches the comment prefix.
11529                    let matching_whitespace_len = line_bytes
11530                        .zip(comment_prefix_whitespace.bytes())
11531                        .take_while(|(a, b)| a == b)
11532                        .count() as u32;
11533                    let end = Point::new(
11534                        start.row,
11535                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
11536                    );
11537                    start..end
11538                } else {
11539                    start..start
11540                }
11541            }
11542
11543            fn comment_suffix_range(
11544                snapshot: &MultiBufferSnapshot,
11545                row: MultiBufferRow,
11546                comment_suffix: &str,
11547                comment_suffix_has_leading_space: bool,
11548            ) -> Range<Point> {
11549                let end = Point::new(row.0, snapshot.line_len(row));
11550                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
11551
11552                let mut line_end_bytes = snapshot
11553                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
11554                    .flatten()
11555                    .copied();
11556
11557                let leading_space_len = if suffix_start_column > 0
11558                    && line_end_bytes.next() == Some(b' ')
11559                    && comment_suffix_has_leading_space
11560                {
11561                    1
11562                } else {
11563                    0
11564                };
11565
11566                // If this line currently begins with the line comment prefix, then record
11567                // the range containing the prefix.
11568                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
11569                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
11570                    start..end
11571                } else {
11572                    end..end
11573                }
11574            }
11575
11576            // TODO: Handle selections that cross excerpts
11577            for selection in &mut selections {
11578                let start_column = snapshot
11579                    .indent_size_for_line(MultiBufferRow(selection.start.row))
11580                    .len;
11581                let language = if let Some(language) =
11582                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
11583                {
11584                    language
11585                } else {
11586                    continue;
11587                };
11588
11589                selection_edit_ranges.clear();
11590
11591                // If multiple selections contain a given row, avoid processing that
11592                // row more than once.
11593                let mut start_row = MultiBufferRow(selection.start.row);
11594                if last_toggled_row == Some(start_row) {
11595                    start_row = start_row.next_row();
11596                }
11597                let end_row =
11598                    if selection.end.row > selection.start.row && selection.end.column == 0 {
11599                        MultiBufferRow(selection.end.row - 1)
11600                    } else {
11601                        MultiBufferRow(selection.end.row)
11602                    };
11603                last_toggled_row = Some(end_row);
11604
11605                if start_row > end_row {
11606                    continue;
11607                }
11608
11609                // If the language has line comments, toggle those.
11610                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
11611
11612                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
11613                if ignore_indent {
11614                    full_comment_prefixes = full_comment_prefixes
11615                        .into_iter()
11616                        .map(|s| Arc::from(s.trim_end()))
11617                        .collect();
11618                }
11619
11620                if !full_comment_prefixes.is_empty() {
11621                    let first_prefix = full_comment_prefixes
11622                        .first()
11623                        .expect("prefixes is non-empty");
11624                    let prefix_trimmed_lengths = full_comment_prefixes
11625                        .iter()
11626                        .map(|p| p.trim_end_matches(' ').len())
11627                        .collect::<SmallVec<[usize; 4]>>();
11628
11629                    let mut all_selection_lines_are_comments = true;
11630
11631                    for row in start_row.0..=end_row.0 {
11632                        let row = MultiBufferRow(row);
11633                        if start_row < end_row && snapshot.is_line_blank(row) {
11634                            continue;
11635                        }
11636
11637                        let prefix_range = full_comment_prefixes
11638                            .iter()
11639                            .zip(prefix_trimmed_lengths.iter().copied())
11640                            .map(|(prefix, trimmed_prefix_len)| {
11641                                comment_prefix_range(
11642                                    snapshot.deref(),
11643                                    row,
11644                                    &prefix[..trimmed_prefix_len],
11645                                    &prefix[trimmed_prefix_len..],
11646                                    ignore_indent,
11647                                )
11648                            })
11649                            .max_by_key(|range| range.end.column - range.start.column)
11650                            .expect("prefixes is non-empty");
11651
11652                        if prefix_range.is_empty() {
11653                            all_selection_lines_are_comments = false;
11654                        }
11655
11656                        selection_edit_ranges.push(prefix_range);
11657                    }
11658
11659                    if all_selection_lines_are_comments {
11660                        edits.extend(
11661                            selection_edit_ranges
11662                                .iter()
11663                                .cloned()
11664                                .map(|range| (range, empty_str.clone())),
11665                        );
11666                    } else {
11667                        let min_column = selection_edit_ranges
11668                            .iter()
11669                            .map(|range| range.start.column)
11670                            .min()
11671                            .unwrap_or(0);
11672                        edits.extend(selection_edit_ranges.iter().map(|range| {
11673                            let position = Point::new(range.start.row, min_column);
11674                            (position..position, first_prefix.clone())
11675                        }));
11676                    }
11677                } else if let Some((full_comment_prefix, comment_suffix)) =
11678                    language.block_comment_delimiters()
11679                {
11680                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
11681                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
11682                    let prefix_range = comment_prefix_range(
11683                        snapshot.deref(),
11684                        start_row,
11685                        comment_prefix,
11686                        comment_prefix_whitespace,
11687                        ignore_indent,
11688                    );
11689                    let suffix_range = comment_suffix_range(
11690                        snapshot.deref(),
11691                        end_row,
11692                        comment_suffix.trim_start_matches(' '),
11693                        comment_suffix.starts_with(' '),
11694                    );
11695
11696                    if prefix_range.is_empty() || suffix_range.is_empty() {
11697                        edits.push((
11698                            prefix_range.start..prefix_range.start,
11699                            full_comment_prefix.clone(),
11700                        ));
11701                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
11702                        suffixes_inserted.push((end_row, comment_suffix.len()));
11703                    } else {
11704                        edits.push((prefix_range, empty_str.clone()));
11705                        edits.push((suffix_range, empty_str.clone()));
11706                    }
11707                } else {
11708                    continue;
11709                }
11710            }
11711
11712            drop(snapshot);
11713            this.buffer.update(cx, |buffer, cx| {
11714                buffer.edit(edits, None, cx);
11715            });
11716
11717            // Adjust selections so that they end before any comment suffixes that
11718            // were inserted.
11719            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
11720            let mut selections = this.selections.all::<Point>(cx);
11721            let snapshot = this.buffer.read(cx).read(cx);
11722            for selection in &mut selections {
11723                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
11724                    match row.cmp(&MultiBufferRow(selection.end.row)) {
11725                        Ordering::Less => {
11726                            suffixes_inserted.next();
11727                            continue;
11728                        }
11729                        Ordering::Greater => break,
11730                        Ordering::Equal => {
11731                            if selection.end.column == snapshot.line_len(row) {
11732                                if selection.is_empty() {
11733                                    selection.start.column -= suffix_len as u32;
11734                                }
11735                                selection.end.column -= suffix_len as u32;
11736                            }
11737                            break;
11738                        }
11739                    }
11740                }
11741            }
11742
11743            drop(snapshot);
11744            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11745                s.select(selections)
11746            });
11747
11748            let selections = this.selections.all::<Point>(cx);
11749            let selections_on_single_row = selections.windows(2).all(|selections| {
11750                selections[0].start.row == selections[1].start.row
11751                    && selections[0].end.row == selections[1].end.row
11752                    && selections[0].start.row == selections[0].end.row
11753            });
11754            let selections_selecting = selections
11755                .iter()
11756                .any(|selection| selection.start != selection.end);
11757            let advance_downwards = action.advance_downwards
11758                && selections_on_single_row
11759                && !selections_selecting
11760                && !matches!(this.mode, EditorMode::SingleLine { .. });
11761
11762            if advance_downwards {
11763                let snapshot = this.buffer.read(cx).snapshot(cx);
11764
11765                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11766                    s.move_cursors_with(|display_snapshot, display_point, _| {
11767                        let mut point = display_point.to_point(display_snapshot);
11768                        point.row += 1;
11769                        point = snapshot.clip_point(point, Bias::Left);
11770                        let display_point = point.to_display_point(display_snapshot);
11771                        let goal = SelectionGoal::HorizontalPosition(
11772                            display_snapshot
11773                                .x_for_display_point(display_point, text_layout_details)
11774                                .into(),
11775                        );
11776                        (display_point, goal)
11777                    })
11778                });
11779            }
11780        });
11781    }
11782
11783    pub fn select_enclosing_symbol(
11784        &mut self,
11785        _: &SelectEnclosingSymbol,
11786        window: &mut Window,
11787        cx: &mut Context<Self>,
11788    ) {
11789        let buffer = self.buffer.read(cx).snapshot(cx);
11790        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
11791
11792        fn update_selection(
11793            selection: &Selection<usize>,
11794            buffer_snap: &MultiBufferSnapshot,
11795        ) -> Option<Selection<usize>> {
11796            let cursor = selection.head();
11797            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
11798            for symbol in symbols.iter().rev() {
11799                let start = symbol.range.start.to_offset(buffer_snap);
11800                let end = symbol.range.end.to_offset(buffer_snap);
11801                let new_range = start..end;
11802                if start < selection.start || end > selection.end {
11803                    return Some(Selection {
11804                        id: selection.id,
11805                        start: new_range.start,
11806                        end: new_range.end,
11807                        goal: SelectionGoal::None,
11808                        reversed: selection.reversed,
11809                    });
11810                }
11811            }
11812            None
11813        }
11814
11815        let mut selected_larger_symbol = false;
11816        let new_selections = old_selections
11817            .iter()
11818            .map(|selection| match update_selection(selection, &buffer) {
11819                Some(new_selection) => {
11820                    if new_selection.range() != selection.range() {
11821                        selected_larger_symbol = true;
11822                    }
11823                    new_selection
11824                }
11825                None => selection.clone(),
11826            })
11827            .collect::<Vec<_>>();
11828
11829        if selected_larger_symbol {
11830            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11831                s.select(new_selections);
11832            });
11833        }
11834    }
11835
11836    pub fn select_larger_syntax_node(
11837        &mut self,
11838        _: &SelectLargerSyntaxNode,
11839        window: &mut Window,
11840        cx: &mut Context<Self>,
11841    ) {
11842        let Some(visible_row_count) = self.visible_row_count() else {
11843            return;
11844        };
11845        let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
11846        if old_selections.is_empty() {
11847            return;
11848        }
11849
11850        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11851        let buffer = self.buffer.read(cx).snapshot(cx);
11852
11853        let mut selected_larger_node = false;
11854        let mut new_selections = old_selections
11855            .iter()
11856            .map(|selection| {
11857                let old_range = selection.start..selection.end;
11858                let mut new_range = old_range.clone();
11859                let mut new_node = None;
11860                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
11861                {
11862                    new_node = Some(node);
11863                    new_range = match containing_range {
11864                        MultiOrSingleBufferOffsetRange::Single(_) => break,
11865                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
11866                    };
11867                    if !display_map.intersects_fold(new_range.start)
11868                        && !display_map.intersects_fold(new_range.end)
11869                    {
11870                        break;
11871                    }
11872                }
11873
11874                if let Some(node) = new_node {
11875                    // Log the ancestor, to support using this action as a way to explore TreeSitter
11876                    // nodes. Parent and grandparent are also logged because this operation will not
11877                    // visit nodes that have the same range as their parent.
11878                    log::info!("Node: {node:?}");
11879                    let parent = node.parent();
11880                    log::info!("Parent: {parent:?}");
11881                    let grandparent = parent.and_then(|x| x.parent());
11882                    log::info!("Grandparent: {grandparent:?}");
11883                }
11884
11885                selected_larger_node |= new_range != old_range;
11886                Selection {
11887                    id: selection.id,
11888                    start: new_range.start,
11889                    end: new_range.end,
11890                    goal: SelectionGoal::None,
11891                    reversed: selection.reversed,
11892                }
11893            })
11894            .collect::<Vec<_>>();
11895
11896        if !selected_larger_node {
11897            return; // don't put this call in the history
11898        }
11899
11900        // scroll based on transformation done to the last selection created by the user
11901        let (last_old, last_new) = old_selections
11902            .last()
11903            .zip(new_selections.last().cloned())
11904            .expect("old_selections isn't empty");
11905
11906        // revert selection
11907        let is_selection_reversed = {
11908            let should_newest_selection_be_reversed = last_old.start != last_new.start;
11909            new_selections.last_mut().expect("checked above").reversed =
11910                should_newest_selection_be_reversed;
11911            should_newest_selection_be_reversed
11912        };
11913
11914        if selected_larger_node {
11915            self.select_syntax_node_history.disable_clearing = true;
11916            self.change_selections(None, window, cx, |s| {
11917                s.select(new_selections.clone());
11918            });
11919            self.select_syntax_node_history.disable_clearing = false;
11920        }
11921
11922        let start_row = last_new.start.to_display_point(&display_map).row().0;
11923        let end_row = last_new.end.to_display_point(&display_map).row().0;
11924        let selection_height = end_row - start_row + 1;
11925        let scroll_margin_rows = self.vertical_scroll_margin() as u32;
11926
11927        // if fits on screen (considering margin), keep it in the middle, else, scroll to selection head
11928        let scroll_behavior = if visible_row_count >= selection_height + scroll_margin_rows * 2 {
11929            let middle_row = (end_row + start_row) / 2;
11930            let selection_center = middle_row.saturating_sub(visible_row_count / 2);
11931            self.set_scroll_top_row(DisplayRow(selection_center), window, cx);
11932            SelectSyntaxNodeScrollBehavior::CenterSelection
11933        } else if is_selection_reversed {
11934            self.scroll_cursor_top(&Default::default(), window, cx);
11935            SelectSyntaxNodeScrollBehavior::CursorTop
11936        } else {
11937            self.scroll_cursor_bottom(&Default::default(), window, cx);
11938            SelectSyntaxNodeScrollBehavior::CursorBottom
11939        };
11940
11941        self.select_syntax_node_history.push((
11942            old_selections,
11943            scroll_behavior,
11944            is_selection_reversed,
11945        ));
11946    }
11947
11948    pub fn select_smaller_syntax_node(
11949        &mut self,
11950        _: &SelectSmallerSyntaxNode,
11951        window: &mut Window,
11952        cx: &mut Context<Self>,
11953    ) {
11954        let Some(visible_row_count) = self.visible_row_count() else {
11955            return;
11956        };
11957
11958        if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
11959            self.select_syntax_node_history.pop()
11960        {
11961            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11962
11963            if let Some(selection) = selections.last_mut() {
11964                selection.reversed = is_selection_reversed;
11965            }
11966
11967            self.select_syntax_node_history.disable_clearing = true;
11968            self.change_selections(None, window, cx, |s| {
11969                s.select(selections.to_vec());
11970            });
11971            self.select_syntax_node_history.disable_clearing = false;
11972
11973            let newest = self.selections.newest::<usize>(cx);
11974            let start_row = newest.start.to_display_point(&display_map).row().0;
11975            let end_row = newest.end.to_display_point(&display_map).row().0;
11976
11977            match scroll_behavior {
11978                SelectSyntaxNodeScrollBehavior::CursorTop => {
11979                    self.scroll_cursor_top(&Default::default(), window, cx);
11980                }
11981                SelectSyntaxNodeScrollBehavior::CenterSelection => {
11982                    let middle_row = (end_row + start_row) / 2;
11983                    let selection_center = middle_row.saturating_sub(visible_row_count / 2);
11984                    // centralize the selection, not the cursor
11985                    self.set_scroll_top_row(DisplayRow(selection_center), window, cx);
11986                }
11987                SelectSyntaxNodeScrollBehavior::CursorBottom => {
11988                    self.scroll_cursor_bottom(&Default::default(), window, cx);
11989                }
11990            }
11991        }
11992    }
11993
11994    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
11995        if !EditorSettings::get_global(cx).gutter.runnables {
11996            self.clear_tasks();
11997            return Task::ready(());
11998        }
11999        let project = self.project.as_ref().map(Entity::downgrade);
12000        cx.spawn_in(window, async move |this, cx| {
12001            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12002            let Some(project) = project.and_then(|p| p.upgrade()) else {
12003                return;
12004            };
12005            let Ok(display_snapshot) = this.update(cx, |this, cx| {
12006                this.display_map.update(cx, |map, cx| map.snapshot(cx))
12007            }) else {
12008                return;
12009            };
12010
12011            let hide_runnables = project
12012                .update(cx, |project, cx| {
12013                    // Do not display any test indicators in non-dev server remote projects.
12014                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12015                })
12016                .unwrap_or(true);
12017            if hide_runnables {
12018                return;
12019            }
12020            let new_rows =
12021                cx.background_spawn({
12022                    let snapshot = display_snapshot.clone();
12023                    async move {
12024                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12025                    }
12026                })
12027                    .await;
12028
12029            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12030            this.update(cx, |this, _| {
12031                this.clear_tasks();
12032                for (key, value) in rows {
12033                    this.insert_tasks(key, value);
12034                }
12035            })
12036            .ok();
12037        })
12038    }
12039    fn fetch_runnable_ranges(
12040        snapshot: &DisplaySnapshot,
12041        range: Range<Anchor>,
12042    ) -> Vec<language::RunnableRange> {
12043        snapshot.buffer_snapshot.runnable_ranges(range).collect()
12044    }
12045
12046    fn runnable_rows(
12047        project: Entity<Project>,
12048        snapshot: DisplaySnapshot,
12049        runnable_ranges: Vec<RunnableRange>,
12050        mut cx: AsyncWindowContext,
12051    ) -> Vec<((BufferId, u32), RunnableTasks)> {
12052        runnable_ranges
12053            .into_iter()
12054            .filter_map(|mut runnable| {
12055                let tasks = cx
12056                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12057                    .ok()?;
12058                if tasks.is_empty() {
12059                    return None;
12060                }
12061
12062                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12063
12064                let row = snapshot
12065                    .buffer_snapshot
12066                    .buffer_line_for_row(MultiBufferRow(point.row))?
12067                    .1
12068                    .start
12069                    .row;
12070
12071                let context_range =
12072                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12073                Some((
12074                    (runnable.buffer_id, row),
12075                    RunnableTasks {
12076                        templates: tasks,
12077                        offset: snapshot
12078                            .buffer_snapshot
12079                            .anchor_before(runnable.run_range.start),
12080                        context_range,
12081                        column: point.column,
12082                        extra_variables: runnable.extra_captures,
12083                    },
12084                ))
12085            })
12086            .collect()
12087    }
12088
12089    fn templates_with_tags(
12090        project: &Entity<Project>,
12091        runnable: &mut Runnable,
12092        cx: &mut App,
12093    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12094        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12095            let (worktree_id, file) = project
12096                .buffer_for_id(runnable.buffer, cx)
12097                .and_then(|buffer| buffer.read(cx).file())
12098                .map(|file| (file.worktree_id(cx), file.clone()))
12099                .unzip();
12100
12101            (
12102                project.task_store().read(cx).task_inventory().cloned(),
12103                worktree_id,
12104                file,
12105            )
12106        });
12107
12108        let tags = mem::take(&mut runnable.tags);
12109        let mut tags: Vec<_> = tags
12110            .into_iter()
12111            .flat_map(|tag| {
12112                let tag = tag.0.clone();
12113                inventory
12114                    .as_ref()
12115                    .into_iter()
12116                    .flat_map(|inventory| {
12117                        inventory.read(cx).list_tasks(
12118                            file.clone(),
12119                            Some(runnable.language.clone()),
12120                            worktree_id,
12121                            cx,
12122                        )
12123                    })
12124                    .filter(move |(_, template)| {
12125                        template.tags.iter().any(|source_tag| source_tag == &tag)
12126                    })
12127            })
12128            .sorted_by_key(|(kind, _)| kind.to_owned())
12129            .collect();
12130        if let Some((leading_tag_source, _)) = tags.first() {
12131            // Strongest source wins; if we have worktree tag binding, prefer that to
12132            // global and language bindings;
12133            // if we have a global binding, prefer that to language binding.
12134            let first_mismatch = tags
12135                .iter()
12136                .position(|(tag_source, _)| tag_source != leading_tag_source);
12137            if let Some(index) = first_mismatch {
12138                tags.truncate(index);
12139            }
12140        }
12141
12142        tags
12143    }
12144
12145    pub fn move_to_enclosing_bracket(
12146        &mut self,
12147        _: &MoveToEnclosingBracket,
12148        window: &mut Window,
12149        cx: &mut Context<Self>,
12150    ) {
12151        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12152            s.move_offsets_with(|snapshot, selection| {
12153                let Some(enclosing_bracket_ranges) =
12154                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
12155                else {
12156                    return;
12157                };
12158
12159                let mut best_length = usize::MAX;
12160                let mut best_inside = false;
12161                let mut best_in_bracket_range = false;
12162                let mut best_destination = None;
12163                for (open, close) in enclosing_bracket_ranges {
12164                    let close = close.to_inclusive();
12165                    let length = close.end() - open.start;
12166                    let inside = selection.start >= open.end && selection.end <= *close.start();
12167                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
12168                        || close.contains(&selection.head());
12169
12170                    // If best is next to a bracket and current isn't, skip
12171                    if !in_bracket_range && best_in_bracket_range {
12172                        continue;
12173                    }
12174
12175                    // Prefer smaller lengths unless best is inside and current isn't
12176                    if length > best_length && (best_inside || !inside) {
12177                        continue;
12178                    }
12179
12180                    best_length = length;
12181                    best_inside = inside;
12182                    best_in_bracket_range = in_bracket_range;
12183                    best_destination = Some(
12184                        if close.contains(&selection.start) && close.contains(&selection.end) {
12185                            if inside {
12186                                open.end
12187                            } else {
12188                                open.start
12189                            }
12190                        } else if inside {
12191                            *close.start()
12192                        } else {
12193                            *close.end()
12194                        },
12195                    );
12196                }
12197
12198                if let Some(destination) = best_destination {
12199                    selection.collapse_to(destination, SelectionGoal::None);
12200                }
12201            })
12202        });
12203    }
12204
12205    pub fn undo_selection(
12206        &mut self,
12207        _: &UndoSelection,
12208        window: &mut Window,
12209        cx: &mut Context<Self>,
12210    ) {
12211        self.end_selection(window, cx);
12212        self.selection_history.mode = SelectionHistoryMode::Undoing;
12213        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
12214            self.change_selections(None, window, cx, |s| {
12215                s.select_anchors(entry.selections.to_vec())
12216            });
12217            self.select_next_state = entry.select_next_state;
12218            self.select_prev_state = entry.select_prev_state;
12219            self.add_selections_state = entry.add_selections_state;
12220            self.request_autoscroll(Autoscroll::newest(), cx);
12221        }
12222        self.selection_history.mode = SelectionHistoryMode::Normal;
12223    }
12224
12225    pub fn redo_selection(
12226        &mut self,
12227        _: &RedoSelection,
12228        window: &mut Window,
12229        cx: &mut Context<Self>,
12230    ) {
12231        self.end_selection(window, cx);
12232        self.selection_history.mode = SelectionHistoryMode::Redoing;
12233        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
12234            self.change_selections(None, window, cx, |s| {
12235                s.select_anchors(entry.selections.to_vec())
12236            });
12237            self.select_next_state = entry.select_next_state;
12238            self.select_prev_state = entry.select_prev_state;
12239            self.add_selections_state = entry.add_selections_state;
12240            self.request_autoscroll(Autoscroll::newest(), cx);
12241        }
12242        self.selection_history.mode = SelectionHistoryMode::Normal;
12243    }
12244
12245    pub fn expand_excerpts(
12246        &mut self,
12247        action: &ExpandExcerpts,
12248        _: &mut Window,
12249        cx: &mut Context<Self>,
12250    ) {
12251        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
12252    }
12253
12254    pub fn expand_excerpts_down(
12255        &mut self,
12256        action: &ExpandExcerptsDown,
12257        _: &mut Window,
12258        cx: &mut Context<Self>,
12259    ) {
12260        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
12261    }
12262
12263    pub fn expand_excerpts_up(
12264        &mut self,
12265        action: &ExpandExcerptsUp,
12266        _: &mut Window,
12267        cx: &mut Context<Self>,
12268    ) {
12269        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
12270    }
12271
12272    pub fn expand_excerpts_for_direction(
12273        &mut self,
12274        lines: u32,
12275        direction: ExpandExcerptDirection,
12276
12277        cx: &mut Context<Self>,
12278    ) {
12279        let selections = self.selections.disjoint_anchors();
12280
12281        let lines = if lines == 0 {
12282            EditorSettings::get_global(cx).expand_excerpt_lines
12283        } else {
12284            lines
12285        };
12286
12287        self.buffer.update(cx, |buffer, cx| {
12288            let snapshot = buffer.snapshot(cx);
12289            let mut excerpt_ids = selections
12290                .iter()
12291                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
12292                .collect::<Vec<_>>();
12293            excerpt_ids.sort();
12294            excerpt_ids.dedup();
12295            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
12296        })
12297    }
12298
12299    pub fn expand_excerpt(
12300        &mut self,
12301        excerpt: ExcerptId,
12302        direction: ExpandExcerptDirection,
12303        window: &mut Window,
12304        cx: &mut Context<Self>,
12305    ) {
12306        let current_scroll_position = self.scroll_position(cx);
12307        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
12308        self.buffer.update(cx, |buffer, cx| {
12309            buffer.expand_excerpts([excerpt], lines, direction, cx)
12310        });
12311        if direction == ExpandExcerptDirection::Down {
12312            let new_scroll_position = current_scroll_position + gpui::Point::new(0.0, lines as f32);
12313            self.set_scroll_position(new_scroll_position, window, cx);
12314        }
12315    }
12316
12317    pub fn go_to_singleton_buffer_point(
12318        &mut self,
12319        point: Point,
12320        window: &mut Window,
12321        cx: &mut Context<Self>,
12322    ) {
12323        self.go_to_singleton_buffer_range(point..point, window, cx);
12324    }
12325
12326    pub fn go_to_singleton_buffer_range(
12327        &mut self,
12328        range: Range<Point>,
12329        window: &mut Window,
12330        cx: &mut Context<Self>,
12331    ) {
12332        let multibuffer = self.buffer().read(cx);
12333        let Some(buffer) = multibuffer.as_singleton() else {
12334            return;
12335        };
12336        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
12337            return;
12338        };
12339        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
12340            return;
12341        };
12342        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
12343            s.select_anchor_ranges([start..end])
12344        });
12345    }
12346
12347    fn go_to_diagnostic(
12348        &mut self,
12349        _: &GoToDiagnostic,
12350        window: &mut Window,
12351        cx: &mut Context<Self>,
12352    ) {
12353        self.go_to_diagnostic_impl(Direction::Next, window, cx)
12354    }
12355
12356    fn go_to_prev_diagnostic(
12357        &mut self,
12358        _: &GoToPreviousDiagnostic,
12359        window: &mut Window,
12360        cx: &mut Context<Self>,
12361    ) {
12362        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
12363    }
12364
12365    pub fn go_to_diagnostic_impl(
12366        &mut self,
12367        direction: Direction,
12368        window: &mut Window,
12369        cx: &mut Context<Self>,
12370    ) {
12371        let buffer = self.buffer.read(cx).snapshot(cx);
12372        let selection = self.selections.newest::<usize>(cx);
12373
12374        // If there is an active Diagnostic Popover jump to its diagnostic instead.
12375        if direction == Direction::Next {
12376            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
12377                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
12378                    return;
12379                };
12380                self.activate_diagnostics(
12381                    buffer_id,
12382                    popover.local_diagnostic.diagnostic.group_id,
12383                    window,
12384                    cx,
12385                );
12386                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
12387                    let primary_range_start = active_diagnostics.primary_range.start;
12388                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12389                        let mut new_selection = s.newest_anchor().clone();
12390                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
12391                        s.select_anchors(vec![new_selection.clone()]);
12392                    });
12393                    self.refresh_inline_completion(false, true, window, cx);
12394                }
12395                return;
12396            }
12397        }
12398
12399        let active_group_id = self
12400            .active_diagnostics
12401            .as_ref()
12402            .map(|active_group| active_group.group_id);
12403        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
12404            active_diagnostics
12405                .primary_range
12406                .to_offset(&buffer)
12407                .to_inclusive()
12408        });
12409        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
12410            if active_primary_range.contains(&selection.head()) {
12411                *active_primary_range.start()
12412            } else {
12413                selection.head()
12414            }
12415        } else {
12416            selection.head()
12417        };
12418
12419        let snapshot = self.snapshot(window, cx);
12420        let primary_diagnostics_before = buffer
12421            .diagnostics_in_range::<usize>(0..search_start)
12422            .filter(|entry| entry.diagnostic.is_primary)
12423            .filter(|entry| entry.range.start != entry.range.end)
12424            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
12425            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
12426            .collect::<Vec<_>>();
12427        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
12428            primary_diagnostics_before
12429                .iter()
12430                .position(|entry| entry.diagnostic.group_id == active_group_id)
12431        });
12432
12433        let primary_diagnostics_after = buffer
12434            .diagnostics_in_range::<usize>(search_start..buffer.len())
12435            .filter(|entry| entry.diagnostic.is_primary)
12436            .filter(|entry| entry.range.start != entry.range.end)
12437            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
12438            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
12439            .collect::<Vec<_>>();
12440        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
12441            primary_diagnostics_after
12442                .iter()
12443                .enumerate()
12444                .rev()
12445                .find_map(|(i, entry)| {
12446                    if entry.diagnostic.group_id == active_group_id {
12447                        Some(i)
12448                    } else {
12449                        None
12450                    }
12451                })
12452        });
12453
12454        let next_primary_diagnostic = match direction {
12455            Direction::Prev => primary_diagnostics_before
12456                .iter()
12457                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
12458                .rev()
12459                .next(),
12460            Direction::Next => primary_diagnostics_after
12461                .iter()
12462                .skip(
12463                    last_same_group_diagnostic_after
12464                        .map(|index| index + 1)
12465                        .unwrap_or(0),
12466                )
12467                .next(),
12468        };
12469
12470        // Cycle around to the start of the buffer, potentially moving back to the start of
12471        // the currently active diagnostic.
12472        let cycle_around = || match direction {
12473            Direction::Prev => primary_diagnostics_after
12474                .iter()
12475                .rev()
12476                .chain(primary_diagnostics_before.iter().rev())
12477                .next(),
12478            Direction::Next => primary_diagnostics_before
12479                .iter()
12480                .chain(primary_diagnostics_after.iter())
12481                .next(),
12482        };
12483
12484        if let Some((primary_range, group_id)) = next_primary_diagnostic
12485            .or_else(cycle_around)
12486            .map(|entry| (&entry.range, entry.diagnostic.group_id))
12487        {
12488            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
12489                return;
12490            };
12491            self.activate_diagnostics(buffer_id, group_id, window, cx);
12492            if self.active_diagnostics.is_some() {
12493                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12494                    s.select(vec![Selection {
12495                        id: selection.id,
12496                        start: primary_range.start,
12497                        end: primary_range.start,
12498                        reversed: false,
12499                        goal: SelectionGoal::None,
12500                    }]);
12501                });
12502                self.refresh_inline_completion(false, true, window, cx);
12503            }
12504        }
12505    }
12506
12507    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
12508        let snapshot = self.snapshot(window, cx);
12509        let selection = self.selections.newest::<Point>(cx);
12510        self.go_to_hunk_before_or_after_position(
12511            &snapshot,
12512            selection.head(),
12513            Direction::Next,
12514            window,
12515            cx,
12516        );
12517    }
12518
12519    fn go_to_hunk_before_or_after_position(
12520        &mut self,
12521        snapshot: &EditorSnapshot,
12522        position: Point,
12523        direction: Direction,
12524        window: &mut Window,
12525        cx: &mut Context<Editor>,
12526    ) {
12527        let row = if direction == Direction::Next {
12528            self.hunk_after_position(snapshot, position)
12529                .map(|hunk| hunk.row_range.start)
12530        } else {
12531            self.hunk_before_position(snapshot, position)
12532        };
12533
12534        if let Some(row) = row {
12535            let destination = Point::new(row.0, 0);
12536            let autoscroll = Autoscroll::center();
12537
12538            self.unfold_ranges(&[destination..destination], false, false, cx);
12539            self.change_selections(Some(autoscroll), window, cx, |s| {
12540                s.select_ranges([destination..destination]);
12541            });
12542        }
12543    }
12544
12545    fn hunk_after_position(
12546        &mut self,
12547        snapshot: &EditorSnapshot,
12548        position: Point,
12549    ) -> Option<MultiBufferDiffHunk> {
12550        snapshot
12551            .buffer_snapshot
12552            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
12553            .find(|hunk| hunk.row_range.start.0 > position.row)
12554            .or_else(|| {
12555                snapshot
12556                    .buffer_snapshot
12557                    .diff_hunks_in_range(Point::zero()..position)
12558                    .find(|hunk| hunk.row_range.end.0 < position.row)
12559            })
12560    }
12561
12562    fn go_to_prev_hunk(
12563        &mut self,
12564        _: &GoToPreviousHunk,
12565        window: &mut Window,
12566        cx: &mut Context<Self>,
12567    ) {
12568        let snapshot = self.snapshot(window, cx);
12569        let selection = self.selections.newest::<Point>(cx);
12570        self.go_to_hunk_before_or_after_position(
12571            &snapshot,
12572            selection.head(),
12573            Direction::Prev,
12574            window,
12575            cx,
12576        );
12577    }
12578
12579    fn hunk_before_position(
12580        &mut self,
12581        snapshot: &EditorSnapshot,
12582        position: Point,
12583    ) -> Option<MultiBufferRow> {
12584        snapshot
12585            .buffer_snapshot
12586            .diff_hunk_before(position)
12587            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
12588    }
12589
12590    fn go_to_line<T: 'static>(
12591        &mut self,
12592        position: Anchor,
12593        highlight_color: Option<Hsla>,
12594        window: &mut Window,
12595        cx: &mut Context<Self>,
12596    ) {
12597        let snapshot = self.snapshot(window, cx).display_snapshot;
12598        let position = position.to_point(&snapshot.buffer_snapshot);
12599        let start = snapshot
12600            .buffer_snapshot
12601            .clip_point(Point::new(position.row, 0), Bias::Left);
12602        let end = start + Point::new(1, 0);
12603        let start = snapshot.buffer_snapshot.anchor_before(start);
12604        let end = snapshot.buffer_snapshot.anchor_before(end);
12605
12606        self.clear_row_highlights::<T>();
12607        self.highlight_rows::<T>(
12608            start..end,
12609            highlight_color
12610                .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
12611            true,
12612            cx,
12613        );
12614        self.request_autoscroll(Autoscroll::center(), cx);
12615    }
12616
12617    pub fn go_to_definition(
12618        &mut self,
12619        _: &GoToDefinition,
12620        window: &mut Window,
12621        cx: &mut Context<Self>,
12622    ) -> Task<Result<Navigated>> {
12623        let definition =
12624            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
12625        cx.spawn_in(window, async move |editor, cx| {
12626            if definition.await? == Navigated::Yes {
12627                return Ok(Navigated::Yes);
12628            }
12629            match editor.update_in(cx, |editor, window, cx| {
12630                editor.find_all_references(&FindAllReferences, window, cx)
12631            })? {
12632                Some(references) => references.await,
12633                None => Ok(Navigated::No),
12634            }
12635        })
12636    }
12637
12638    pub fn go_to_declaration(
12639        &mut self,
12640        _: &GoToDeclaration,
12641        window: &mut Window,
12642        cx: &mut Context<Self>,
12643    ) -> Task<Result<Navigated>> {
12644        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
12645    }
12646
12647    pub fn go_to_declaration_split(
12648        &mut self,
12649        _: &GoToDeclaration,
12650        window: &mut Window,
12651        cx: &mut Context<Self>,
12652    ) -> Task<Result<Navigated>> {
12653        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
12654    }
12655
12656    pub fn go_to_implementation(
12657        &mut self,
12658        _: &GoToImplementation,
12659        window: &mut Window,
12660        cx: &mut Context<Self>,
12661    ) -> Task<Result<Navigated>> {
12662        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
12663    }
12664
12665    pub fn go_to_implementation_split(
12666        &mut self,
12667        _: &GoToImplementationSplit,
12668        window: &mut Window,
12669        cx: &mut Context<Self>,
12670    ) -> Task<Result<Navigated>> {
12671        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
12672    }
12673
12674    pub fn go_to_type_definition(
12675        &mut self,
12676        _: &GoToTypeDefinition,
12677        window: &mut Window,
12678        cx: &mut Context<Self>,
12679    ) -> Task<Result<Navigated>> {
12680        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
12681    }
12682
12683    pub fn go_to_definition_split(
12684        &mut self,
12685        _: &GoToDefinitionSplit,
12686        window: &mut Window,
12687        cx: &mut Context<Self>,
12688    ) -> Task<Result<Navigated>> {
12689        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
12690    }
12691
12692    pub fn go_to_type_definition_split(
12693        &mut self,
12694        _: &GoToTypeDefinitionSplit,
12695        window: &mut Window,
12696        cx: &mut Context<Self>,
12697    ) -> Task<Result<Navigated>> {
12698        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
12699    }
12700
12701    fn go_to_definition_of_kind(
12702        &mut self,
12703        kind: GotoDefinitionKind,
12704        split: bool,
12705        window: &mut Window,
12706        cx: &mut Context<Self>,
12707    ) -> Task<Result<Navigated>> {
12708        let Some(provider) = self.semantics_provider.clone() else {
12709            return Task::ready(Ok(Navigated::No));
12710        };
12711        let head = self.selections.newest::<usize>(cx).head();
12712        let buffer = self.buffer.read(cx);
12713        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
12714            text_anchor
12715        } else {
12716            return Task::ready(Ok(Navigated::No));
12717        };
12718
12719        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
12720            return Task::ready(Ok(Navigated::No));
12721        };
12722
12723        cx.spawn_in(window, async move |editor, cx| {
12724            let definitions = definitions.await?;
12725            let navigated = editor
12726                .update_in(cx, |editor, window, cx| {
12727                    editor.navigate_to_hover_links(
12728                        Some(kind),
12729                        definitions
12730                            .into_iter()
12731                            .filter(|location| {
12732                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
12733                            })
12734                            .map(HoverLink::Text)
12735                            .collect::<Vec<_>>(),
12736                        split,
12737                        window,
12738                        cx,
12739                    )
12740                })?
12741                .await?;
12742            anyhow::Ok(navigated)
12743        })
12744    }
12745
12746    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
12747        let selection = self.selections.newest_anchor();
12748        let head = selection.head();
12749        let tail = selection.tail();
12750
12751        let Some((buffer, start_position)) =
12752            self.buffer.read(cx).text_anchor_for_position(head, cx)
12753        else {
12754            return;
12755        };
12756
12757        let end_position = if head != tail {
12758            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
12759                return;
12760            };
12761            Some(pos)
12762        } else {
12763            None
12764        };
12765
12766        let url_finder = cx.spawn_in(window, async move |editor, cx| {
12767            let url = if let Some(end_pos) = end_position {
12768                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
12769            } else {
12770                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
12771            };
12772
12773            if let Some(url) = url {
12774                editor.update(cx, |_, cx| {
12775                    cx.open_url(&url);
12776                })
12777            } else {
12778                Ok(())
12779            }
12780        });
12781
12782        url_finder.detach();
12783    }
12784
12785    pub fn open_selected_filename(
12786        &mut self,
12787        _: &OpenSelectedFilename,
12788        window: &mut Window,
12789        cx: &mut Context<Self>,
12790    ) {
12791        let Some(workspace) = self.workspace() else {
12792            return;
12793        };
12794
12795        let position = self.selections.newest_anchor().head();
12796
12797        let Some((buffer, buffer_position)) =
12798            self.buffer.read(cx).text_anchor_for_position(position, cx)
12799        else {
12800            return;
12801        };
12802
12803        let project = self.project.clone();
12804
12805        cx.spawn_in(window, async move |_, cx| {
12806            let result = find_file(&buffer, project, buffer_position, cx).await;
12807
12808            if let Some((_, path)) = result {
12809                workspace
12810                    .update_in(cx, |workspace, window, cx| {
12811                        workspace.open_resolved_path(path, window, cx)
12812                    })?
12813                    .await?;
12814            }
12815            anyhow::Ok(())
12816        })
12817        .detach();
12818    }
12819
12820    pub(crate) fn navigate_to_hover_links(
12821        &mut self,
12822        kind: Option<GotoDefinitionKind>,
12823        mut definitions: Vec<HoverLink>,
12824        split: bool,
12825        window: &mut Window,
12826        cx: &mut Context<Editor>,
12827    ) -> Task<Result<Navigated>> {
12828        // If there is one definition, just open it directly
12829        if definitions.len() == 1 {
12830            let definition = definitions.pop().unwrap();
12831
12832            enum TargetTaskResult {
12833                Location(Option<Location>),
12834                AlreadyNavigated,
12835            }
12836
12837            let target_task = match definition {
12838                HoverLink::Text(link) => {
12839                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
12840                }
12841                HoverLink::InlayHint(lsp_location, server_id) => {
12842                    let computation =
12843                        self.compute_target_location(lsp_location, server_id, window, cx);
12844                    cx.background_spawn(async move {
12845                        let location = computation.await?;
12846                        Ok(TargetTaskResult::Location(location))
12847                    })
12848                }
12849                HoverLink::Url(url) => {
12850                    cx.open_url(&url);
12851                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
12852                }
12853                HoverLink::File(path) => {
12854                    if let Some(workspace) = self.workspace() {
12855                        cx.spawn_in(window, async move |_, cx| {
12856                            workspace
12857                                .update_in(cx, |workspace, window, cx| {
12858                                    workspace.open_resolved_path(path, window, cx)
12859                                })?
12860                                .await
12861                                .map(|_| TargetTaskResult::AlreadyNavigated)
12862                        })
12863                    } else {
12864                        Task::ready(Ok(TargetTaskResult::Location(None)))
12865                    }
12866                }
12867            };
12868            cx.spawn_in(window, async move |editor, cx| {
12869                let target = match target_task.await.context("target resolution task")? {
12870                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
12871                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
12872                    TargetTaskResult::Location(Some(target)) => target,
12873                };
12874
12875                editor.update_in(cx, |editor, window, cx| {
12876                    let Some(workspace) = editor.workspace() else {
12877                        return Navigated::No;
12878                    };
12879                    let pane = workspace.read(cx).active_pane().clone();
12880
12881                    let range = target.range.to_point(target.buffer.read(cx));
12882                    let range = editor.range_for_match(&range);
12883                    let range = collapse_multiline_range(range);
12884
12885                    if !split
12886                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
12887                    {
12888                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
12889                    } else {
12890                        window.defer(cx, move |window, cx| {
12891                            let target_editor: Entity<Self> =
12892                                workspace.update(cx, |workspace, cx| {
12893                                    let pane = if split {
12894                                        workspace.adjacent_pane(window, cx)
12895                                    } else {
12896                                        workspace.active_pane().clone()
12897                                    };
12898
12899                                    workspace.open_project_item(
12900                                        pane,
12901                                        target.buffer.clone(),
12902                                        true,
12903                                        true,
12904                                        window,
12905                                        cx,
12906                                    )
12907                                });
12908                            target_editor.update(cx, |target_editor, cx| {
12909                                // When selecting a definition in a different buffer, disable the nav history
12910                                // to avoid creating a history entry at the previous cursor location.
12911                                pane.update(cx, |pane, _| pane.disable_history());
12912                                target_editor.go_to_singleton_buffer_range(range, window, cx);
12913                                pane.update(cx, |pane, _| pane.enable_history());
12914                            });
12915                        });
12916                    }
12917                    Navigated::Yes
12918                })
12919            })
12920        } else if !definitions.is_empty() {
12921            cx.spawn_in(window, async move |editor, cx| {
12922                let (title, location_tasks, workspace) = editor
12923                    .update_in(cx, |editor, window, cx| {
12924                        let tab_kind = match kind {
12925                            Some(GotoDefinitionKind::Implementation) => "Implementations",
12926                            _ => "Definitions",
12927                        };
12928                        let title = definitions
12929                            .iter()
12930                            .find_map(|definition| match definition {
12931                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
12932                                    let buffer = origin.buffer.read(cx);
12933                                    format!(
12934                                        "{} for {}",
12935                                        tab_kind,
12936                                        buffer
12937                                            .text_for_range(origin.range.clone())
12938                                            .collect::<String>()
12939                                    )
12940                                }),
12941                                HoverLink::InlayHint(_, _) => None,
12942                                HoverLink::Url(_) => None,
12943                                HoverLink::File(_) => None,
12944                            })
12945                            .unwrap_or(tab_kind.to_string());
12946                        let location_tasks = definitions
12947                            .into_iter()
12948                            .map(|definition| match definition {
12949                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
12950                                HoverLink::InlayHint(lsp_location, server_id) => editor
12951                                    .compute_target_location(lsp_location, server_id, window, cx),
12952                                HoverLink::Url(_) => Task::ready(Ok(None)),
12953                                HoverLink::File(_) => Task::ready(Ok(None)),
12954                            })
12955                            .collect::<Vec<_>>();
12956                        (title, location_tasks, editor.workspace().clone())
12957                    })
12958                    .context("location tasks preparation")?;
12959
12960                let locations = future::join_all(location_tasks)
12961                    .await
12962                    .into_iter()
12963                    .filter_map(|location| location.transpose())
12964                    .collect::<Result<_>>()
12965                    .context("location tasks")?;
12966
12967                let Some(workspace) = workspace else {
12968                    return Ok(Navigated::No);
12969                };
12970                let opened = workspace
12971                    .update_in(cx, |workspace, window, cx| {
12972                        Self::open_locations_in_multibuffer(
12973                            workspace,
12974                            locations,
12975                            title,
12976                            split,
12977                            MultibufferSelectionMode::First,
12978                            window,
12979                            cx,
12980                        )
12981                    })
12982                    .ok();
12983
12984                anyhow::Ok(Navigated::from_bool(opened.is_some()))
12985            })
12986        } else {
12987            Task::ready(Ok(Navigated::No))
12988        }
12989    }
12990
12991    fn compute_target_location(
12992        &self,
12993        lsp_location: lsp::Location,
12994        server_id: LanguageServerId,
12995        window: &mut Window,
12996        cx: &mut Context<Self>,
12997    ) -> Task<anyhow::Result<Option<Location>>> {
12998        let Some(project) = self.project.clone() else {
12999            return Task::ready(Ok(None));
13000        };
13001
13002        cx.spawn_in(window, async move |editor, cx| {
13003            let location_task = editor.update(cx, |_, cx| {
13004                project.update(cx, |project, cx| {
13005                    let language_server_name = project
13006                        .language_server_statuses(cx)
13007                        .find(|(id, _)| server_id == *id)
13008                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13009                    language_server_name.map(|language_server_name| {
13010                        project.open_local_buffer_via_lsp(
13011                            lsp_location.uri.clone(),
13012                            server_id,
13013                            language_server_name,
13014                            cx,
13015                        )
13016                    })
13017                })
13018            })?;
13019            let location = match location_task {
13020                Some(task) => Some({
13021                    let target_buffer_handle = task.await.context("open local buffer")?;
13022                    let range = target_buffer_handle.update(cx, |target_buffer, _| {
13023                        let target_start = target_buffer
13024                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13025                        let target_end = target_buffer
13026                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13027                        target_buffer.anchor_after(target_start)
13028                            ..target_buffer.anchor_before(target_end)
13029                    })?;
13030                    Location {
13031                        buffer: target_buffer_handle,
13032                        range,
13033                    }
13034                }),
13035                None => None,
13036            };
13037            Ok(location)
13038        })
13039    }
13040
13041    pub fn find_all_references(
13042        &mut self,
13043        _: &FindAllReferences,
13044        window: &mut Window,
13045        cx: &mut Context<Self>,
13046    ) -> Option<Task<Result<Navigated>>> {
13047        let selection = self.selections.newest::<usize>(cx);
13048        let multi_buffer = self.buffer.read(cx);
13049        let head = selection.head();
13050
13051        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13052        let head_anchor = multi_buffer_snapshot.anchor_at(
13053            head,
13054            if head < selection.tail() {
13055                Bias::Right
13056            } else {
13057                Bias::Left
13058            },
13059        );
13060
13061        match self
13062            .find_all_references_task_sources
13063            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13064        {
13065            Ok(_) => {
13066                log::info!(
13067                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
13068                );
13069                return None;
13070            }
13071            Err(i) => {
13072                self.find_all_references_task_sources.insert(i, head_anchor);
13073            }
13074        }
13075
13076        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13077        let workspace = self.workspace()?;
13078        let project = workspace.read(cx).project().clone();
13079        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13080        Some(cx.spawn_in(window, async move |editor, cx| {
13081            let _cleanup = cx.on_drop(&editor, move |editor, _| {
13082                if let Ok(i) = editor
13083                    .find_all_references_task_sources
13084                    .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13085                {
13086                    editor.find_all_references_task_sources.remove(i);
13087                }
13088            });
13089
13090            let locations = references.await?;
13091            if locations.is_empty() {
13092                return anyhow::Ok(Navigated::No);
13093            }
13094
13095            workspace.update_in(cx, |workspace, window, cx| {
13096                let title = locations
13097                    .first()
13098                    .as_ref()
13099                    .map(|location| {
13100                        let buffer = location.buffer.read(cx);
13101                        format!(
13102                            "References to `{}`",
13103                            buffer
13104                                .text_for_range(location.range.clone())
13105                                .collect::<String>()
13106                        )
13107                    })
13108                    .unwrap();
13109                Self::open_locations_in_multibuffer(
13110                    workspace,
13111                    locations,
13112                    title,
13113                    false,
13114                    MultibufferSelectionMode::First,
13115                    window,
13116                    cx,
13117                );
13118                Navigated::Yes
13119            })
13120        }))
13121    }
13122
13123    /// Opens a multibuffer with the given project locations in it
13124    pub fn open_locations_in_multibuffer(
13125        workspace: &mut Workspace,
13126        mut locations: Vec<Location>,
13127        title: String,
13128        split: bool,
13129        multibuffer_selection_mode: MultibufferSelectionMode,
13130        window: &mut Window,
13131        cx: &mut Context<Workspace>,
13132    ) {
13133        // If there are multiple definitions, open them in a multibuffer
13134        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13135        let mut locations = locations.into_iter().peekable();
13136        let mut ranges = Vec::new();
13137        let capability = workspace.project().read(cx).capability();
13138
13139        let excerpt_buffer = cx.new(|cx| {
13140            let mut multibuffer = MultiBuffer::new(capability);
13141            while let Some(location) = locations.next() {
13142                let buffer = location.buffer.read(cx);
13143                let mut ranges_for_buffer = Vec::new();
13144                let range = location.range.to_offset(buffer);
13145                ranges_for_buffer.push(range.clone());
13146
13147                while let Some(next_location) = locations.peek() {
13148                    if next_location.buffer == location.buffer {
13149                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
13150                        locations.next();
13151                    } else {
13152                        break;
13153                    }
13154                }
13155
13156                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
13157                ranges.extend(multibuffer.push_excerpts_with_context_lines(
13158                    location.buffer.clone(),
13159                    ranges_for_buffer,
13160                    DEFAULT_MULTIBUFFER_CONTEXT,
13161                    cx,
13162                ))
13163            }
13164
13165            multibuffer.with_title(title)
13166        });
13167
13168        let editor = cx.new(|cx| {
13169            Editor::for_multibuffer(
13170                excerpt_buffer,
13171                Some(workspace.project().clone()),
13172                window,
13173                cx,
13174            )
13175        });
13176        editor.update(cx, |editor, cx| {
13177            match multibuffer_selection_mode {
13178                MultibufferSelectionMode::First => {
13179                    if let Some(first_range) = ranges.first() {
13180                        editor.change_selections(None, window, cx, |selections| {
13181                            selections.clear_disjoint();
13182                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
13183                        });
13184                    }
13185                    editor.highlight_background::<Self>(
13186                        &ranges,
13187                        |theme| theme.editor_highlighted_line_background,
13188                        cx,
13189                    );
13190                }
13191                MultibufferSelectionMode::All => {
13192                    editor.change_selections(None, window, cx, |selections| {
13193                        selections.clear_disjoint();
13194                        selections.select_anchor_ranges(ranges);
13195                    });
13196                }
13197            }
13198            editor.register_buffers_with_language_servers(cx);
13199        });
13200
13201        let item = Box::new(editor);
13202        let item_id = item.item_id();
13203
13204        if split {
13205            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
13206        } else {
13207            if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
13208                let (preview_item_id, preview_item_idx) =
13209                    workspace.active_pane().update(cx, |pane, _| {
13210                        (pane.preview_item_id(), pane.preview_item_idx())
13211                    });
13212
13213                workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
13214
13215                if let Some(preview_item_id) = preview_item_id {
13216                    workspace.active_pane().update(cx, |pane, cx| {
13217                        pane.remove_item(preview_item_id, false, false, window, cx);
13218                    });
13219                }
13220            } else {
13221                workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
13222            }
13223        }
13224        workspace.active_pane().update(cx, |pane, cx| {
13225            pane.set_preview_item_id(Some(item_id), cx);
13226        });
13227    }
13228
13229    pub fn rename(
13230        &mut self,
13231        _: &Rename,
13232        window: &mut Window,
13233        cx: &mut Context<Self>,
13234    ) -> Option<Task<Result<()>>> {
13235        use language::ToOffset as _;
13236
13237        let provider = self.semantics_provider.clone()?;
13238        let selection = self.selections.newest_anchor().clone();
13239        let (cursor_buffer, cursor_buffer_position) = self
13240            .buffer
13241            .read(cx)
13242            .text_anchor_for_position(selection.head(), cx)?;
13243        let (tail_buffer, cursor_buffer_position_end) = self
13244            .buffer
13245            .read(cx)
13246            .text_anchor_for_position(selection.tail(), cx)?;
13247        if tail_buffer != cursor_buffer {
13248            return None;
13249        }
13250
13251        let snapshot = cursor_buffer.read(cx).snapshot();
13252        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
13253        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
13254        let prepare_rename = provider
13255            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
13256            .unwrap_or_else(|| Task::ready(Ok(None)));
13257        drop(snapshot);
13258
13259        Some(cx.spawn_in(window, async move |this, cx| {
13260            let rename_range = if let Some(range) = prepare_rename.await? {
13261                Some(range)
13262            } else {
13263                this.update(cx, |this, cx| {
13264                    let buffer = this.buffer.read(cx).snapshot(cx);
13265                    let mut buffer_highlights = this
13266                        .document_highlights_for_position(selection.head(), &buffer)
13267                        .filter(|highlight| {
13268                            highlight.start.excerpt_id == selection.head().excerpt_id
13269                                && highlight.end.excerpt_id == selection.head().excerpt_id
13270                        });
13271                    buffer_highlights
13272                        .next()
13273                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
13274                })?
13275            };
13276            if let Some(rename_range) = rename_range {
13277                this.update_in(cx, |this, window, cx| {
13278                    let snapshot = cursor_buffer.read(cx).snapshot();
13279                    let rename_buffer_range = rename_range.to_offset(&snapshot);
13280                    let cursor_offset_in_rename_range =
13281                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
13282                    let cursor_offset_in_rename_range_end =
13283                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
13284
13285                    this.take_rename(false, window, cx);
13286                    let buffer = this.buffer.read(cx).read(cx);
13287                    let cursor_offset = selection.head().to_offset(&buffer);
13288                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
13289                    let rename_end = rename_start + rename_buffer_range.len();
13290                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
13291                    let mut old_highlight_id = None;
13292                    let old_name: Arc<str> = buffer
13293                        .chunks(rename_start..rename_end, true)
13294                        .map(|chunk| {
13295                            if old_highlight_id.is_none() {
13296                                old_highlight_id = chunk.syntax_highlight_id;
13297                            }
13298                            chunk.text
13299                        })
13300                        .collect::<String>()
13301                        .into();
13302
13303                    drop(buffer);
13304
13305                    // Position the selection in the rename editor so that it matches the current selection.
13306                    this.show_local_selections = false;
13307                    let rename_editor = cx.new(|cx| {
13308                        let mut editor = Editor::single_line(window, cx);
13309                        editor.buffer.update(cx, |buffer, cx| {
13310                            buffer.edit([(0..0, old_name.clone())], None, cx)
13311                        });
13312                        let rename_selection_range = match cursor_offset_in_rename_range
13313                            .cmp(&cursor_offset_in_rename_range_end)
13314                        {
13315                            Ordering::Equal => {
13316                                editor.select_all(&SelectAll, window, cx);
13317                                return editor;
13318                            }
13319                            Ordering::Less => {
13320                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
13321                            }
13322                            Ordering::Greater => {
13323                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
13324                            }
13325                        };
13326                        if rename_selection_range.end > old_name.len() {
13327                            editor.select_all(&SelectAll, window, cx);
13328                        } else {
13329                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13330                                s.select_ranges([rename_selection_range]);
13331                            });
13332                        }
13333                        editor
13334                    });
13335                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
13336                        if e == &EditorEvent::Focused {
13337                            cx.emit(EditorEvent::FocusedIn)
13338                        }
13339                    })
13340                    .detach();
13341
13342                    let write_highlights =
13343                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
13344                    let read_highlights =
13345                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
13346                    let ranges = write_highlights
13347                        .iter()
13348                        .flat_map(|(_, ranges)| ranges.iter())
13349                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
13350                        .cloned()
13351                        .collect();
13352
13353                    this.highlight_text::<Rename>(
13354                        ranges,
13355                        HighlightStyle {
13356                            fade_out: Some(0.6),
13357                            ..Default::default()
13358                        },
13359                        cx,
13360                    );
13361                    let rename_focus_handle = rename_editor.focus_handle(cx);
13362                    window.focus(&rename_focus_handle);
13363                    let block_id = this.insert_blocks(
13364                        [BlockProperties {
13365                            style: BlockStyle::Flex,
13366                            placement: BlockPlacement::Below(range.start),
13367                            height: 1,
13368                            render: Arc::new({
13369                                let rename_editor = rename_editor.clone();
13370                                move |cx: &mut BlockContext| {
13371                                    let mut text_style = cx.editor_style.text.clone();
13372                                    if let Some(highlight_style) = old_highlight_id
13373                                        .and_then(|h| h.style(&cx.editor_style.syntax))
13374                                    {
13375                                        text_style = text_style.highlight(highlight_style);
13376                                    }
13377                                    div()
13378                                        .block_mouse_down()
13379                                        .pl(cx.anchor_x)
13380                                        .child(EditorElement::new(
13381                                            &rename_editor,
13382                                            EditorStyle {
13383                                                background: cx.theme().system().transparent,
13384                                                local_player: cx.editor_style.local_player,
13385                                                text: text_style,
13386                                                scrollbar_width: cx.editor_style.scrollbar_width,
13387                                                syntax: cx.editor_style.syntax.clone(),
13388                                                status: cx.editor_style.status.clone(),
13389                                                inlay_hints_style: HighlightStyle {
13390                                                    font_weight: Some(FontWeight::BOLD),
13391                                                    ..make_inlay_hints_style(cx.app)
13392                                                },
13393                                                inline_completion_styles: make_suggestion_styles(
13394                                                    cx.app,
13395                                                ),
13396                                                ..EditorStyle::default()
13397                                            },
13398                                        ))
13399                                        .into_any_element()
13400                                }
13401                            }),
13402                            priority: 0,
13403                        }],
13404                        Some(Autoscroll::fit()),
13405                        cx,
13406                    )[0];
13407                    this.pending_rename = Some(RenameState {
13408                        range,
13409                        old_name,
13410                        editor: rename_editor,
13411                        block_id,
13412                    });
13413                })?;
13414            }
13415
13416            Ok(())
13417        }))
13418    }
13419
13420    pub fn confirm_rename(
13421        &mut self,
13422        _: &ConfirmRename,
13423        window: &mut Window,
13424        cx: &mut Context<Self>,
13425    ) -> Option<Task<Result<()>>> {
13426        let rename = self.take_rename(false, window, cx)?;
13427        let workspace = self.workspace()?.downgrade();
13428        let (buffer, start) = self
13429            .buffer
13430            .read(cx)
13431            .text_anchor_for_position(rename.range.start, cx)?;
13432        let (end_buffer, _) = self
13433            .buffer
13434            .read(cx)
13435            .text_anchor_for_position(rename.range.end, cx)?;
13436        if buffer != end_buffer {
13437            return None;
13438        }
13439
13440        let old_name = rename.old_name;
13441        let new_name = rename.editor.read(cx).text(cx);
13442
13443        let rename = self.semantics_provider.as_ref()?.perform_rename(
13444            &buffer,
13445            start,
13446            new_name.clone(),
13447            cx,
13448        )?;
13449
13450        Some(cx.spawn_in(window, async move |editor, cx| {
13451            let project_transaction = rename.await?;
13452            Self::open_project_transaction(
13453                &editor,
13454                workspace,
13455                project_transaction,
13456                format!("Rename: {}{}", old_name, new_name),
13457                cx,
13458            )
13459            .await?;
13460
13461            editor.update(cx, |editor, cx| {
13462                editor.refresh_document_highlights(cx);
13463            })?;
13464            Ok(())
13465        }))
13466    }
13467
13468    fn take_rename(
13469        &mut self,
13470        moving_cursor: bool,
13471        window: &mut Window,
13472        cx: &mut Context<Self>,
13473    ) -> Option<RenameState> {
13474        let rename = self.pending_rename.take()?;
13475        if rename.editor.focus_handle(cx).is_focused(window) {
13476            window.focus(&self.focus_handle);
13477        }
13478
13479        self.remove_blocks(
13480            [rename.block_id].into_iter().collect(),
13481            Some(Autoscroll::fit()),
13482            cx,
13483        );
13484        self.clear_highlights::<Rename>(cx);
13485        self.show_local_selections = true;
13486
13487        if moving_cursor {
13488            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
13489                editor.selections.newest::<usize>(cx).head()
13490            });
13491
13492            // Update the selection to match the position of the selection inside
13493            // the rename editor.
13494            let snapshot = self.buffer.read(cx).read(cx);
13495            let rename_range = rename.range.to_offset(&snapshot);
13496            let cursor_in_editor = snapshot
13497                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
13498                .min(rename_range.end);
13499            drop(snapshot);
13500
13501            self.change_selections(None, window, cx, |s| {
13502                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
13503            });
13504        } else {
13505            self.refresh_document_highlights(cx);
13506        }
13507
13508        Some(rename)
13509    }
13510
13511    pub fn pending_rename(&self) -> Option<&RenameState> {
13512        self.pending_rename.as_ref()
13513    }
13514
13515    fn format(
13516        &mut self,
13517        _: &Format,
13518        window: &mut Window,
13519        cx: &mut Context<Self>,
13520    ) -> Option<Task<Result<()>>> {
13521        let project = match &self.project {
13522            Some(project) => project.clone(),
13523            None => return None,
13524        };
13525
13526        Some(self.perform_format(
13527            project,
13528            FormatTrigger::Manual,
13529            FormatTarget::Buffers,
13530            window,
13531            cx,
13532        ))
13533    }
13534
13535    fn format_selections(
13536        &mut self,
13537        _: &FormatSelections,
13538        window: &mut Window,
13539        cx: &mut Context<Self>,
13540    ) -> Option<Task<Result<()>>> {
13541        let project = match &self.project {
13542            Some(project) => project.clone(),
13543            None => return None,
13544        };
13545
13546        let ranges = self
13547            .selections
13548            .all_adjusted(cx)
13549            .into_iter()
13550            .map(|selection| selection.range())
13551            .collect_vec();
13552
13553        Some(self.perform_format(
13554            project,
13555            FormatTrigger::Manual,
13556            FormatTarget::Ranges(ranges),
13557            window,
13558            cx,
13559        ))
13560    }
13561
13562    fn perform_format(
13563        &mut self,
13564        project: Entity<Project>,
13565        trigger: FormatTrigger,
13566        target: FormatTarget,
13567        window: &mut Window,
13568        cx: &mut Context<Self>,
13569    ) -> Task<Result<()>> {
13570        let buffer = self.buffer.clone();
13571        let (buffers, target) = match target {
13572            FormatTarget::Buffers => {
13573                let mut buffers = buffer.read(cx).all_buffers();
13574                if trigger == FormatTrigger::Save {
13575                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
13576                }
13577                (buffers, LspFormatTarget::Buffers)
13578            }
13579            FormatTarget::Ranges(selection_ranges) => {
13580                let multi_buffer = buffer.read(cx);
13581                let snapshot = multi_buffer.read(cx);
13582                let mut buffers = HashSet::default();
13583                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
13584                    BTreeMap::new();
13585                for selection_range in selection_ranges {
13586                    for (buffer, buffer_range, _) in
13587                        snapshot.range_to_buffer_ranges(selection_range)
13588                    {
13589                        let buffer_id = buffer.remote_id();
13590                        let start = buffer.anchor_before(buffer_range.start);
13591                        let end = buffer.anchor_after(buffer_range.end);
13592                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
13593                        buffer_id_to_ranges
13594                            .entry(buffer_id)
13595                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
13596                            .or_insert_with(|| vec![start..end]);
13597                    }
13598                }
13599                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
13600            }
13601        };
13602
13603        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
13604        let format = project.update(cx, |project, cx| {
13605            project.format(buffers, target, true, trigger, cx)
13606        });
13607
13608        cx.spawn_in(window, async move |_, cx| {
13609            let transaction = futures::select_biased! {
13610                transaction = format.log_err().fuse() => transaction,
13611                () = timeout => {
13612                    log::warn!("timed out waiting for formatting");
13613                    None
13614                }
13615            };
13616
13617            buffer
13618                .update(cx, |buffer, cx| {
13619                    if let Some(transaction) = transaction {
13620                        if !buffer.is_singleton() {
13621                            buffer.push_transaction(&transaction.0, cx);
13622                        }
13623                    }
13624                    cx.notify();
13625                })
13626                .ok();
13627
13628            Ok(())
13629        })
13630    }
13631
13632    fn organize_imports(
13633        &mut self,
13634        _: &OrganizeImports,
13635        window: &mut Window,
13636        cx: &mut Context<Self>,
13637    ) -> Option<Task<Result<()>>> {
13638        let project = match &self.project {
13639            Some(project) => project.clone(),
13640            None => return None,
13641        };
13642        Some(self.perform_code_action_kind(
13643            project,
13644            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
13645            window,
13646            cx,
13647        ))
13648    }
13649
13650    fn perform_code_action_kind(
13651        &mut self,
13652        project: Entity<Project>,
13653        kind: CodeActionKind,
13654        window: &mut Window,
13655        cx: &mut Context<Self>,
13656    ) -> Task<Result<()>> {
13657        let buffer = self.buffer.clone();
13658        let buffers = buffer.read(cx).all_buffers();
13659        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
13660        let apply_action = project.update(cx, |project, cx| {
13661            project.apply_code_action_kind(buffers, kind, true, cx)
13662        });
13663        cx.spawn_in(window, async move |_, cx| {
13664            let transaction = futures::select_biased! {
13665                () = timeout => {
13666                    log::warn!("timed out waiting for executing code action");
13667                    None
13668                }
13669                transaction = apply_action.log_err().fuse() => transaction,
13670            };
13671            buffer
13672                .update(cx, |buffer, cx| {
13673                    // check if we need this
13674                    if let Some(transaction) = transaction {
13675                        if !buffer.is_singleton() {
13676                            buffer.push_transaction(&transaction.0, cx);
13677                        }
13678                    }
13679                    cx.notify();
13680                })
13681                .ok();
13682            Ok(())
13683        })
13684    }
13685
13686    fn restart_language_server(
13687        &mut self,
13688        _: &RestartLanguageServer,
13689        _: &mut Window,
13690        cx: &mut Context<Self>,
13691    ) {
13692        if let Some(project) = self.project.clone() {
13693            self.buffer.update(cx, |multi_buffer, cx| {
13694                project.update(cx, |project, cx| {
13695                    project.restart_language_servers_for_buffers(
13696                        multi_buffer.all_buffers().into_iter().collect(),
13697                        cx,
13698                    );
13699                });
13700            })
13701        }
13702    }
13703
13704    fn cancel_language_server_work(
13705        workspace: &mut Workspace,
13706        _: &actions::CancelLanguageServerWork,
13707        _: &mut Window,
13708        cx: &mut Context<Workspace>,
13709    ) {
13710        let project = workspace.project();
13711        let buffers = workspace
13712            .active_item(cx)
13713            .and_then(|item| item.act_as::<Editor>(cx))
13714            .map_or(HashSet::default(), |editor| {
13715                editor.read(cx).buffer.read(cx).all_buffers()
13716            });
13717        project.update(cx, |project, cx| {
13718            project.cancel_language_server_work_for_buffers(buffers, cx);
13719        });
13720    }
13721
13722    fn show_character_palette(
13723        &mut self,
13724        _: &ShowCharacterPalette,
13725        window: &mut Window,
13726        _: &mut Context<Self>,
13727    ) {
13728        window.show_character_palette();
13729    }
13730
13731    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
13732        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
13733            let buffer = self.buffer.read(cx).snapshot(cx);
13734            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
13735            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
13736            let is_valid = buffer
13737                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
13738                .any(|entry| {
13739                    entry.diagnostic.is_primary
13740                        && !entry.range.is_empty()
13741                        && entry.range.start == primary_range_start
13742                        && entry.diagnostic.message == active_diagnostics.primary_message
13743                });
13744
13745            if is_valid != active_diagnostics.is_valid {
13746                active_diagnostics.is_valid = is_valid;
13747                if is_valid {
13748                    let mut new_styles = HashMap::default();
13749                    for (block_id, diagnostic) in &active_diagnostics.blocks {
13750                        new_styles.insert(
13751                            *block_id,
13752                            diagnostic_block_renderer(diagnostic.clone(), None, true),
13753                        );
13754                    }
13755                    self.display_map.update(cx, |display_map, _cx| {
13756                        display_map.replace_blocks(new_styles);
13757                    });
13758                } else {
13759                    self.dismiss_diagnostics(cx);
13760                }
13761            }
13762        }
13763    }
13764
13765    fn activate_diagnostics(
13766        &mut self,
13767        buffer_id: BufferId,
13768        group_id: usize,
13769        window: &mut Window,
13770        cx: &mut Context<Self>,
13771    ) {
13772        self.dismiss_diagnostics(cx);
13773        let snapshot = self.snapshot(window, cx);
13774        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
13775            let buffer = self.buffer.read(cx).snapshot(cx);
13776
13777            let mut primary_range = None;
13778            let mut primary_message = None;
13779            let diagnostic_group = buffer
13780                .diagnostic_group(buffer_id, group_id)
13781                .filter_map(|entry| {
13782                    let start = entry.range.start;
13783                    let end = entry.range.end;
13784                    if snapshot.is_line_folded(MultiBufferRow(start.row))
13785                        && (start.row == end.row
13786                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
13787                    {
13788                        return None;
13789                    }
13790                    if entry.diagnostic.is_primary {
13791                        primary_range = Some(entry.range.clone());
13792                        primary_message = Some(entry.diagnostic.message.clone());
13793                    }
13794                    Some(entry)
13795                })
13796                .collect::<Vec<_>>();
13797            let primary_range = primary_range?;
13798            let primary_message = primary_message?;
13799
13800            let blocks = display_map
13801                .insert_blocks(
13802                    diagnostic_group.iter().map(|entry| {
13803                        let diagnostic = entry.diagnostic.clone();
13804                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
13805                        BlockProperties {
13806                            style: BlockStyle::Fixed,
13807                            placement: BlockPlacement::Below(
13808                                buffer.anchor_after(entry.range.start),
13809                            ),
13810                            height: message_height,
13811                            render: diagnostic_block_renderer(diagnostic, None, true),
13812                            priority: 0,
13813                        }
13814                    }),
13815                    cx,
13816                )
13817                .into_iter()
13818                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
13819                .collect();
13820
13821            Some(ActiveDiagnosticGroup {
13822                primary_range: buffer.anchor_before(primary_range.start)
13823                    ..buffer.anchor_after(primary_range.end),
13824                primary_message,
13825                group_id,
13826                blocks,
13827                is_valid: true,
13828            })
13829        });
13830    }
13831
13832    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
13833        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
13834            self.display_map.update(cx, |display_map, cx| {
13835                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
13836            });
13837            cx.notify();
13838        }
13839    }
13840
13841    /// Disable inline diagnostics rendering for this editor.
13842    pub fn disable_inline_diagnostics(&mut self) {
13843        self.inline_diagnostics_enabled = false;
13844        self.inline_diagnostics_update = Task::ready(());
13845        self.inline_diagnostics.clear();
13846    }
13847
13848    pub fn inline_diagnostics_enabled(&self) -> bool {
13849        self.inline_diagnostics_enabled
13850    }
13851
13852    pub fn show_inline_diagnostics(&self) -> bool {
13853        self.show_inline_diagnostics
13854    }
13855
13856    pub fn toggle_inline_diagnostics(
13857        &mut self,
13858        _: &ToggleInlineDiagnostics,
13859        window: &mut Window,
13860        cx: &mut Context<'_, Editor>,
13861    ) {
13862        self.show_inline_diagnostics = !self.show_inline_diagnostics;
13863        self.refresh_inline_diagnostics(false, window, cx);
13864    }
13865
13866    fn refresh_inline_diagnostics(
13867        &mut self,
13868        debounce: bool,
13869        window: &mut Window,
13870        cx: &mut Context<Self>,
13871    ) {
13872        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
13873            self.inline_diagnostics_update = Task::ready(());
13874            self.inline_diagnostics.clear();
13875            return;
13876        }
13877
13878        let debounce_ms = ProjectSettings::get_global(cx)
13879            .diagnostics
13880            .inline
13881            .update_debounce_ms;
13882        let debounce = if debounce && debounce_ms > 0 {
13883            Some(Duration::from_millis(debounce_ms))
13884        } else {
13885            None
13886        };
13887        self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
13888            if let Some(debounce) = debounce {
13889                cx.background_executor().timer(debounce).await;
13890            }
13891            let Some(snapshot) = editor
13892                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
13893                .ok()
13894            else {
13895                return;
13896            };
13897
13898            let new_inline_diagnostics = cx
13899                .background_spawn(async move {
13900                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
13901                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
13902                        let message = diagnostic_entry
13903                            .diagnostic
13904                            .message
13905                            .split_once('\n')
13906                            .map(|(line, _)| line)
13907                            .map(SharedString::new)
13908                            .unwrap_or_else(|| {
13909                                SharedString::from(diagnostic_entry.diagnostic.message)
13910                            });
13911                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
13912                        let (Ok(i) | Err(i)) = inline_diagnostics
13913                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
13914                        inline_diagnostics.insert(
13915                            i,
13916                            (
13917                                start_anchor,
13918                                InlineDiagnostic {
13919                                    message,
13920                                    group_id: diagnostic_entry.diagnostic.group_id,
13921                                    start: diagnostic_entry.range.start.to_point(&snapshot),
13922                                    is_primary: diagnostic_entry.diagnostic.is_primary,
13923                                    severity: diagnostic_entry.diagnostic.severity,
13924                                },
13925                            ),
13926                        );
13927                    }
13928                    inline_diagnostics
13929                })
13930                .await;
13931
13932            editor
13933                .update(cx, |editor, cx| {
13934                    editor.inline_diagnostics = new_inline_diagnostics;
13935                    cx.notify();
13936                })
13937                .ok();
13938        });
13939    }
13940
13941    pub fn set_selections_from_remote(
13942        &mut self,
13943        selections: Vec<Selection<Anchor>>,
13944        pending_selection: Option<Selection<Anchor>>,
13945        window: &mut Window,
13946        cx: &mut Context<Self>,
13947    ) {
13948        let old_cursor_position = self.selections.newest_anchor().head();
13949        self.selections.change_with(cx, |s| {
13950            s.select_anchors(selections);
13951            if let Some(pending_selection) = pending_selection {
13952                s.set_pending(pending_selection, SelectMode::Character);
13953            } else {
13954                s.clear_pending();
13955            }
13956        });
13957        self.selections_did_change(false, &old_cursor_position, true, window, cx);
13958    }
13959
13960    fn push_to_selection_history(&mut self) {
13961        self.selection_history.push(SelectionHistoryEntry {
13962            selections: self.selections.disjoint_anchors(),
13963            select_next_state: self.select_next_state.clone(),
13964            select_prev_state: self.select_prev_state.clone(),
13965            add_selections_state: self.add_selections_state.clone(),
13966        });
13967    }
13968
13969    pub fn transact(
13970        &mut self,
13971        window: &mut Window,
13972        cx: &mut Context<Self>,
13973        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
13974    ) -> Option<TransactionId> {
13975        self.start_transaction_at(Instant::now(), window, cx);
13976        update(self, window, cx);
13977        self.end_transaction_at(Instant::now(), cx)
13978    }
13979
13980    pub fn start_transaction_at(
13981        &mut self,
13982        now: Instant,
13983        window: &mut Window,
13984        cx: &mut Context<Self>,
13985    ) {
13986        self.end_selection(window, cx);
13987        if let Some(tx_id) = self
13988            .buffer
13989            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
13990        {
13991            self.selection_history
13992                .insert_transaction(tx_id, self.selections.disjoint_anchors());
13993            cx.emit(EditorEvent::TransactionBegun {
13994                transaction_id: tx_id,
13995            })
13996        }
13997    }
13998
13999    pub fn end_transaction_at(
14000        &mut self,
14001        now: Instant,
14002        cx: &mut Context<Self>,
14003    ) -> Option<TransactionId> {
14004        if let Some(transaction_id) = self
14005            .buffer
14006            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14007        {
14008            if let Some((_, end_selections)) =
14009                self.selection_history.transaction_mut(transaction_id)
14010            {
14011                *end_selections = Some(self.selections.disjoint_anchors());
14012            } else {
14013                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14014            }
14015
14016            cx.emit(EditorEvent::Edited { transaction_id });
14017            Some(transaction_id)
14018        } else {
14019            None
14020        }
14021    }
14022
14023    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14024        if self.selection_mark_mode {
14025            self.change_selections(None, window, cx, |s| {
14026                s.move_with(|_, sel| {
14027                    sel.collapse_to(sel.head(), SelectionGoal::None);
14028                });
14029            })
14030        }
14031        self.selection_mark_mode = true;
14032        cx.notify();
14033    }
14034
14035    pub fn swap_selection_ends(
14036        &mut self,
14037        _: &actions::SwapSelectionEnds,
14038        window: &mut Window,
14039        cx: &mut Context<Self>,
14040    ) {
14041        self.change_selections(None, window, cx, |s| {
14042            s.move_with(|_, sel| {
14043                if sel.start != sel.end {
14044                    sel.reversed = !sel.reversed
14045                }
14046            });
14047        });
14048        self.request_autoscroll(Autoscroll::newest(), cx);
14049        cx.notify();
14050    }
14051
14052    pub fn toggle_fold(
14053        &mut self,
14054        _: &actions::ToggleFold,
14055        window: &mut Window,
14056        cx: &mut Context<Self>,
14057    ) {
14058        if self.is_singleton(cx) {
14059            let selection = self.selections.newest::<Point>(cx);
14060
14061            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14062            let range = if selection.is_empty() {
14063                let point = selection.head().to_display_point(&display_map);
14064                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14065                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14066                    .to_point(&display_map);
14067                start..end
14068            } else {
14069                selection.range()
14070            };
14071            if display_map.folds_in_range(range).next().is_some() {
14072                self.unfold_lines(&Default::default(), window, cx)
14073            } else {
14074                self.fold(&Default::default(), window, cx)
14075            }
14076        } else {
14077            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14078            let buffer_ids: HashSet<_> = self
14079                .selections
14080                .disjoint_anchor_ranges()
14081                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14082                .collect();
14083
14084            let should_unfold = buffer_ids
14085                .iter()
14086                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14087
14088            for buffer_id in buffer_ids {
14089                if should_unfold {
14090                    self.unfold_buffer(buffer_id, cx);
14091                } else {
14092                    self.fold_buffer(buffer_id, cx);
14093                }
14094            }
14095        }
14096    }
14097
14098    pub fn toggle_fold_recursive(
14099        &mut self,
14100        _: &actions::ToggleFoldRecursive,
14101        window: &mut Window,
14102        cx: &mut Context<Self>,
14103    ) {
14104        let selection = self.selections.newest::<Point>(cx);
14105
14106        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14107        let range = if selection.is_empty() {
14108            let point = selection.head().to_display_point(&display_map);
14109            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14110            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14111                .to_point(&display_map);
14112            start..end
14113        } else {
14114            selection.range()
14115        };
14116        if display_map.folds_in_range(range).next().is_some() {
14117            self.unfold_recursive(&Default::default(), window, cx)
14118        } else {
14119            self.fold_recursive(&Default::default(), window, cx)
14120        }
14121    }
14122
14123    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
14124        if self.is_singleton(cx) {
14125            let mut to_fold = Vec::new();
14126            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14127            let selections = self.selections.all_adjusted(cx);
14128
14129            for selection in selections {
14130                let range = selection.range().sorted();
14131                let buffer_start_row = range.start.row;
14132
14133                if range.start.row != range.end.row {
14134                    let mut found = false;
14135                    let mut row = range.start.row;
14136                    while row <= range.end.row {
14137                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
14138                        {
14139                            found = true;
14140                            row = crease.range().end.row + 1;
14141                            to_fold.push(crease);
14142                        } else {
14143                            row += 1
14144                        }
14145                    }
14146                    if found {
14147                        continue;
14148                    }
14149                }
14150
14151                for row in (0..=range.start.row).rev() {
14152                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14153                        if crease.range().end.row >= buffer_start_row {
14154                            to_fold.push(crease);
14155                            if row <= range.start.row {
14156                                break;
14157                            }
14158                        }
14159                    }
14160                }
14161            }
14162
14163            self.fold_creases(to_fold, true, window, cx);
14164        } else {
14165            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14166            let buffer_ids = self
14167                .selections
14168                .disjoint_anchor_ranges()
14169                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14170                .collect::<HashSet<_>>();
14171            for buffer_id in buffer_ids {
14172                self.fold_buffer(buffer_id, cx);
14173            }
14174        }
14175    }
14176
14177    fn fold_at_level(
14178        &mut self,
14179        fold_at: &FoldAtLevel,
14180        window: &mut Window,
14181        cx: &mut Context<Self>,
14182    ) {
14183        if !self.buffer.read(cx).is_singleton() {
14184            return;
14185        }
14186
14187        let fold_at_level = fold_at.0;
14188        let snapshot = self.buffer.read(cx).snapshot(cx);
14189        let mut to_fold = Vec::new();
14190        let mut stack = vec![(0, snapshot.max_row().0, 1)];
14191
14192        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
14193            while start_row < end_row {
14194                match self
14195                    .snapshot(window, cx)
14196                    .crease_for_buffer_row(MultiBufferRow(start_row))
14197                {
14198                    Some(crease) => {
14199                        let nested_start_row = crease.range().start.row + 1;
14200                        let nested_end_row = crease.range().end.row;
14201
14202                        if current_level < fold_at_level {
14203                            stack.push((nested_start_row, nested_end_row, current_level + 1));
14204                        } else if current_level == fold_at_level {
14205                            to_fold.push(crease);
14206                        }
14207
14208                        start_row = nested_end_row + 1;
14209                    }
14210                    None => start_row += 1,
14211                }
14212            }
14213        }
14214
14215        self.fold_creases(to_fold, true, window, cx);
14216    }
14217
14218    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
14219        if self.buffer.read(cx).is_singleton() {
14220            let mut fold_ranges = Vec::new();
14221            let snapshot = self.buffer.read(cx).snapshot(cx);
14222
14223            for row in 0..snapshot.max_row().0 {
14224                if let Some(foldable_range) = self
14225                    .snapshot(window, cx)
14226                    .crease_for_buffer_row(MultiBufferRow(row))
14227                {
14228                    fold_ranges.push(foldable_range);
14229                }
14230            }
14231
14232            self.fold_creases(fold_ranges, true, window, cx);
14233        } else {
14234            self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
14235                editor
14236                    .update_in(cx, |editor, _, cx| {
14237                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14238                            editor.fold_buffer(buffer_id, cx);
14239                        }
14240                    })
14241                    .ok();
14242            });
14243        }
14244    }
14245
14246    pub fn fold_function_bodies(
14247        &mut self,
14248        _: &actions::FoldFunctionBodies,
14249        window: &mut Window,
14250        cx: &mut Context<Self>,
14251    ) {
14252        let snapshot = self.buffer.read(cx).snapshot(cx);
14253
14254        let ranges = snapshot
14255            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
14256            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
14257            .collect::<Vec<_>>();
14258
14259        let creases = ranges
14260            .into_iter()
14261            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
14262            .collect();
14263
14264        self.fold_creases(creases, true, window, cx);
14265    }
14266
14267    pub fn fold_recursive(
14268        &mut self,
14269        _: &actions::FoldRecursive,
14270        window: &mut Window,
14271        cx: &mut Context<Self>,
14272    ) {
14273        let mut to_fold = Vec::new();
14274        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14275        let selections = self.selections.all_adjusted(cx);
14276
14277        for selection in selections {
14278            let range = selection.range().sorted();
14279            let buffer_start_row = range.start.row;
14280
14281            if range.start.row != range.end.row {
14282                let mut found = false;
14283                for row in range.start.row..=range.end.row {
14284                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14285                        found = true;
14286                        to_fold.push(crease);
14287                    }
14288                }
14289                if found {
14290                    continue;
14291                }
14292            }
14293
14294            for row in (0..=range.start.row).rev() {
14295                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14296                    if crease.range().end.row >= buffer_start_row {
14297                        to_fold.push(crease);
14298                    } else {
14299                        break;
14300                    }
14301                }
14302            }
14303        }
14304
14305        self.fold_creases(to_fold, true, window, cx);
14306    }
14307
14308    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
14309        let buffer_row = fold_at.buffer_row;
14310        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14311
14312        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
14313            let autoscroll = self
14314                .selections
14315                .all::<Point>(cx)
14316                .iter()
14317                .any(|selection| crease.range().overlaps(&selection.range()));
14318
14319            self.fold_creases(vec![crease], autoscroll, window, cx);
14320        }
14321    }
14322
14323    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
14324        if self.is_singleton(cx) {
14325            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14326            let buffer = &display_map.buffer_snapshot;
14327            let selections = self.selections.all::<Point>(cx);
14328            let ranges = selections
14329                .iter()
14330                .map(|s| {
14331                    let range = s.display_range(&display_map).sorted();
14332                    let mut start = range.start.to_point(&display_map);
14333                    let mut end = range.end.to_point(&display_map);
14334                    start.column = 0;
14335                    end.column = buffer.line_len(MultiBufferRow(end.row));
14336                    start..end
14337                })
14338                .collect::<Vec<_>>();
14339
14340            self.unfold_ranges(&ranges, true, true, cx);
14341        } else {
14342            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14343            let buffer_ids = self
14344                .selections
14345                .disjoint_anchor_ranges()
14346                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14347                .collect::<HashSet<_>>();
14348            for buffer_id in buffer_ids {
14349                self.unfold_buffer(buffer_id, cx);
14350            }
14351        }
14352    }
14353
14354    pub fn unfold_recursive(
14355        &mut self,
14356        _: &UnfoldRecursive,
14357        _window: &mut Window,
14358        cx: &mut Context<Self>,
14359    ) {
14360        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14361        let selections = self.selections.all::<Point>(cx);
14362        let ranges = selections
14363            .iter()
14364            .map(|s| {
14365                let mut range = s.display_range(&display_map).sorted();
14366                *range.start.column_mut() = 0;
14367                *range.end.column_mut() = display_map.line_len(range.end.row());
14368                let start = range.start.to_point(&display_map);
14369                let end = range.end.to_point(&display_map);
14370                start..end
14371            })
14372            .collect::<Vec<_>>();
14373
14374        self.unfold_ranges(&ranges, true, true, cx);
14375    }
14376
14377    pub fn unfold_at(
14378        &mut self,
14379        unfold_at: &UnfoldAt,
14380        _window: &mut Window,
14381        cx: &mut Context<Self>,
14382    ) {
14383        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14384
14385        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
14386            ..Point::new(
14387                unfold_at.buffer_row.0,
14388                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
14389            );
14390
14391        let autoscroll = self
14392            .selections
14393            .all::<Point>(cx)
14394            .iter()
14395            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
14396
14397        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
14398    }
14399
14400    pub fn unfold_all(
14401        &mut self,
14402        _: &actions::UnfoldAll,
14403        _window: &mut Window,
14404        cx: &mut Context<Self>,
14405    ) {
14406        if self.buffer.read(cx).is_singleton() {
14407            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14408            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
14409        } else {
14410            self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
14411                editor
14412                    .update(cx, |editor, cx| {
14413                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14414                            editor.unfold_buffer(buffer_id, cx);
14415                        }
14416                    })
14417                    .ok();
14418            });
14419        }
14420    }
14421
14422    pub fn fold_selected_ranges(
14423        &mut self,
14424        _: &FoldSelectedRanges,
14425        window: &mut Window,
14426        cx: &mut Context<Self>,
14427    ) {
14428        let selections = self.selections.all::<Point>(cx);
14429        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14430        let line_mode = self.selections.line_mode;
14431        let ranges = selections
14432            .into_iter()
14433            .map(|s| {
14434                if line_mode {
14435                    let start = Point::new(s.start.row, 0);
14436                    let end = Point::new(
14437                        s.end.row,
14438                        display_map
14439                            .buffer_snapshot
14440                            .line_len(MultiBufferRow(s.end.row)),
14441                    );
14442                    Crease::simple(start..end, display_map.fold_placeholder.clone())
14443                } else {
14444                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
14445                }
14446            })
14447            .collect::<Vec<_>>();
14448        self.fold_creases(ranges, true, window, cx);
14449    }
14450
14451    pub fn fold_ranges<T: ToOffset + Clone>(
14452        &mut self,
14453        ranges: Vec<Range<T>>,
14454        auto_scroll: bool,
14455        window: &mut Window,
14456        cx: &mut Context<Self>,
14457    ) {
14458        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14459        let ranges = ranges
14460            .into_iter()
14461            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
14462            .collect::<Vec<_>>();
14463        self.fold_creases(ranges, auto_scroll, window, cx);
14464    }
14465
14466    pub fn fold_creases<T: ToOffset + Clone>(
14467        &mut self,
14468        creases: Vec<Crease<T>>,
14469        auto_scroll: bool,
14470        window: &mut Window,
14471        cx: &mut Context<Self>,
14472    ) {
14473        if creases.is_empty() {
14474            return;
14475        }
14476
14477        let mut buffers_affected = HashSet::default();
14478        let multi_buffer = self.buffer().read(cx);
14479        for crease in &creases {
14480            if let Some((_, buffer, _)) =
14481                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
14482            {
14483                buffers_affected.insert(buffer.read(cx).remote_id());
14484            };
14485        }
14486
14487        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
14488
14489        if auto_scroll {
14490            self.request_autoscroll(Autoscroll::fit(), cx);
14491        }
14492
14493        cx.notify();
14494
14495        if let Some(active_diagnostics) = self.active_diagnostics.take() {
14496            // Clear diagnostics block when folding a range that contains it.
14497            let snapshot = self.snapshot(window, cx);
14498            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
14499                drop(snapshot);
14500                self.active_diagnostics = Some(active_diagnostics);
14501                self.dismiss_diagnostics(cx);
14502            } else {
14503                self.active_diagnostics = Some(active_diagnostics);
14504            }
14505        }
14506
14507        self.scrollbar_marker_state.dirty = true;
14508        self.folds_did_change(cx);
14509    }
14510
14511    /// Removes any folds whose ranges intersect any of the given ranges.
14512    pub fn unfold_ranges<T: ToOffset + Clone>(
14513        &mut self,
14514        ranges: &[Range<T>],
14515        inclusive: bool,
14516        auto_scroll: bool,
14517        cx: &mut Context<Self>,
14518    ) {
14519        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
14520            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
14521        });
14522        self.folds_did_change(cx);
14523    }
14524
14525    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
14526        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
14527            return;
14528        }
14529        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
14530        self.display_map.update(cx, |display_map, cx| {
14531            display_map.fold_buffers([buffer_id], cx)
14532        });
14533        cx.emit(EditorEvent::BufferFoldToggled {
14534            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
14535            folded: true,
14536        });
14537        cx.notify();
14538    }
14539
14540    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
14541        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
14542            return;
14543        }
14544        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
14545        self.display_map.update(cx, |display_map, cx| {
14546            display_map.unfold_buffers([buffer_id], cx);
14547        });
14548        cx.emit(EditorEvent::BufferFoldToggled {
14549            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
14550            folded: false,
14551        });
14552        cx.notify();
14553    }
14554
14555    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
14556        self.display_map.read(cx).is_buffer_folded(buffer)
14557    }
14558
14559    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
14560        self.display_map.read(cx).folded_buffers()
14561    }
14562
14563    /// Removes any folds with the given ranges.
14564    pub fn remove_folds_with_type<T: ToOffset + Clone>(
14565        &mut self,
14566        ranges: &[Range<T>],
14567        type_id: TypeId,
14568        auto_scroll: bool,
14569        cx: &mut Context<Self>,
14570    ) {
14571        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
14572            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
14573        });
14574        self.folds_did_change(cx);
14575    }
14576
14577    fn remove_folds_with<T: ToOffset + Clone>(
14578        &mut self,
14579        ranges: &[Range<T>],
14580        auto_scroll: bool,
14581        cx: &mut Context<Self>,
14582        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
14583    ) {
14584        if ranges.is_empty() {
14585            return;
14586        }
14587
14588        let mut buffers_affected = HashSet::default();
14589        let multi_buffer = self.buffer().read(cx);
14590        for range in ranges {
14591            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
14592                buffers_affected.insert(buffer.read(cx).remote_id());
14593            };
14594        }
14595
14596        self.display_map.update(cx, update);
14597
14598        if auto_scroll {
14599            self.request_autoscroll(Autoscroll::fit(), cx);
14600        }
14601
14602        cx.notify();
14603        self.scrollbar_marker_state.dirty = true;
14604        self.active_indent_guides_state.dirty = true;
14605    }
14606
14607    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
14608        self.display_map.read(cx).fold_placeholder.clone()
14609    }
14610
14611    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
14612        self.buffer.update(cx, |buffer, cx| {
14613            buffer.set_all_diff_hunks_expanded(cx);
14614        });
14615    }
14616
14617    pub fn expand_all_diff_hunks(
14618        &mut self,
14619        _: &ExpandAllDiffHunks,
14620        _window: &mut Window,
14621        cx: &mut Context<Self>,
14622    ) {
14623        self.buffer.update(cx, |buffer, cx| {
14624            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
14625        });
14626    }
14627
14628    pub fn toggle_selected_diff_hunks(
14629        &mut self,
14630        _: &ToggleSelectedDiffHunks,
14631        _window: &mut Window,
14632        cx: &mut Context<Self>,
14633    ) {
14634        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
14635        self.toggle_diff_hunks_in_ranges(ranges, cx);
14636    }
14637
14638    pub fn diff_hunks_in_ranges<'a>(
14639        &'a self,
14640        ranges: &'a [Range<Anchor>],
14641        buffer: &'a MultiBufferSnapshot,
14642    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
14643        ranges.iter().flat_map(move |range| {
14644            let end_excerpt_id = range.end.excerpt_id;
14645            let range = range.to_point(buffer);
14646            let mut peek_end = range.end;
14647            if range.end.row < buffer.max_row().0 {
14648                peek_end = Point::new(range.end.row + 1, 0);
14649            }
14650            buffer
14651                .diff_hunks_in_range(range.start..peek_end)
14652                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
14653        })
14654    }
14655
14656    pub fn has_stageable_diff_hunks_in_ranges(
14657        &self,
14658        ranges: &[Range<Anchor>],
14659        snapshot: &MultiBufferSnapshot,
14660    ) -> bool {
14661        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
14662        hunks.any(|hunk| hunk.status().has_secondary_hunk())
14663    }
14664
14665    pub fn toggle_staged_selected_diff_hunks(
14666        &mut self,
14667        _: &::git::ToggleStaged,
14668        _: &mut Window,
14669        cx: &mut Context<Self>,
14670    ) {
14671        let snapshot = self.buffer.read(cx).snapshot(cx);
14672        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
14673        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
14674        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
14675    }
14676
14677    pub fn stage_and_next(
14678        &mut self,
14679        _: &::git::StageAndNext,
14680        window: &mut Window,
14681        cx: &mut Context<Self>,
14682    ) {
14683        self.do_stage_or_unstage_and_next(true, window, cx);
14684    }
14685
14686    pub fn unstage_and_next(
14687        &mut self,
14688        _: &::git::UnstageAndNext,
14689        window: &mut Window,
14690        cx: &mut Context<Self>,
14691    ) {
14692        self.do_stage_or_unstage_and_next(false, window, cx);
14693    }
14694
14695    pub fn stage_or_unstage_diff_hunks(
14696        &mut self,
14697        stage: bool,
14698        ranges: Vec<Range<Anchor>>,
14699        cx: &mut Context<Self>,
14700    ) {
14701        let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
14702        cx.spawn(async move |this, cx| {
14703            task.await?;
14704            this.update(cx, |this, cx| {
14705                let snapshot = this.buffer.read(cx).snapshot(cx);
14706                let chunk_by = this
14707                    .diff_hunks_in_ranges(&ranges, &snapshot)
14708                    .chunk_by(|hunk| hunk.buffer_id);
14709                for (buffer_id, hunks) in &chunk_by {
14710                    this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
14711                }
14712            })
14713        })
14714        .detach_and_log_err(cx);
14715    }
14716
14717    fn save_buffers_for_ranges_if_needed(
14718        &mut self,
14719        ranges: &[Range<Anchor>],
14720        cx: &mut Context<'_, Editor>,
14721    ) -> Task<Result<()>> {
14722        let multibuffer = self.buffer.read(cx);
14723        let snapshot = multibuffer.read(cx);
14724        let buffer_ids: HashSet<_> = ranges
14725            .iter()
14726            .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
14727            .collect();
14728        drop(snapshot);
14729
14730        let mut buffers = HashSet::default();
14731        for buffer_id in buffer_ids {
14732            if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
14733                let buffer = buffer_entity.read(cx);
14734                if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
14735                {
14736                    buffers.insert(buffer_entity);
14737                }
14738            }
14739        }
14740
14741        if let Some(project) = &self.project {
14742            project.update(cx, |project, cx| project.save_buffers(buffers, cx))
14743        } else {
14744            Task::ready(Ok(()))
14745        }
14746    }
14747
14748    fn do_stage_or_unstage_and_next(
14749        &mut self,
14750        stage: bool,
14751        window: &mut Window,
14752        cx: &mut Context<Self>,
14753    ) {
14754        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
14755
14756        if ranges.iter().any(|range| range.start != range.end) {
14757            self.stage_or_unstage_diff_hunks(stage, ranges, cx);
14758            return;
14759        }
14760
14761        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
14762        let snapshot = self.snapshot(window, cx);
14763        let position = self.selections.newest::<Point>(cx).head();
14764        let mut row = snapshot
14765            .buffer_snapshot
14766            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
14767            .find(|hunk| hunk.row_range.start.0 > position.row)
14768            .map(|hunk| hunk.row_range.start);
14769
14770        let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
14771        // Outside of the project diff editor, wrap around to the beginning.
14772        if !all_diff_hunks_expanded {
14773            row = row.or_else(|| {
14774                snapshot
14775                    .buffer_snapshot
14776                    .diff_hunks_in_range(Point::zero()..position)
14777                    .find(|hunk| hunk.row_range.end.0 < position.row)
14778                    .map(|hunk| hunk.row_range.start)
14779            });
14780        }
14781
14782        if let Some(row) = row {
14783            let destination = Point::new(row.0, 0);
14784            let autoscroll = Autoscroll::center();
14785
14786            self.unfold_ranges(&[destination..destination], false, false, cx);
14787            self.change_selections(Some(autoscroll), window, cx, |s| {
14788                s.select_ranges([destination..destination]);
14789            });
14790        }
14791    }
14792
14793    fn do_stage_or_unstage(
14794        &self,
14795        stage: bool,
14796        buffer_id: BufferId,
14797        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
14798        cx: &mut App,
14799    ) -> Option<()> {
14800        let project = self.project.as_ref()?;
14801        let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
14802        let diff = self.buffer.read(cx).diff_for(buffer_id)?;
14803        let buffer_snapshot = buffer.read(cx).snapshot();
14804        let file_exists = buffer_snapshot
14805            .file()
14806            .is_some_and(|file| file.disk_state().exists());
14807        diff.update(cx, |diff, cx| {
14808            diff.stage_or_unstage_hunks(
14809                stage,
14810                &hunks
14811                    .map(|hunk| buffer_diff::DiffHunk {
14812                        buffer_range: hunk.buffer_range,
14813                        diff_base_byte_range: hunk.diff_base_byte_range,
14814                        secondary_status: hunk.secondary_status,
14815                        range: Point::zero()..Point::zero(), // unused
14816                    })
14817                    .collect::<Vec<_>>(),
14818                &buffer_snapshot,
14819                file_exists,
14820                cx,
14821            )
14822        });
14823        None
14824    }
14825
14826    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
14827        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
14828        self.buffer
14829            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
14830    }
14831
14832    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
14833        self.buffer.update(cx, |buffer, cx| {
14834            let ranges = vec![Anchor::min()..Anchor::max()];
14835            if !buffer.all_diff_hunks_expanded()
14836                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
14837            {
14838                buffer.collapse_diff_hunks(ranges, cx);
14839                true
14840            } else {
14841                false
14842            }
14843        })
14844    }
14845
14846    fn toggle_diff_hunks_in_ranges(
14847        &mut self,
14848        ranges: Vec<Range<Anchor>>,
14849        cx: &mut Context<'_, Editor>,
14850    ) {
14851        self.buffer.update(cx, |buffer, cx| {
14852            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
14853            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
14854        })
14855    }
14856
14857    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
14858        self.buffer.update(cx, |buffer, cx| {
14859            let snapshot = buffer.snapshot(cx);
14860            let excerpt_id = range.end.excerpt_id;
14861            let point_range = range.to_point(&snapshot);
14862            let expand = !buffer.single_hunk_is_expanded(range, cx);
14863            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
14864        })
14865    }
14866
14867    pub(crate) fn apply_all_diff_hunks(
14868        &mut self,
14869        _: &ApplyAllDiffHunks,
14870        window: &mut Window,
14871        cx: &mut Context<Self>,
14872    ) {
14873        let buffers = self.buffer.read(cx).all_buffers();
14874        for branch_buffer in buffers {
14875            branch_buffer.update(cx, |branch_buffer, cx| {
14876                branch_buffer.merge_into_base(Vec::new(), cx);
14877            });
14878        }
14879
14880        if let Some(project) = self.project.clone() {
14881            self.save(true, project, window, cx).detach_and_log_err(cx);
14882        }
14883    }
14884
14885    pub(crate) fn apply_selected_diff_hunks(
14886        &mut self,
14887        _: &ApplyDiffHunk,
14888        window: &mut Window,
14889        cx: &mut Context<Self>,
14890    ) {
14891        let snapshot = self.snapshot(window, cx);
14892        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
14893        let mut ranges_by_buffer = HashMap::default();
14894        self.transact(window, cx, |editor, _window, cx| {
14895            for hunk in hunks {
14896                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
14897                    ranges_by_buffer
14898                        .entry(buffer.clone())
14899                        .or_insert_with(Vec::new)
14900                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
14901                }
14902            }
14903
14904            for (buffer, ranges) in ranges_by_buffer {
14905                buffer.update(cx, |buffer, cx| {
14906                    buffer.merge_into_base(ranges, cx);
14907                });
14908            }
14909        });
14910
14911        if let Some(project) = self.project.clone() {
14912            self.save(true, project, window, cx).detach_and_log_err(cx);
14913        }
14914    }
14915
14916    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
14917        if hovered != self.gutter_hovered {
14918            self.gutter_hovered = hovered;
14919            cx.notify();
14920        }
14921    }
14922
14923    pub fn insert_blocks(
14924        &mut self,
14925        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
14926        autoscroll: Option<Autoscroll>,
14927        cx: &mut Context<Self>,
14928    ) -> Vec<CustomBlockId> {
14929        let blocks = self
14930            .display_map
14931            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
14932        if let Some(autoscroll) = autoscroll {
14933            self.request_autoscroll(autoscroll, cx);
14934        }
14935        cx.notify();
14936        blocks
14937    }
14938
14939    pub fn resize_blocks(
14940        &mut self,
14941        heights: HashMap<CustomBlockId, u32>,
14942        autoscroll: Option<Autoscroll>,
14943        cx: &mut Context<Self>,
14944    ) {
14945        self.display_map
14946            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
14947        if let Some(autoscroll) = autoscroll {
14948            self.request_autoscroll(autoscroll, cx);
14949        }
14950        cx.notify();
14951    }
14952
14953    pub fn replace_blocks(
14954        &mut self,
14955        renderers: HashMap<CustomBlockId, RenderBlock>,
14956        autoscroll: Option<Autoscroll>,
14957        cx: &mut Context<Self>,
14958    ) {
14959        self.display_map
14960            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
14961        if let Some(autoscroll) = autoscroll {
14962            self.request_autoscroll(autoscroll, cx);
14963        }
14964        cx.notify();
14965    }
14966
14967    pub fn remove_blocks(
14968        &mut self,
14969        block_ids: HashSet<CustomBlockId>,
14970        autoscroll: Option<Autoscroll>,
14971        cx: &mut Context<Self>,
14972    ) {
14973        self.display_map.update(cx, |display_map, cx| {
14974            display_map.remove_blocks(block_ids, cx)
14975        });
14976        if let Some(autoscroll) = autoscroll {
14977            self.request_autoscroll(autoscroll, cx);
14978        }
14979        cx.notify();
14980    }
14981
14982    pub fn row_for_block(
14983        &self,
14984        block_id: CustomBlockId,
14985        cx: &mut Context<Self>,
14986    ) -> Option<DisplayRow> {
14987        self.display_map
14988            .update(cx, |map, cx| map.row_for_block(block_id, cx))
14989    }
14990
14991    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
14992        self.focused_block = Some(focused_block);
14993    }
14994
14995    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
14996        self.focused_block.take()
14997    }
14998
14999    pub fn insert_creases(
15000        &mut self,
15001        creases: impl IntoIterator<Item = Crease<Anchor>>,
15002        cx: &mut Context<Self>,
15003    ) -> Vec<CreaseId> {
15004        self.display_map
15005            .update(cx, |map, cx| map.insert_creases(creases, cx))
15006    }
15007
15008    pub fn remove_creases(
15009        &mut self,
15010        ids: impl IntoIterator<Item = CreaseId>,
15011        cx: &mut Context<Self>,
15012    ) {
15013        self.display_map
15014            .update(cx, |map, cx| map.remove_creases(ids, cx));
15015    }
15016
15017    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15018        self.display_map
15019            .update(cx, |map, cx| map.snapshot(cx))
15020            .longest_row()
15021    }
15022
15023    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15024        self.display_map
15025            .update(cx, |map, cx| map.snapshot(cx))
15026            .max_point()
15027    }
15028
15029    pub fn text(&self, cx: &App) -> String {
15030        self.buffer.read(cx).read(cx).text()
15031    }
15032
15033    pub fn is_empty(&self, cx: &App) -> bool {
15034        self.buffer.read(cx).read(cx).is_empty()
15035    }
15036
15037    pub fn text_option(&self, cx: &App) -> Option<String> {
15038        let text = self.text(cx);
15039        let text = text.trim();
15040
15041        if text.is_empty() {
15042            return None;
15043        }
15044
15045        Some(text.to_string())
15046    }
15047
15048    pub fn set_text(
15049        &mut self,
15050        text: impl Into<Arc<str>>,
15051        window: &mut Window,
15052        cx: &mut Context<Self>,
15053    ) {
15054        self.transact(window, cx, |this, _, cx| {
15055            this.buffer
15056                .read(cx)
15057                .as_singleton()
15058                .expect("you can only call set_text on editors for singleton buffers")
15059                .update(cx, |buffer, cx| buffer.set_text(text, cx));
15060        });
15061    }
15062
15063    pub fn display_text(&self, cx: &mut App) -> String {
15064        self.display_map
15065            .update(cx, |map, cx| map.snapshot(cx))
15066            .text()
15067    }
15068
15069    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15070        let mut wrap_guides = smallvec::smallvec![];
15071
15072        if self.show_wrap_guides == Some(false) {
15073            return wrap_guides;
15074        }
15075
15076        let settings = self.buffer.read(cx).language_settings(cx);
15077        if settings.show_wrap_guides {
15078            match self.soft_wrap_mode(cx) {
15079                SoftWrap::Column(soft_wrap) => {
15080                    wrap_guides.push((soft_wrap as usize, true));
15081                }
15082                SoftWrap::Bounded(soft_wrap) => {
15083                    wrap_guides.push((soft_wrap as usize, true));
15084                }
15085                SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15086            }
15087            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15088        }
15089
15090        wrap_guides
15091    }
15092
15093    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15094        let settings = self.buffer.read(cx).language_settings(cx);
15095        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15096        match mode {
15097            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
15098                SoftWrap::None
15099            }
15100            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
15101            language_settings::SoftWrap::PreferredLineLength => {
15102                SoftWrap::Column(settings.preferred_line_length)
15103            }
15104            language_settings::SoftWrap::Bounded => {
15105                SoftWrap::Bounded(settings.preferred_line_length)
15106            }
15107        }
15108    }
15109
15110    pub fn set_soft_wrap_mode(
15111        &mut self,
15112        mode: language_settings::SoftWrap,
15113
15114        cx: &mut Context<Self>,
15115    ) {
15116        self.soft_wrap_mode_override = Some(mode);
15117        cx.notify();
15118    }
15119
15120    pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
15121        self.hard_wrap = hard_wrap;
15122        cx.notify();
15123    }
15124
15125    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
15126        self.text_style_refinement = Some(style);
15127    }
15128
15129    /// called by the Element so we know what style we were most recently rendered with.
15130    pub(crate) fn set_style(
15131        &mut self,
15132        style: EditorStyle,
15133        window: &mut Window,
15134        cx: &mut Context<Self>,
15135    ) {
15136        let rem_size = window.rem_size();
15137        self.display_map.update(cx, |map, cx| {
15138            map.set_font(
15139                style.text.font(),
15140                style.text.font_size.to_pixels(rem_size),
15141                cx,
15142            )
15143        });
15144        self.style = Some(style);
15145    }
15146
15147    pub fn style(&self) -> Option<&EditorStyle> {
15148        self.style.as_ref()
15149    }
15150
15151    // Called by the element. This method is not designed to be called outside of the editor
15152    // element's layout code because it does not notify when rewrapping is computed synchronously.
15153    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
15154        self.display_map
15155            .update(cx, |map, cx| map.set_wrap_width(width, cx))
15156    }
15157
15158    pub fn set_soft_wrap(&mut self) {
15159        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
15160    }
15161
15162    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
15163        if self.soft_wrap_mode_override.is_some() {
15164            self.soft_wrap_mode_override.take();
15165        } else {
15166            let soft_wrap = match self.soft_wrap_mode(cx) {
15167                SoftWrap::GitDiff => return,
15168                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
15169                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
15170                    language_settings::SoftWrap::None
15171                }
15172            };
15173            self.soft_wrap_mode_override = Some(soft_wrap);
15174        }
15175        cx.notify();
15176    }
15177
15178    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
15179        let Some(workspace) = self.workspace() else {
15180            return;
15181        };
15182        let fs = workspace.read(cx).app_state().fs.clone();
15183        let current_show = TabBarSettings::get_global(cx).show;
15184        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
15185            setting.show = Some(!current_show);
15186        });
15187    }
15188
15189    pub fn toggle_indent_guides(
15190        &mut self,
15191        _: &ToggleIndentGuides,
15192        _: &mut Window,
15193        cx: &mut Context<Self>,
15194    ) {
15195        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
15196            self.buffer
15197                .read(cx)
15198                .language_settings(cx)
15199                .indent_guides
15200                .enabled
15201        });
15202        self.show_indent_guides = Some(!currently_enabled);
15203        cx.notify();
15204    }
15205
15206    fn should_show_indent_guides(&self) -> Option<bool> {
15207        self.show_indent_guides
15208    }
15209
15210    pub fn toggle_line_numbers(
15211        &mut self,
15212        _: &ToggleLineNumbers,
15213        _: &mut Window,
15214        cx: &mut Context<Self>,
15215    ) {
15216        let mut editor_settings = EditorSettings::get_global(cx).clone();
15217        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
15218        EditorSettings::override_global(editor_settings, cx);
15219    }
15220
15221    pub fn line_numbers_enabled(&self, cx: &App) -> bool {
15222        if let Some(show_line_numbers) = self.show_line_numbers {
15223            return show_line_numbers;
15224        }
15225        EditorSettings::get_global(cx).gutter.line_numbers
15226    }
15227
15228    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
15229        self.use_relative_line_numbers
15230            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
15231    }
15232
15233    pub fn toggle_relative_line_numbers(
15234        &mut self,
15235        _: &ToggleRelativeLineNumbers,
15236        _: &mut Window,
15237        cx: &mut Context<Self>,
15238    ) {
15239        let is_relative = self.should_use_relative_line_numbers(cx);
15240        self.set_relative_line_number(Some(!is_relative), cx)
15241    }
15242
15243    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
15244        self.use_relative_line_numbers = is_relative;
15245        cx.notify();
15246    }
15247
15248    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
15249        self.show_gutter = show_gutter;
15250        cx.notify();
15251    }
15252
15253    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
15254        self.show_scrollbars = show_scrollbars;
15255        cx.notify();
15256    }
15257
15258    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
15259        self.show_line_numbers = Some(show_line_numbers);
15260        cx.notify();
15261    }
15262
15263    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
15264        self.show_git_diff_gutter = Some(show_git_diff_gutter);
15265        cx.notify();
15266    }
15267
15268    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
15269        self.show_code_actions = Some(show_code_actions);
15270        cx.notify();
15271    }
15272
15273    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
15274        self.show_runnables = Some(show_runnables);
15275        cx.notify();
15276    }
15277
15278    pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
15279        self.show_breakpoints = Some(show_breakpoints);
15280        cx.notify();
15281    }
15282
15283    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
15284        if self.display_map.read(cx).masked != masked {
15285            self.display_map.update(cx, |map, _| map.masked = masked);
15286        }
15287        cx.notify()
15288    }
15289
15290    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
15291        self.show_wrap_guides = Some(show_wrap_guides);
15292        cx.notify();
15293    }
15294
15295    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
15296        self.show_indent_guides = Some(show_indent_guides);
15297        cx.notify();
15298    }
15299
15300    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
15301        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
15302            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
15303                if let Some(dir) = file.abs_path(cx).parent() {
15304                    return Some(dir.to_owned());
15305                }
15306            }
15307
15308            if let Some(project_path) = buffer.read(cx).project_path(cx) {
15309                return Some(project_path.path.to_path_buf());
15310            }
15311        }
15312
15313        None
15314    }
15315
15316    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
15317        self.active_excerpt(cx)?
15318            .1
15319            .read(cx)
15320            .file()
15321            .and_then(|f| f.as_local())
15322    }
15323
15324    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15325        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15326            let buffer = buffer.read(cx);
15327            if let Some(project_path) = buffer.project_path(cx) {
15328                let project = self.project.as_ref()?.read(cx);
15329                project.absolute_path(&project_path, cx)
15330            } else {
15331                buffer
15332                    .file()
15333                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
15334            }
15335        })
15336    }
15337
15338    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15339        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15340            let project_path = buffer.read(cx).project_path(cx)?;
15341            let project = self.project.as_ref()?.read(cx);
15342            let entry = project.entry_for_path(&project_path, cx)?;
15343            let path = entry.path.to_path_buf();
15344            Some(path)
15345        })
15346    }
15347
15348    pub fn reveal_in_finder(
15349        &mut self,
15350        _: &RevealInFileManager,
15351        _window: &mut Window,
15352        cx: &mut Context<Self>,
15353    ) {
15354        if let Some(target) = self.target_file(cx) {
15355            cx.reveal_path(&target.abs_path(cx));
15356        }
15357    }
15358
15359    pub fn copy_path(
15360        &mut self,
15361        _: &zed_actions::workspace::CopyPath,
15362        _window: &mut Window,
15363        cx: &mut Context<Self>,
15364    ) {
15365        if let Some(path) = self.target_file_abs_path(cx) {
15366            if let Some(path) = path.to_str() {
15367                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
15368            }
15369        }
15370    }
15371
15372    pub fn copy_relative_path(
15373        &mut self,
15374        _: &zed_actions::workspace::CopyRelativePath,
15375        _window: &mut Window,
15376        cx: &mut Context<Self>,
15377    ) {
15378        if let Some(path) = self.target_file_path(cx) {
15379            if let Some(path) = path.to_str() {
15380                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
15381            }
15382        }
15383    }
15384
15385    pub fn project_path(&self, cx: &mut Context<Self>) -> Option<ProjectPath> {
15386        if let Some(buffer) = self.buffer.read(cx).as_singleton() {
15387            buffer.read_with(cx, |buffer, cx| buffer.project_path(cx))
15388        } else {
15389            None
15390        }
15391    }
15392
15393    pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15394        let _ = maybe!({
15395            let breakpoint_store = self.breakpoint_store.as_ref()?;
15396
15397            let Some((_, _, active_position)) =
15398                breakpoint_store.read(cx).active_position().cloned()
15399            else {
15400                self.clear_row_highlights::<DebugCurrentRowHighlight>();
15401                return None;
15402            };
15403
15404            let snapshot = self
15405                .project
15406                .as_ref()?
15407                .read(cx)
15408                .buffer_for_id(active_position.buffer_id?, cx)?
15409                .read(cx)
15410                .snapshot();
15411
15412            for (id, ExcerptRange { context, .. }) in self
15413                .buffer
15414                .read(cx)
15415                .excerpts_for_buffer(active_position.buffer_id?, cx)
15416            {
15417                if context.start.cmp(&active_position, &snapshot).is_ge()
15418                    || context.end.cmp(&active_position, &snapshot).is_lt()
15419                {
15420                    continue;
15421                }
15422                let snapshot = self.buffer.read(cx).snapshot(cx);
15423                let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
15424
15425                self.clear_row_highlights::<DebugCurrentRowHighlight>();
15426                self.go_to_line::<DebugCurrentRowHighlight>(
15427                    multibuffer_anchor,
15428                    Some(cx.theme().colors().editor_debugger_active_line_background),
15429                    window,
15430                    cx,
15431                );
15432
15433                cx.notify();
15434            }
15435
15436            Some(())
15437        });
15438    }
15439
15440    pub fn copy_file_name_without_extension(
15441        &mut self,
15442        _: &CopyFileNameWithoutExtension,
15443        _: &mut Window,
15444        cx: &mut Context<Self>,
15445    ) {
15446        if let Some(file) = self.target_file(cx) {
15447            if let Some(file_stem) = file.path().file_stem() {
15448                if let Some(name) = file_stem.to_str() {
15449                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
15450                }
15451            }
15452        }
15453    }
15454
15455    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
15456        if let Some(file) = self.target_file(cx) {
15457            if let Some(file_name) = file.path().file_name() {
15458                if let Some(name) = file_name.to_str() {
15459                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
15460                }
15461            }
15462        }
15463    }
15464
15465    pub fn toggle_git_blame(
15466        &mut self,
15467        _: &::git::Blame,
15468        window: &mut Window,
15469        cx: &mut Context<Self>,
15470    ) {
15471        self.show_git_blame_gutter = !self.show_git_blame_gutter;
15472
15473        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
15474            self.start_git_blame(true, window, cx);
15475        }
15476
15477        cx.notify();
15478    }
15479
15480    pub fn toggle_git_blame_inline(
15481        &mut self,
15482        _: &ToggleGitBlameInline,
15483        window: &mut Window,
15484        cx: &mut Context<Self>,
15485    ) {
15486        self.toggle_git_blame_inline_internal(true, window, cx);
15487        cx.notify();
15488    }
15489
15490    pub fn git_blame_inline_enabled(&self) -> bool {
15491        self.git_blame_inline_enabled
15492    }
15493
15494    pub fn toggle_selection_menu(
15495        &mut self,
15496        _: &ToggleSelectionMenu,
15497        _: &mut Window,
15498        cx: &mut Context<Self>,
15499    ) {
15500        self.show_selection_menu = self
15501            .show_selection_menu
15502            .map(|show_selections_menu| !show_selections_menu)
15503            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
15504
15505        cx.notify();
15506    }
15507
15508    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
15509        self.show_selection_menu
15510            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
15511    }
15512
15513    fn start_git_blame(
15514        &mut self,
15515        user_triggered: bool,
15516        window: &mut Window,
15517        cx: &mut Context<Self>,
15518    ) {
15519        if let Some(project) = self.project.as_ref() {
15520            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
15521                return;
15522            };
15523
15524            if buffer.read(cx).file().is_none() {
15525                return;
15526            }
15527
15528            let focused = self.focus_handle(cx).contains_focused(window, cx);
15529
15530            let project = project.clone();
15531            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
15532            self.blame_subscription =
15533                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
15534            self.blame = Some(blame);
15535        }
15536    }
15537
15538    fn toggle_git_blame_inline_internal(
15539        &mut self,
15540        user_triggered: bool,
15541        window: &mut Window,
15542        cx: &mut Context<Self>,
15543    ) {
15544        if self.git_blame_inline_enabled {
15545            self.git_blame_inline_enabled = false;
15546            self.show_git_blame_inline = false;
15547            self.show_git_blame_inline_delay_task.take();
15548        } else {
15549            self.git_blame_inline_enabled = true;
15550            self.start_git_blame_inline(user_triggered, window, cx);
15551        }
15552
15553        cx.notify();
15554    }
15555
15556    fn start_git_blame_inline(
15557        &mut self,
15558        user_triggered: bool,
15559        window: &mut Window,
15560        cx: &mut Context<Self>,
15561    ) {
15562        self.start_git_blame(user_triggered, window, cx);
15563
15564        if ProjectSettings::get_global(cx)
15565            .git
15566            .inline_blame_delay()
15567            .is_some()
15568        {
15569            self.start_inline_blame_timer(window, cx);
15570        } else {
15571            self.show_git_blame_inline = true
15572        }
15573    }
15574
15575    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
15576        self.blame.as_ref()
15577    }
15578
15579    pub fn show_git_blame_gutter(&self) -> bool {
15580        self.show_git_blame_gutter
15581    }
15582
15583    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
15584        self.show_git_blame_gutter && self.has_blame_entries(cx)
15585    }
15586
15587    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
15588        self.show_git_blame_inline
15589            && (self.focus_handle.is_focused(window)
15590                || self
15591                    .git_blame_inline_tooltip
15592                    .as_ref()
15593                    .and_then(|t| t.upgrade())
15594                    .is_some())
15595            && !self.newest_selection_head_on_empty_line(cx)
15596            && self.has_blame_entries(cx)
15597    }
15598
15599    fn has_blame_entries(&self, cx: &App) -> bool {
15600        self.blame()
15601            .map_or(false, |blame| blame.read(cx).has_generated_entries())
15602    }
15603
15604    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
15605        let cursor_anchor = self.selections.newest_anchor().head();
15606
15607        let snapshot = self.buffer.read(cx).snapshot(cx);
15608        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
15609
15610        snapshot.line_len(buffer_row) == 0
15611    }
15612
15613    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
15614        let buffer_and_selection = maybe!({
15615            let selection = self.selections.newest::<Point>(cx);
15616            let selection_range = selection.range();
15617
15618            let multi_buffer = self.buffer().read(cx);
15619            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15620            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
15621
15622            let (buffer, range, _) = if selection.reversed {
15623                buffer_ranges.first()
15624            } else {
15625                buffer_ranges.last()
15626            }?;
15627
15628            let selection = text::ToPoint::to_point(&range.start, &buffer).row
15629                ..text::ToPoint::to_point(&range.end, &buffer).row;
15630            Some((
15631                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
15632                selection,
15633            ))
15634        });
15635
15636        let Some((buffer, selection)) = buffer_and_selection else {
15637            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
15638        };
15639
15640        let Some(project) = self.project.as_ref() else {
15641            return Task::ready(Err(anyhow!("editor does not have project")));
15642        };
15643
15644        project.update(cx, |project, cx| {
15645            project.get_permalink_to_line(&buffer, selection, cx)
15646        })
15647    }
15648
15649    pub fn copy_permalink_to_line(
15650        &mut self,
15651        _: &CopyPermalinkToLine,
15652        window: &mut Window,
15653        cx: &mut Context<Self>,
15654    ) {
15655        let permalink_task = self.get_permalink_to_line(cx);
15656        let workspace = self.workspace();
15657
15658        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
15659            Ok(permalink) => {
15660                cx.update(|_, cx| {
15661                    cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
15662                })
15663                .ok();
15664            }
15665            Err(err) => {
15666                let message = format!("Failed to copy permalink: {err}");
15667
15668                Err::<(), anyhow::Error>(err).log_err();
15669
15670                if let Some(workspace) = workspace {
15671                    workspace
15672                        .update_in(cx, |workspace, _, cx| {
15673                            struct CopyPermalinkToLine;
15674
15675                            workspace.show_toast(
15676                                Toast::new(
15677                                    NotificationId::unique::<CopyPermalinkToLine>(),
15678                                    message,
15679                                ),
15680                                cx,
15681                            )
15682                        })
15683                        .ok();
15684                }
15685            }
15686        })
15687        .detach();
15688    }
15689
15690    pub fn copy_file_location(
15691        &mut self,
15692        _: &CopyFileLocation,
15693        _: &mut Window,
15694        cx: &mut Context<Self>,
15695    ) {
15696        let selection = self.selections.newest::<Point>(cx).start.row + 1;
15697        if let Some(file) = self.target_file(cx) {
15698            if let Some(path) = file.path().to_str() {
15699                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
15700            }
15701        }
15702    }
15703
15704    pub fn open_permalink_to_line(
15705        &mut self,
15706        _: &OpenPermalinkToLine,
15707        window: &mut Window,
15708        cx: &mut Context<Self>,
15709    ) {
15710        let permalink_task = self.get_permalink_to_line(cx);
15711        let workspace = self.workspace();
15712
15713        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
15714            Ok(permalink) => {
15715                cx.update(|_, cx| {
15716                    cx.open_url(permalink.as_ref());
15717                })
15718                .ok();
15719            }
15720            Err(err) => {
15721                let message = format!("Failed to open permalink: {err}");
15722
15723                Err::<(), anyhow::Error>(err).log_err();
15724
15725                if let Some(workspace) = workspace {
15726                    workspace
15727                        .update(cx, |workspace, cx| {
15728                            struct OpenPermalinkToLine;
15729
15730                            workspace.show_toast(
15731                                Toast::new(
15732                                    NotificationId::unique::<OpenPermalinkToLine>(),
15733                                    message,
15734                                ),
15735                                cx,
15736                            )
15737                        })
15738                        .ok();
15739                }
15740            }
15741        })
15742        .detach();
15743    }
15744
15745    pub fn insert_uuid_v4(
15746        &mut self,
15747        _: &InsertUuidV4,
15748        window: &mut Window,
15749        cx: &mut Context<Self>,
15750    ) {
15751        self.insert_uuid(UuidVersion::V4, window, cx);
15752    }
15753
15754    pub fn insert_uuid_v7(
15755        &mut self,
15756        _: &InsertUuidV7,
15757        window: &mut Window,
15758        cx: &mut Context<Self>,
15759    ) {
15760        self.insert_uuid(UuidVersion::V7, window, cx);
15761    }
15762
15763    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
15764        self.transact(window, cx, |this, window, cx| {
15765            let edits = this
15766                .selections
15767                .all::<Point>(cx)
15768                .into_iter()
15769                .map(|selection| {
15770                    let uuid = match version {
15771                        UuidVersion::V4 => uuid::Uuid::new_v4(),
15772                        UuidVersion::V7 => uuid::Uuid::now_v7(),
15773                    };
15774
15775                    (selection.range(), uuid.to_string())
15776                });
15777            this.edit(edits, cx);
15778            this.refresh_inline_completion(true, false, window, cx);
15779        });
15780    }
15781
15782    pub fn open_selections_in_multibuffer(
15783        &mut self,
15784        _: &OpenSelectionsInMultibuffer,
15785        window: &mut Window,
15786        cx: &mut Context<Self>,
15787    ) {
15788        let multibuffer = self.buffer.read(cx);
15789
15790        let Some(buffer) = multibuffer.as_singleton() else {
15791            return;
15792        };
15793
15794        let Some(workspace) = self.workspace() else {
15795            return;
15796        };
15797
15798        let locations = self
15799            .selections
15800            .disjoint_anchors()
15801            .iter()
15802            .map(|range| Location {
15803                buffer: buffer.clone(),
15804                range: range.start.text_anchor..range.end.text_anchor,
15805            })
15806            .collect::<Vec<_>>();
15807
15808        let title = multibuffer.title(cx).to_string();
15809
15810        cx.spawn_in(window, async move |_, cx| {
15811            workspace.update_in(cx, |workspace, window, cx| {
15812                Self::open_locations_in_multibuffer(
15813                    workspace,
15814                    locations,
15815                    format!("Selections for '{title}'"),
15816                    false,
15817                    MultibufferSelectionMode::All,
15818                    window,
15819                    cx,
15820                );
15821            })
15822        })
15823        .detach();
15824    }
15825
15826    /// Adds a row highlight for the given range. If a row has multiple highlights, the
15827    /// last highlight added will be used.
15828    ///
15829    /// If the range ends at the beginning of a line, then that line will not be highlighted.
15830    pub fn highlight_rows<T: 'static>(
15831        &mut self,
15832        range: Range<Anchor>,
15833        color: Hsla,
15834        should_autoscroll: bool,
15835        cx: &mut Context<Self>,
15836    ) {
15837        let snapshot = self.buffer().read(cx).snapshot(cx);
15838        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
15839        let ix = row_highlights.binary_search_by(|highlight| {
15840            Ordering::Equal
15841                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
15842                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
15843        });
15844
15845        if let Err(mut ix) = ix {
15846            let index = post_inc(&mut self.highlight_order);
15847
15848            // If this range intersects with the preceding highlight, then merge it with
15849            // the preceding highlight. Otherwise insert a new highlight.
15850            let mut merged = false;
15851            if ix > 0 {
15852                let prev_highlight = &mut row_highlights[ix - 1];
15853                if prev_highlight
15854                    .range
15855                    .end
15856                    .cmp(&range.start, &snapshot)
15857                    .is_ge()
15858                {
15859                    ix -= 1;
15860                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
15861                        prev_highlight.range.end = range.end;
15862                    }
15863                    merged = true;
15864                    prev_highlight.index = index;
15865                    prev_highlight.color = color;
15866                    prev_highlight.should_autoscroll = should_autoscroll;
15867                }
15868            }
15869
15870            if !merged {
15871                row_highlights.insert(
15872                    ix,
15873                    RowHighlight {
15874                        range: range.clone(),
15875                        index,
15876                        color,
15877                        should_autoscroll,
15878                    },
15879                );
15880            }
15881
15882            // If any of the following highlights intersect with this one, merge them.
15883            while let Some(next_highlight) = row_highlights.get(ix + 1) {
15884                let highlight = &row_highlights[ix];
15885                if next_highlight
15886                    .range
15887                    .start
15888                    .cmp(&highlight.range.end, &snapshot)
15889                    .is_le()
15890                {
15891                    if next_highlight
15892                        .range
15893                        .end
15894                        .cmp(&highlight.range.end, &snapshot)
15895                        .is_gt()
15896                    {
15897                        row_highlights[ix].range.end = next_highlight.range.end;
15898                    }
15899                    row_highlights.remove(ix + 1);
15900                } else {
15901                    break;
15902                }
15903            }
15904        }
15905    }
15906
15907    /// Remove any highlighted row ranges of the given type that intersect the
15908    /// given ranges.
15909    pub fn remove_highlighted_rows<T: 'static>(
15910        &mut self,
15911        ranges_to_remove: Vec<Range<Anchor>>,
15912        cx: &mut Context<Self>,
15913    ) {
15914        let snapshot = self.buffer().read(cx).snapshot(cx);
15915        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
15916        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
15917        row_highlights.retain(|highlight| {
15918            while let Some(range_to_remove) = ranges_to_remove.peek() {
15919                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
15920                    Ordering::Less | Ordering::Equal => {
15921                        ranges_to_remove.next();
15922                    }
15923                    Ordering::Greater => {
15924                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
15925                            Ordering::Less | Ordering::Equal => {
15926                                return false;
15927                            }
15928                            Ordering::Greater => break,
15929                        }
15930                    }
15931                }
15932            }
15933
15934            true
15935        })
15936    }
15937
15938    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
15939    pub fn clear_row_highlights<T: 'static>(&mut self) {
15940        self.highlighted_rows.remove(&TypeId::of::<T>());
15941    }
15942
15943    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
15944    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
15945        self.highlighted_rows
15946            .get(&TypeId::of::<T>())
15947            .map_or(&[] as &[_], |vec| vec.as_slice())
15948            .iter()
15949            .map(|highlight| (highlight.range.clone(), highlight.color))
15950    }
15951
15952    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
15953    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
15954    /// Allows to ignore certain kinds of highlights.
15955    pub fn highlighted_display_rows(
15956        &self,
15957        window: &mut Window,
15958        cx: &mut App,
15959    ) -> BTreeMap<DisplayRow, LineHighlight> {
15960        let snapshot = self.snapshot(window, cx);
15961        let mut used_highlight_orders = HashMap::default();
15962        self.highlighted_rows
15963            .iter()
15964            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
15965            .fold(
15966                BTreeMap::<DisplayRow, LineHighlight>::new(),
15967                |mut unique_rows, highlight| {
15968                    let start = highlight.range.start.to_display_point(&snapshot);
15969                    let end = highlight.range.end.to_display_point(&snapshot);
15970                    let start_row = start.row().0;
15971                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
15972                        && end.column() == 0
15973                    {
15974                        end.row().0.saturating_sub(1)
15975                    } else {
15976                        end.row().0
15977                    };
15978                    for row in start_row..=end_row {
15979                        let used_index =
15980                            used_highlight_orders.entry(row).or_insert(highlight.index);
15981                        if highlight.index >= *used_index {
15982                            *used_index = highlight.index;
15983                            unique_rows.insert(DisplayRow(row), highlight.color.into());
15984                        }
15985                    }
15986                    unique_rows
15987                },
15988            )
15989    }
15990
15991    pub fn highlighted_display_row_for_autoscroll(
15992        &self,
15993        snapshot: &DisplaySnapshot,
15994    ) -> Option<DisplayRow> {
15995        self.highlighted_rows
15996            .values()
15997            .flat_map(|highlighted_rows| highlighted_rows.iter())
15998            .filter_map(|highlight| {
15999                if highlight.should_autoscroll {
16000                    Some(highlight.range.start.to_display_point(snapshot).row())
16001                } else {
16002                    None
16003                }
16004            })
16005            .min()
16006    }
16007
16008    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16009        self.highlight_background::<SearchWithinRange>(
16010            ranges,
16011            |colors| colors.editor_document_highlight_read_background,
16012            cx,
16013        )
16014    }
16015
16016    pub fn set_breadcrumb_header(&mut self, new_header: String) {
16017        self.breadcrumb_header = Some(new_header);
16018    }
16019
16020    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16021        self.clear_background_highlights::<SearchWithinRange>(cx);
16022    }
16023
16024    pub fn highlight_background<T: 'static>(
16025        &mut self,
16026        ranges: &[Range<Anchor>],
16027        color_fetcher: fn(&ThemeColors) -> Hsla,
16028        cx: &mut Context<Self>,
16029    ) {
16030        self.background_highlights
16031            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16032        self.scrollbar_marker_state.dirty = true;
16033        cx.notify();
16034    }
16035
16036    pub fn clear_background_highlights<T: 'static>(
16037        &mut self,
16038        cx: &mut Context<Self>,
16039    ) -> Option<BackgroundHighlight> {
16040        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16041        if !text_highlights.1.is_empty() {
16042            self.scrollbar_marker_state.dirty = true;
16043            cx.notify();
16044        }
16045        Some(text_highlights)
16046    }
16047
16048    pub fn highlight_gutter<T: 'static>(
16049        &mut self,
16050        ranges: &[Range<Anchor>],
16051        color_fetcher: fn(&App) -> Hsla,
16052        cx: &mut Context<Self>,
16053    ) {
16054        self.gutter_highlights
16055            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16056        cx.notify();
16057    }
16058
16059    pub fn clear_gutter_highlights<T: 'static>(
16060        &mut self,
16061        cx: &mut Context<Self>,
16062    ) -> Option<GutterHighlight> {
16063        cx.notify();
16064        self.gutter_highlights.remove(&TypeId::of::<T>())
16065    }
16066
16067    #[cfg(feature = "test-support")]
16068    pub fn all_text_background_highlights(
16069        &self,
16070        window: &mut Window,
16071        cx: &mut Context<Self>,
16072    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16073        let snapshot = self.snapshot(window, cx);
16074        let buffer = &snapshot.buffer_snapshot;
16075        let start = buffer.anchor_before(0);
16076        let end = buffer.anchor_after(buffer.len());
16077        let theme = cx.theme().colors();
16078        self.background_highlights_in_range(start..end, &snapshot, theme)
16079    }
16080
16081    #[cfg(feature = "test-support")]
16082    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
16083        let snapshot = self.buffer().read(cx).snapshot(cx);
16084
16085        let highlights = self
16086            .background_highlights
16087            .get(&TypeId::of::<items::BufferSearchHighlights>());
16088
16089        if let Some((_color, ranges)) = highlights {
16090            ranges
16091                .iter()
16092                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
16093                .collect_vec()
16094        } else {
16095            vec![]
16096        }
16097    }
16098
16099    fn document_highlights_for_position<'a>(
16100        &'a self,
16101        position: Anchor,
16102        buffer: &'a MultiBufferSnapshot,
16103    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
16104        let read_highlights = self
16105            .background_highlights
16106            .get(&TypeId::of::<DocumentHighlightRead>())
16107            .map(|h| &h.1);
16108        let write_highlights = self
16109            .background_highlights
16110            .get(&TypeId::of::<DocumentHighlightWrite>())
16111            .map(|h| &h.1);
16112        let left_position = position.bias_left(buffer);
16113        let right_position = position.bias_right(buffer);
16114        read_highlights
16115            .into_iter()
16116            .chain(write_highlights)
16117            .flat_map(move |ranges| {
16118                let start_ix = match ranges.binary_search_by(|probe| {
16119                    let cmp = probe.end.cmp(&left_position, buffer);
16120                    if cmp.is_ge() {
16121                        Ordering::Greater
16122                    } else {
16123                        Ordering::Less
16124                    }
16125                }) {
16126                    Ok(i) | Err(i) => i,
16127                };
16128
16129                ranges[start_ix..]
16130                    .iter()
16131                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
16132            })
16133    }
16134
16135    pub fn has_background_highlights<T: 'static>(&self) -> bool {
16136        self.background_highlights
16137            .get(&TypeId::of::<T>())
16138            .map_or(false, |(_, highlights)| !highlights.is_empty())
16139    }
16140
16141    pub fn background_highlights_in_range(
16142        &self,
16143        search_range: Range<Anchor>,
16144        display_snapshot: &DisplaySnapshot,
16145        theme: &ThemeColors,
16146    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16147        let mut results = Vec::new();
16148        for (color_fetcher, ranges) in self.background_highlights.values() {
16149            let color = color_fetcher(theme);
16150            let start_ix = match ranges.binary_search_by(|probe| {
16151                let cmp = probe
16152                    .end
16153                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16154                if cmp.is_gt() {
16155                    Ordering::Greater
16156                } else {
16157                    Ordering::Less
16158                }
16159            }) {
16160                Ok(i) | Err(i) => i,
16161            };
16162            for range in &ranges[start_ix..] {
16163                if range
16164                    .start
16165                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16166                    .is_ge()
16167                {
16168                    break;
16169                }
16170
16171                let start = range.start.to_display_point(display_snapshot);
16172                let end = range.end.to_display_point(display_snapshot);
16173                results.push((start..end, color))
16174            }
16175        }
16176        results
16177    }
16178
16179    pub fn background_highlight_row_ranges<T: 'static>(
16180        &self,
16181        search_range: Range<Anchor>,
16182        display_snapshot: &DisplaySnapshot,
16183        count: usize,
16184    ) -> Vec<RangeInclusive<DisplayPoint>> {
16185        let mut results = Vec::new();
16186        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
16187            return vec![];
16188        };
16189
16190        let start_ix = match ranges.binary_search_by(|probe| {
16191            let cmp = probe
16192                .end
16193                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16194            if cmp.is_gt() {
16195                Ordering::Greater
16196            } else {
16197                Ordering::Less
16198            }
16199        }) {
16200            Ok(i) | Err(i) => i,
16201        };
16202        let mut push_region = |start: Option<Point>, end: Option<Point>| {
16203            if let (Some(start_display), Some(end_display)) = (start, end) {
16204                results.push(
16205                    start_display.to_display_point(display_snapshot)
16206                        ..=end_display.to_display_point(display_snapshot),
16207                );
16208            }
16209        };
16210        let mut start_row: Option<Point> = None;
16211        let mut end_row: Option<Point> = None;
16212        if ranges.len() > count {
16213            return Vec::new();
16214        }
16215        for range in &ranges[start_ix..] {
16216            if range
16217                .start
16218                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16219                .is_ge()
16220            {
16221                break;
16222            }
16223            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
16224            if let Some(current_row) = &end_row {
16225                if end.row == current_row.row {
16226                    continue;
16227                }
16228            }
16229            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
16230            if start_row.is_none() {
16231                assert_eq!(end_row, None);
16232                start_row = Some(start);
16233                end_row = Some(end);
16234                continue;
16235            }
16236            if let Some(current_end) = end_row.as_mut() {
16237                if start.row > current_end.row + 1 {
16238                    push_region(start_row, end_row);
16239                    start_row = Some(start);
16240                    end_row = Some(end);
16241                } else {
16242                    // Merge two hunks.
16243                    *current_end = end;
16244                }
16245            } else {
16246                unreachable!();
16247            }
16248        }
16249        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
16250        push_region(start_row, end_row);
16251        results
16252    }
16253
16254    pub fn gutter_highlights_in_range(
16255        &self,
16256        search_range: Range<Anchor>,
16257        display_snapshot: &DisplaySnapshot,
16258        cx: &App,
16259    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16260        let mut results = Vec::new();
16261        for (color_fetcher, ranges) in self.gutter_highlights.values() {
16262            let color = color_fetcher(cx);
16263            let start_ix = match ranges.binary_search_by(|probe| {
16264                let cmp = probe
16265                    .end
16266                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16267                if cmp.is_gt() {
16268                    Ordering::Greater
16269                } else {
16270                    Ordering::Less
16271                }
16272            }) {
16273                Ok(i) | Err(i) => i,
16274            };
16275            for range in &ranges[start_ix..] {
16276                if range
16277                    .start
16278                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16279                    .is_ge()
16280                {
16281                    break;
16282                }
16283
16284                let start = range.start.to_display_point(display_snapshot);
16285                let end = range.end.to_display_point(display_snapshot);
16286                results.push((start..end, color))
16287            }
16288        }
16289        results
16290    }
16291
16292    /// Get the text ranges corresponding to the redaction query
16293    pub fn redacted_ranges(
16294        &self,
16295        search_range: Range<Anchor>,
16296        display_snapshot: &DisplaySnapshot,
16297        cx: &App,
16298    ) -> Vec<Range<DisplayPoint>> {
16299        display_snapshot
16300            .buffer_snapshot
16301            .redacted_ranges(search_range, |file| {
16302                if let Some(file) = file {
16303                    file.is_private()
16304                        && EditorSettings::get(
16305                            Some(SettingsLocation {
16306                                worktree_id: file.worktree_id(cx),
16307                                path: file.path().as_ref(),
16308                            }),
16309                            cx,
16310                        )
16311                        .redact_private_values
16312                } else {
16313                    false
16314                }
16315            })
16316            .map(|range| {
16317                range.start.to_display_point(display_snapshot)
16318                    ..range.end.to_display_point(display_snapshot)
16319            })
16320            .collect()
16321    }
16322
16323    pub fn highlight_text<T: 'static>(
16324        &mut self,
16325        ranges: Vec<Range<Anchor>>,
16326        style: HighlightStyle,
16327        cx: &mut Context<Self>,
16328    ) {
16329        self.display_map.update(cx, |map, _| {
16330            map.highlight_text(TypeId::of::<T>(), ranges, style)
16331        });
16332        cx.notify();
16333    }
16334
16335    pub(crate) fn highlight_inlays<T: 'static>(
16336        &mut self,
16337        highlights: Vec<InlayHighlight>,
16338        style: HighlightStyle,
16339        cx: &mut Context<Self>,
16340    ) {
16341        self.display_map.update(cx, |map, _| {
16342            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
16343        });
16344        cx.notify();
16345    }
16346
16347    pub fn text_highlights<'a, T: 'static>(
16348        &'a self,
16349        cx: &'a App,
16350    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
16351        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
16352    }
16353
16354    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
16355        let cleared = self
16356            .display_map
16357            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
16358        if cleared {
16359            cx.notify();
16360        }
16361    }
16362
16363    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
16364        (self.read_only(cx) || self.blink_manager.read(cx).visible())
16365            && self.focus_handle.is_focused(window)
16366    }
16367
16368    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
16369        self.show_cursor_when_unfocused = is_enabled;
16370        cx.notify();
16371    }
16372
16373    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
16374        cx.notify();
16375    }
16376
16377    fn on_buffer_event(
16378        &mut self,
16379        multibuffer: &Entity<MultiBuffer>,
16380        event: &multi_buffer::Event,
16381        window: &mut Window,
16382        cx: &mut Context<Self>,
16383    ) {
16384        match event {
16385            multi_buffer::Event::Edited {
16386                singleton_buffer_edited,
16387                edited_buffer: buffer_edited,
16388            } => {
16389                self.scrollbar_marker_state.dirty = true;
16390                self.active_indent_guides_state.dirty = true;
16391                self.refresh_active_diagnostics(cx);
16392                self.refresh_code_actions(window, cx);
16393                if self.has_active_inline_completion() {
16394                    self.update_visible_inline_completion(window, cx);
16395                }
16396                if let Some(buffer) = buffer_edited {
16397                    let buffer_id = buffer.read(cx).remote_id();
16398                    if !self.registered_buffers.contains_key(&buffer_id) {
16399                        if let Some(project) = self.project.as_ref() {
16400                            project.update(cx, |project, cx| {
16401                                self.registered_buffers.insert(
16402                                    buffer_id,
16403                                    project.register_buffer_with_language_servers(&buffer, cx),
16404                                );
16405                            })
16406                        }
16407                    }
16408                }
16409                cx.emit(EditorEvent::BufferEdited);
16410                cx.emit(SearchEvent::MatchesInvalidated);
16411                if *singleton_buffer_edited {
16412                    if let Some(project) = &self.project {
16413                        #[allow(clippy::mutable_key_type)]
16414                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
16415                            multibuffer
16416                                .all_buffers()
16417                                .into_iter()
16418                                .filter_map(|buffer| {
16419                                    buffer.update(cx, |buffer, cx| {
16420                                        let language = buffer.language()?;
16421                                        let should_discard = project.update(cx, |project, cx| {
16422                                            project.is_local()
16423                                                && !project.has_language_servers_for(buffer, cx)
16424                                        });
16425                                        should_discard.not().then_some(language.clone())
16426                                    })
16427                                })
16428                                .collect::<HashSet<_>>()
16429                        });
16430                        if !languages_affected.is_empty() {
16431                            self.refresh_inlay_hints(
16432                                InlayHintRefreshReason::BufferEdited(languages_affected),
16433                                cx,
16434                            );
16435                        }
16436                    }
16437                }
16438
16439                let Some(project) = &self.project else { return };
16440                let (telemetry, is_via_ssh) = {
16441                    let project = project.read(cx);
16442                    let telemetry = project.client().telemetry().clone();
16443                    let is_via_ssh = project.is_via_ssh();
16444                    (telemetry, is_via_ssh)
16445                };
16446                refresh_linked_ranges(self, window, cx);
16447                telemetry.log_edit_event("editor", is_via_ssh);
16448            }
16449            multi_buffer::Event::ExcerptsAdded {
16450                buffer,
16451                predecessor,
16452                excerpts,
16453            } => {
16454                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16455                let buffer_id = buffer.read(cx).remote_id();
16456                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
16457                    if let Some(project) = &self.project {
16458                        get_uncommitted_diff_for_buffer(
16459                            project,
16460                            [buffer.clone()],
16461                            self.buffer.clone(),
16462                            cx,
16463                        )
16464                        .detach();
16465                    }
16466                }
16467                cx.emit(EditorEvent::ExcerptsAdded {
16468                    buffer: buffer.clone(),
16469                    predecessor: *predecessor,
16470                    excerpts: excerpts.clone(),
16471                });
16472                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
16473            }
16474            multi_buffer::Event::ExcerptsRemoved { ids } => {
16475                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
16476                let buffer = self.buffer.read(cx);
16477                self.registered_buffers
16478                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
16479                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
16480                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
16481            }
16482            multi_buffer::Event::ExcerptsEdited {
16483                excerpt_ids,
16484                buffer_ids,
16485            } => {
16486                self.display_map.update(cx, |map, cx| {
16487                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
16488                });
16489                cx.emit(EditorEvent::ExcerptsEdited {
16490                    ids: excerpt_ids.clone(),
16491                })
16492            }
16493            multi_buffer::Event::ExcerptsExpanded { ids } => {
16494                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
16495                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
16496            }
16497            multi_buffer::Event::Reparsed(buffer_id) => {
16498                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16499                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
16500
16501                cx.emit(EditorEvent::Reparsed(*buffer_id));
16502            }
16503            multi_buffer::Event::DiffHunksToggled => {
16504                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16505            }
16506            multi_buffer::Event::LanguageChanged(buffer_id) => {
16507                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
16508                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
16509                cx.emit(EditorEvent::Reparsed(*buffer_id));
16510                cx.notify();
16511            }
16512            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
16513            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
16514            multi_buffer::Event::FileHandleChanged
16515            | multi_buffer::Event::Reloaded
16516            | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
16517            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
16518            multi_buffer::Event::DiagnosticsUpdated => {
16519                self.refresh_active_diagnostics(cx);
16520                self.refresh_inline_diagnostics(true, window, cx);
16521                self.scrollbar_marker_state.dirty = true;
16522                cx.notify();
16523            }
16524            _ => {}
16525        };
16526    }
16527
16528    fn on_display_map_changed(
16529        &mut self,
16530        _: Entity<DisplayMap>,
16531        _: &mut Window,
16532        cx: &mut Context<Self>,
16533    ) {
16534        cx.notify();
16535    }
16536
16537    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16538        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16539        self.update_edit_prediction_settings(cx);
16540        self.refresh_inline_completion(true, false, window, cx);
16541        self.refresh_inlay_hints(
16542            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
16543                self.selections.newest_anchor().head(),
16544                &self.buffer.read(cx).snapshot(cx),
16545                cx,
16546            )),
16547            cx,
16548        );
16549
16550        let old_cursor_shape = self.cursor_shape;
16551
16552        {
16553            let editor_settings = EditorSettings::get_global(cx);
16554            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
16555            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
16556            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
16557        }
16558
16559        if old_cursor_shape != self.cursor_shape {
16560            cx.emit(EditorEvent::CursorShapeChanged);
16561        }
16562
16563        let project_settings = ProjectSettings::get_global(cx);
16564        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
16565
16566        if self.mode == EditorMode::Full {
16567            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
16568            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
16569            if self.show_inline_diagnostics != show_inline_diagnostics {
16570                self.show_inline_diagnostics = show_inline_diagnostics;
16571                self.refresh_inline_diagnostics(false, window, cx);
16572            }
16573
16574            if self.git_blame_inline_enabled != inline_blame_enabled {
16575                self.toggle_git_blame_inline_internal(false, window, cx);
16576            }
16577        }
16578
16579        cx.notify();
16580    }
16581
16582    pub fn set_searchable(&mut self, searchable: bool) {
16583        self.searchable = searchable;
16584    }
16585
16586    pub fn searchable(&self) -> bool {
16587        self.searchable
16588    }
16589
16590    fn open_proposed_changes_editor(
16591        &mut self,
16592        _: &OpenProposedChangesEditor,
16593        window: &mut Window,
16594        cx: &mut Context<Self>,
16595    ) {
16596        let Some(workspace) = self.workspace() else {
16597            cx.propagate();
16598            return;
16599        };
16600
16601        let selections = self.selections.all::<usize>(cx);
16602        let multi_buffer = self.buffer.read(cx);
16603        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16604        let mut new_selections_by_buffer = HashMap::default();
16605        for selection in selections {
16606            for (buffer, range, _) in
16607                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
16608            {
16609                let mut range = range.to_point(buffer);
16610                range.start.column = 0;
16611                range.end.column = buffer.line_len(range.end.row);
16612                new_selections_by_buffer
16613                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
16614                    .or_insert(Vec::new())
16615                    .push(range)
16616            }
16617        }
16618
16619        let proposed_changes_buffers = new_selections_by_buffer
16620            .into_iter()
16621            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
16622            .collect::<Vec<_>>();
16623        let proposed_changes_editor = cx.new(|cx| {
16624            ProposedChangesEditor::new(
16625                "Proposed changes",
16626                proposed_changes_buffers,
16627                self.project.clone(),
16628                window,
16629                cx,
16630            )
16631        });
16632
16633        window.defer(cx, move |window, cx| {
16634            workspace.update(cx, |workspace, cx| {
16635                workspace.active_pane().update(cx, |pane, cx| {
16636                    pane.add_item(
16637                        Box::new(proposed_changes_editor),
16638                        true,
16639                        true,
16640                        None,
16641                        window,
16642                        cx,
16643                    );
16644                });
16645            });
16646        });
16647    }
16648
16649    pub fn open_excerpts_in_split(
16650        &mut self,
16651        _: &OpenExcerptsSplit,
16652        window: &mut Window,
16653        cx: &mut Context<Self>,
16654    ) {
16655        self.open_excerpts_common(None, true, window, cx)
16656    }
16657
16658    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
16659        self.open_excerpts_common(None, false, window, cx)
16660    }
16661
16662    fn open_excerpts_common(
16663        &mut self,
16664        jump_data: Option<JumpData>,
16665        split: bool,
16666        window: &mut Window,
16667        cx: &mut Context<Self>,
16668    ) {
16669        let Some(workspace) = self.workspace() else {
16670            cx.propagate();
16671            return;
16672        };
16673
16674        if self.buffer.read(cx).is_singleton() {
16675            cx.propagate();
16676            return;
16677        }
16678
16679        let mut new_selections_by_buffer = HashMap::default();
16680        match &jump_data {
16681            Some(JumpData::MultiBufferPoint {
16682                excerpt_id,
16683                position,
16684                anchor,
16685                line_offset_from_top,
16686            }) => {
16687                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
16688                if let Some(buffer) = multi_buffer_snapshot
16689                    .buffer_id_for_excerpt(*excerpt_id)
16690                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
16691                {
16692                    let buffer_snapshot = buffer.read(cx).snapshot();
16693                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
16694                        language::ToPoint::to_point(anchor, &buffer_snapshot)
16695                    } else {
16696                        buffer_snapshot.clip_point(*position, Bias::Left)
16697                    };
16698                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
16699                    new_selections_by_buffer.insert(
16700                        buffer,
16701                        (
16702                            vec![jump_to_offset..jump_to_offset],
16703                            Some(*line_offset_from_top),
16704                        ),
16705                    );
16706                }
16707            }
16708            Some(JumpData::MultiBufferRow {
16709                row,
16710                line_offset_from_top,
16711            }) => {
16712                let point = MultiBufferPoint::new(row.0, 0);
16713                if let Some((buffer, buffer_point, _)) =
16714                    self.buffer.read(cx).point_to_buffer_point(point, cx)
16715                {
16716                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
16717                    new_selections_by_buffer
16718                        .entry(buffer)
16719                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
16720                        .0
16721                        .push(buffer_offset..buffer_offset)
16722                }
16723            }
16724            None => {
16725                let selections = self.selections.all::<usize>(cx);
16726                let multi_buffer = self.buffer.read(cx);
16727                for selection in selections {
16728                    for (snapshot, range, _, anchor) in multi_buffer
16729                        .snapshot(cx)
16730                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
16731                    {
16732                        if let Some(anchor) = anchor {
16733                            // selection is in a deleted hunk
16734                            let Some(buffer_id) = anchor.buffer_id else {
16735                                continue;
16736                            };
16737                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
16738                                continue;
16739                            };
16740                            let offset = text::ToOffset::to_offset(
16741                                &anchor.text_anchor,
16742                                &buffer_handle.read(cx).snapshot(),
16743                            );
16744                            let range = offset..offset;
16745                            new_selections_by_buffer
16746                                .entry(buffer_handle)
16747                                .or_insert((Vec::new(), None))
16748                                .0
16749                                .push(range)
16750                        } else {
16751                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
16752                            else {
16753                                continue;
16754                            };
16755                            new_selections_by_buffer
16756                                .entry(buffer_handle)
16757                                .or_insert((Vec::new(), None))
16758                                .0
16759                                .push(range)
16760                        }
16761                    }
16762                }
16763            }
16764        }
16765
16766        if new_selections_by_buffer.is_empty() {
16767            return;
16768        }
16769
16770        // We defer the pane interaction because we ourselves are a workspace item
16771        // and activating a new item causes the pane to call a method on us reentrantly,
16772        // which panics if we're on the stack.
16773        window.defer(cx, move |window, cx| {
16774            workspace.update(cx, |workspace, cx| {
16775                let pane = if split {
16776                    workspace.adjacent_pane(window, cx)
16777                } else {
16778                    workspace.active_pane().clone()
16779                };
16780
16781                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
16782                    let editor = buffer
16783                        .read(cx)
16784                        .file()
16785                        .is_none()
16786                        .then(|| {
16787                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
16788                            // so `workspace.open_project_item` will never find them, always opening a new editor.
16789                            // Instead, we try to activate the existing editor in the pane first.
16790                            let (editor, pane_item_index) =
16791                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
16792                                    let editor = item.downcast::<Editor>()?;
16793                                    let singleton_buffer =
16794                                        editor.read(cx).buffer().read(cx).as_singleton()?;
16795                                    if singleton_buffer == buffer {
16796                                        Some((editor, i))
16797                                    } else {
16798                                        None
16799                                    }
16800                                })?;
16801                            pane.update(cx, |pane, cx| {
16802                                pane.activate_item(pane_item_index, true, true, window, cx)
16803                            });
16804                            Some(editor)
16805                        })
16806                        .flatten()
16807                        .unwrap_or_else(|| {
16808                            workspace.open_project_item::<Self>(
16809                                pane.clone(),
16810                                buffer,
16811                                true,
16812                                true,
16813                                window,
16814                                cx,
16815                            )
16816                        });
16817
16818                    editor.update(cx, |editor, cx| {
16819                        let autoscroll = match scroll_offset {
16820                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
16821                            None => Autoscroll::newest(),
16822                        };
16823                        let nav_history = editor.nav_history.take();
16824                        editor.change_selections(Some(autoscroll), window, cx, |s| {
16825                            s.select_ranges(ranges);
16826                        });
16827                        editor.nav_history = nav_history;
16828                    });
16829                }
16830            })
16831        });
16832    }
16833
16834    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
16835        let snapshot = self.buffer.read(cx).read(cx);
16836        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
16837        Some(
16838            ranges
16839                .iter()
16840                .map(move |range| {
16841                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
16842                })
16843                .collect(),
16844        )
16845    }
16846
16847    fn selection_replacement_ranges(
16848        &self,
16849        range: Range<OffsetUtf16>,
16850        cx: &mut App,
16851    ) -> Vec<Range<OffsetUtf16>> {
16852        let selections = self.selections.all::<OffsetUtf16>(cx);
16853        let newest_selection = selections
16854            .iter()
16855            .max_by_key(|selection| selection.id)
16856            .unwrap();
16857        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
16858        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
16859        let snapshot = self.buffer.read(cx).read(cx);
16860        selections
16861            .into_iter()
16862            .map(|mut selection| {
16863                selection.start.0 =
16864                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
16865                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
16866                snapshot.clip_offset_utf16(selection.start, Bias::Left)
16867                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
16868            })
16869            .collect()
16870    }
16871
16872    fn report_editor_event(
16873        &self,
16874        event_type: &'static str,
16875        file_extension: Option<String>,
16876        cx: &App,
16877    ) {
16878        if cfg!(any(test, feature = "test-support")) {
16879            return;
16880        }
16881
16882        let Some(project) = &self.project else { return };
16883
16884        // If None, we are in a file without an extension
16885        let file = self
16886            .buffer
16887            .read(cx)
16888            .as_singleton()
16889            .and_then(|b| b.read(cx).file());
16890        let file_extension = file_extension.or(file
16891            .as_ref()
16892            .and_then(|file| Path::new(file.file_name(cx)).extension())
16893            .and_then(|e| e.to_str())
16894            .map(|a| a.to_string()));
16895
16896        let vim_mode = cx
16897            .global::<SettingsStore>()
16898            .raw_user_settings()
16899            .get("vim_mode")
16900            == Some(&serde_json::Value::Bool(true));
16901
16902        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
16903        let copilot_enabled = edit_predictions_provider
16904            == language::language_settings::EditPredictionProvider::Copilot;
16905        let copilot_enabled_for_language = self
16906            .buffer
16907            .read(cx)
16908            .language_settings(cx)
16909            .show_edit_predictions;
16910
16911        let project = project.read(cx);
16912        telemetry::event!(
16913            event_type,
16914            file_extension,
16915            vim_mode,
16916            copilot_enabled,
16917            copilot_enabled_for_language,
16918            edit_predictions_provider,
16919            is_via_ssh = project.is_via_ssh(),
16920        );
16921    }
16922
16923    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
16924    /// with each line being an array of {text, highlight} objects.
16925    fn copy_highlight_json(
16926        &mut self,
16927        _: &CopyHighlightJson,
16928        window: &mut Window,
16929        cx: &mut Context<Self>,
16930    ) {
16931        #[derive(Serialize)]
16932        struct Chunk<'a> {
16933            text: String,
16934            highlight: Option<&'a str>,
16935        }
16936
16937        let snapshot = self.buffer.read(cx).snapshot(cx);
16938        let range = self
16939            .selected_text_range(false, window, cx)
16940            .and_then(|selection| {
16941                if selection.range.is_empty() {
16942                    None
16943                } else {
16944                    Some(selection.range)
16945                }
16946            })
16947            .unwrap_or_else(|| 0..snapshot.len());
16948
16949        let chunks = snapshot.chunks(range, true);
16950        let mut lines = Vec::new();
16951        let mut line: VecDeque<Chunk> = VecDeque::new();
16952
16953        let Some(style) = self.style.as_ref() else {
16954            return;
16955        };
16956
16957        for chunk in chunks {
16958            let highlight = chunk
16959                .syntax_highlight_id
16960                .and_then(|id| id.name(&style.syntax));
16961            let mut chunk_lines = chunk.text.split('\n').peekable();
16962            while let Some(text) = chunk_lines.next() {
16963                let mut merged_with_last_token = false;
16964                if let Some(last_token) = line.back_mut() {
16965                    if last_token.highlight == highlight {
16966                        last_token.text.push_str(text);
16967                        merged_with_last_token = true;
16968                    }
16969                }
16970
16971                if !merged_with_last_token {
16972                    line.push_back(Chunk {
16973                        text: text.into(),
16974                        highlight,
16975                    });
16976                }
16977
16978                if chunk_lines.peek().is_some() {
16979                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
16980                        line.pop_front();
16981                    }
16982                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
16983                        line.pop_back();
16984                    }
16985
16986                    lines.push(mem::take(&mut line));
16987                }
16988            }
16989        }
16990
16991        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
16992            return;
16993        };
16994        cx.write_to_clipboard(ClipboardItem::new_string(lines));
16995    }
16996
16997    pub fn open_context_menu(
16998        &mut self,
16999        _: &OpenContextMenu,
17000        window: &mut Window,
17001        cx: &mut Context<Self>,
17002    ) {
17003        self.request_autoscroll(Autoscroll::newest(), cx);
17004        let position = self.selections.newest_display(cx).start;
17005        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17006    }
17007
17008    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17009        &self.inlay_hint_cache
17010    }
17011
17012    pub fn replay_insert_event(
17013        &mut self,
17014        text: &str,
17015        relative_utf16_range: Option<Range<isize>>,
17016        window: &mut Window,
17017        cx: &mut Context<Self>,
17018    ) {
17019        if !self.input_enabled {
17020            cx.emit(EditorEvent::InputIgnored { text: text.into() });
17021            return;
17022        }
17023        if let Some(relative_utf16_range) = relative_utf16_range {
17024            let selections = self.selections.all::<OffsetUtf16>(cx);
17025            self.change_selections(None, window, cx, |s| {
17026                let new_ranges = selections.into_iter().map(|range| {
17027                    let start = OffsetUtf16(
17028                        range
17029                            .head()
17030                            .0
17031                            .saturating_add_signed(relative_utf16_range.start),
17032                    );
17033                    let end = OffsetUtf16(
17034                        range
17035                            .head()
17036                            .0
17037                            .saturating_add_signed(relative_utf16_range.end),
17038                    );
17039                    start..end
17040                });
17041                s.select_ranges(new_ranges);
17042            });
17043        }
17044
17045        self.handle_input(text, window, cx);
17046    }
17047
17048    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
17049        let Some(provider) = self.semantics_provider.as_ref() else {
17050            return false;
17051        };
17052
17053        let mut supports = false;
17054        self.buffer().update(cx, |this, cx| {
17055            this.for_each_buffer(|buffer| {
17056                supports |= provider.supports_inlay_hints(buffer, cx);
17057            });
17058        });
17059
17060        supports
17061    }
17062
17063    pub fn is_focused(&self, window: &Window) -> bool {
17064        self.focus_handle.is_focused(window)
17065    }
17066
17067    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17068        cx.emit(EditorEvent::Focused);
17069
17070        if let Some(descendant) = self
17071            .last_focused_descendant
17072            .take()
17073            .and_then(|descendant| descendant.upgrade())
17074        {
17075            window.focus(&descendant);
17076        } else {
17077            if let Some(blame) = self.blame.as_ref() {
17078                blame.update(cx, GitBlame::focus)
17079            }
17080
17081            self.blink_manager.update(cx, BlinkManager::enable);
17082            self.show_cursor_names(window, cx);
17083            self.buffer.update(cx, |buffer, cx| {
17084                buffer.finalize_last_transaction(cx);
17085                if self.leader_peer_id.is_none() {
17086                    buffer.set_active_selections(
17087                        &self.selections.disjoint_anchors(),
17088                        self.selections.line_mode,
17089                        self.cursor_shape,
17090                        cx,
17091                    );
17092                }
17093            });
17094        }
17095    }
17096
17097    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17098        cx.emit(EditorEvent::FocusedIn)
17099    }
17100
17101    fn handle_focus_out(
17102        &mut self,
17103        event: FocusOutEvent,
17104        _window: &mut Window,
17105        cx: &mut Context<Self>,
17106    ) {
17107        if event.blurred != self.focus_handle {
17108            self.last_focused_descendant = Some(event.blurred);
17109        }
17110        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
17111    }
17112
17113    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17114        self.blink_manager.update(cx, BlinkManager::disable);
17115        self.buffer
17116            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
17117
17118        if let Some(blame) = self.blame.as_ref() {
17119            blame.update(cx, GitBlame::blur)
17120        }
17121        if !self.hover_state.focused(window, cx) {
17122            hide_hover(self, cx);
17123        }
17124        if !self
17125            .context_menu
17126            .borrow()
17127            .as_ref()
17128            .is_some_and(|context_menu| context_menu.focused(window, cx))
17129        {
17130            self.hide_context_menu(window, cx);
17131        }
17132        self.discard_inline_completion(false, cx);
17133        cx.emit(EditorEvent::Blurred);
17134        cx.notify();
17135    }
17136
17137    pub fn register_action<A: Action>(
17138        &mut self,
17139        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
17140    ) -> Subscription {
17141        let id = self.next_editor_action_id.post_inc();
17142        let listener = Arc::new(listener);
17143        self.editor_actions.borrow_mut().insert(
17144            id,
17145            Box::new(move |window, _| {
17146                let listener = listener.clone();
17147                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
17148                    let action = action.downcast_ref().unwrap();
17149                    if phase == DispatchPhase::Bubble {
17150                        listener(action, window, cx)
17151                    }
17152                })
17153            }),
17154        );
17155
17156        let editor_actions = self.editor_actions.clone();
17157        Subscription::new(move || {
17158            editor_actions.borrow_mut().remove(&id);
17159        })
17160    }
17161
17162    pub fn file_header_size(&self) -> u32 {
17163        FILE_HEADER_HEIGHT
17164    }
17165
17166    pub fn restore(
17167        &mut self,
17168        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
17169        window: &mut Window,
17170        cx: &mut Context<Self>,
17171    ) {
17172        let workspace = self.workspace();
17173        let project = self.project.as_ref();
17174        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
17175            let mut tasks = Vec::new();
17176            for (buffer_id, changes) in revert_changes {
17177                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
17178                    buffer.update(cx, |buffer, cx| {
17179                        buffer.edit(
17180                            changes
17181                                .into_iter()
17182                                .map(|(range, text)| (range, text.to_string())),
17183                            None,
17184                            cx,
17185                        );
17186                    });
17187
17188                    if let Some(project) =
17189                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
17190                    {
17191                        project.update(cx, |project, cx| {
17192                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
17193                        })
17194                    }
17195                }
17196            }
17197            tasks
17198        });
17199        cx.spawn_in(window, async move |_, cx| {
17200            for (buffer, task) in save_tasks {
17201                let result = task.await;
17202                if result.is_err() {
17203                    let Some(path) = buffer
17204                        .read_with(cx, |buffer, cx| buffer.project_path(cx))
17205                        .ok()
17206                    else {
17207                        continue;
17208                    };
17209                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
17210                        let Some(task) = cx
17211                            .update_window_entity(&workspace, |workspace, window, cx| {
17212                                workspace
17213                                    .open_path_preview(path, None, false, false, false, window, cx)
17214                            })
17215                            .ok()
17216                        else {
17217                            continue;
17218                        };
17219                        task.await.log_err();
17220                    }
17221                }
17222            }
17223        })
17224        .detach();
17225        self.change_selections(None, window, cx, |selections| selections.refresh());
17226    }
17227
17228    pub fn to_pixel_point(
17229        &self,
17230        source: multi_buffer::Anchor,
17231        editor_snapshot: &EditorSnapshot,
17232        window: &mut Window,
17233    ) -> Option<gpui::Point<Pixels>> {
17234        let source_point = source.to_display_point(editor_snapshot);
17235        self.display_to_pixel_point(source_point, editor_snapshot, window)
17236    }
17237
17238    pub fn display_to_pixel_point(
17239        &self,
17240        source: DisplayPoint,
17241        editor_snapshot: &EditorSnapshot,
17242        window: &mut Window,
17243    ) -> Option<gpui::Point<Pixels>> {
17244        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
17245        let text_layout_details = self.text_layout_details(window);
17246        let scroll_top = text_layout_details
17247            .scroll_anchor
17248            .scroll_position(editor_snapshot)
17249            .y;
17250
17251        if source.row().as_f32() < scroll_top.floor() {
17252            return None;
17253        }
17254        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
17255        let source_y = line_height * (source.row().as_f32() - scroll_top);
17256        Some(gpui::Point::new(source_x, source_y))
17257    }
17258
17259    pub fn has_visible_completions_menu(&self) -> bool {
17260        !self.edit_prediction_preview_is_active()
17261            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
17262                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
17263            })
17264    }
17265
17266    pub fn register_addon<T: Addon>(&mut self, instance: T) {
17267        self.addons
17268            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
17269    }
17270
17271    pub fn unregister_addon<T: Addon>(&mut self) {
17272        self.addons.remove(&std::any::TypeId::of::<T>());
17273    }
17274
17275    pub fn addon<T: Addon>(&self) -> Option<&T> {
17276        let type_id = std::any::TypeId::of::<T>();
17277        self.addons
17278            .get(&type_id)
17279            .and_then(|item| item.to_any().downcast_ref::<T>())
17280    }
17281
17282    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
17283        let text_layout_details = self.text_layout_details(window);
17284        let style = &text_layout_details.editor_style;
17285        let font_id = window.text_system().resolve_font(&style.text.font());
17286        let font_size = style.text.font_size.to_pixels(window.rem_size());
17287        let line_height = style.text.line_height_in_pixels(window.rem_size());
17288        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
17289
17290        gpui::Size::new(em_width, line_height)
17291    }
17292
17293    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
17294        self.load_diff_task.clone()
17295    }
17296
17297    fn read_metadata_from_db(
17298        &mut self,
17299        item_id: u64,
17300        workspace_id: WorkspaceId,
17301        window: &mut Window,
17302        cx: &mut Context<Editor>,
17303    ) {
17304        if self.is_singleton(cx)
17305            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
17306        {
17307            let buffer_snapshot = OnceCell::new();
17308
17309            if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
17310                if !selections.is_empty() {
17311                    let snapshot =
17312                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
17313                    self.change_selections(None, window, cx, |s| {
17314                        s.select_ranges(selections.into_iter().map(|(start, end)| {
17315                            snapshot.clip_offset(start, Bias::Left)
17316                                ..snapshot.clip_offset(end, Bias::Right)
17317                        }));
17318                    });
17319                }
17320            };
17321
17322            if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
17323                if !folds.is_empty() {
17324                    let snapshot =
17325                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
17326                    self.fold_ranges(
17327                        folds
17328                            .into_iter()
17329                            .map(|(start, end)| {
17330                                snapshot.clip_offset(start, Bias::Left)
17331                                    ..snapshot.clip_offset(end, Bias::Right)
17332                            })
17333                            .collect(),
17334                        false,
17335                        window,
17336                        cx,
17337                    );
17338                }
17339            }
17340        }
17341
17342        self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
17343    }
17344}
17345
17346fn insert_extra_newline_brackets(
17347    buffer: &MultiBufferSnapshot,
17348    range: Range<usize>,
17349    language: &language::LanguageScope,
17350) -> bool {
17351    let leading_whitespace_len = buffer
17352        .reversed_chars_at(range.start)
17353        .take_while(|c| c.is_whitespace() && *c != '\n')
17354        .map(|c| c.len_utf8())
17355        .sum::<usize>();
17356    let trailing_whitespace_len = buffer
17357        .chars_at(range.end)
17358        .take_while(|c| c.is_whitespace() && *c != '\n')
17359        .map(|c| c.len_utf8())
17360        .sum::<usize>();
17361    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
17362
17363    language.brackets().any(|(pair, enabled)| {
17364        let pair_start = pair.start.trim_end();
17365        let pair_end = pair.end.trim_start();
17366
17367        enabled
17368            && pair.newline
17369            && buffer.contains_str_at(range.end, pair_end)
17370            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
17371    })
17372}
17373
17374fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
17375    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
17376        [(buffer, range, _)] => (*buffer, range.clone()),
17377        _ => return false,
17378    };
17379    let pair = {
17380        let mut result: Option<BracketMatch> = None;
17381
17382        for pair in buffer
17383            .all_bracket_ranges(range.clone())
17384            .filter(move |pair| {
17385                pair.open_range.start <= range.start && pair.close_range.end >= range.end
17386            })
17387        {
17388            let len = pair.close_range.end - pair.open_range.start;
17389
17390            if let Some(existing) = &result {
17391                let existing_len = existing.close_range.end - existing.open_range.start;
17392                if len > existing_len {
17393                    continue;
17394                }
17395            }
17396
17397            result = Some(pair);
17398        }
17399
17400        result
17401    };
17402    let Some(pair) = pair else {
17403        return false;
17404    };
17405    pair.newline_only
17406        && buffer
17407            .chars_for_range(pair.open_range.end..range.start)
17408            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
17409            .all(|c| c.is_whitespace() && c != '\n')
17410}
17411
17412fn get_uncommitted_diff_for_buffer(
17413    project: &Entity<Project>,
17414    buffers: impl IntoIterator<Item = Entity<Buffer>>,
17415    buffer: Entity<MultiBuffer>,
17416    cx: &mut App,
17417) -> Task<()> {
17418    let mut tasks = Vec::new();
17419    project.update(cx, |project, cx| {
17420        for buffer in buffers {
17421            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
17422        }
17423    });
17424    cx.spawn(async move |cx| {
17425        let diffs = future::join_all(tasks).await;
17426        buffer
17427            .update(cx, |buffer, cx| {
17428                for diff in diffs.into_iter().flatten() {
17429                    buffer.add_diff(diff, cx);
17430                }
17431            })
17432            .ok();
17433    })
17434}
17435
17436fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
17437    let tab_size = tab_size.get() as usize;
17438    let mut width = offset;
17439
17440    for ch in text.chars() {
17441        width += if ch == '\t' {
17442            tab_size - (width % tab_size)
17443        } else {
17444            1
17445        };
17446    }
17447
17448    width - offset
17449}
17450
17451#[cfg(test)]
17452mod tests {
17453    use super::*;
17454
17455    #[test]
17456    fn test_string_size_with_expanded_tabs() {
17457        let nz = |val| NonZeroU32::new(val).unwrap();
17458        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
17459        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
17460        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
17461        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
17462        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
17463        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
17464        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
17465        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
17466    }
17467}
17468
17469/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
17470struct WordBreakingTokenizer<'a> {
17471    input: &'a str,
17472}
17473
17474impl<'a> WordBreakingTokenizer<'a> {
17475    fn new(input: &'a str) -> Self {
17476        Self { input }
17477    }
17478}
17479
17480fn is_char_ideographic(ch: char) -> bool {
17481    use unicode_script::Script::*;
17482    use unicode_script::UnicodeScript;
17483    matches!(ch.script(), Han | Tangut | Yi)
17484}
17485
17486fn is_grapheme_ideographic(text: &str) -> bool {
17487    text.chars().any(is_char_ideographic)
17488}
17489
17490fn is_grapheme_whitespace(text: &str) -> bool {
17491    text.chars().any(|x| x.is_whitespace())
17492}
17493
17494fn should_stay_with_preceding_ideograph(text: &str) -> bool {
17495    text.chars().next().map_or(false, |ch| {
17496        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
17497    })
17498}
17499
17500#[derive(PartialEq, Eq, Debug, Clone, Copy)]
17501enum WordBreakToken<'a> {
17502    Word { token: &'a str, grapheme_len: usize },
17503    InlineWhitespace { token: &'a str, grapheme_len: usize },
17504    Newline,
17505}
17506
17507impl<'a> Iterator for WordBreakingTokenizer<'a> {
17508    /// Yields a span, the count of graphemes in the token, and whether it was
17509    /// whitespace. Note that it also breaks at word boundaries.
17510    type Item = WordBreakToken<'a>;
17511
17512    fn next(&mut self) -> Option<Self::Item> {
17513        use unicode_segmentation::UnicodeSegmentation;
17514        if self.input.is_empty() {
17515            return None;
17516        }
17517
17518        let mut iter = self.input.graphemes(true).peekable();
17519        let mut offset = 0;
17520        let mut grapheme_len = 0;
17521        if let Some(first_grapheme) = iter.next() {
17522            let is_newline = first_grapheme == "\n";
17523            let is_whitespace = is_grapheme_whitespace(first_grapheme);
17524            offset += first_grapheme.len();
17525            grapheme_len += 1;
17526            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
17527                if let Some(grapheme) = iter.peek().copied() {
17528                    if should_stay_with_preceding_ideograph(grapheme) {
17529                        offset += grapheme.len();
17530                        grapheme_len += 1;
17531                    }
17532                }
17533            } else {
17534                let mut words = self.input[offset..].split_word_bound_indices().peekable();
17535                let mut next_word_bound = words.peek().copied();
17536                if next_word_bound.map_or(false, |(i, _)| i == 0) {
17537                    next_word_bound = words.next();
17538                }
17539                while let Some(grapheme) = iter.peek().copied() {
17540                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
17541                        break;
17542                    };
17543                    if is_grapheme_whitespace(grapheme) != is_whitespace
17544                        || (grapheme == "\n") != is_newline
17545                    {
17546                        break;
17547                    };
17548                    offset += grapheme.len();
17549                    grapheme_len += 1;
17550                    iter.next();
17551                }
17552            }
17553            let token = &self.input[..offset];
17554            self.input = &self.input[offset..];
17555            if token == "\n" {
17556                Some(WordBreakToken::Newline)
17557            } else if is_whitespace {
17558                Some(WordBreakToken::InlineWhitespace {
17559                    token,
17560                    grapheme_len,
17561                })
17562            } else {
17563                Some(WordBreakToken::Word {
17564                    token,
17565                    grapheme_len,
17566                })
17567            }
17568        } else {
17569            None
17570        }
17571    }
17572}
17573
17574#[test]
17575fn test_word_breaking_tokenizer() {
17576    let tests: &[(&str, &[WordBreakToken<'static>])] = &[
17577        ("", &[]),
17578        ("  ", &[whitespace("  ", 2)]),
17579        ("Ʒ", &[word("Ʒ", 1)]),
17580        ("Ǽ", &[word("Ǽ", 1)]),
17581        ("", &[word("", 1)]),
17582        ("⋑⋑", &[word("⋑⋑", 2)]),
17583        (
17584            "原理,进而",
17585            &[word("", 1), word("理,", 2), word("", 1), word("", 1)],
17586        ),
17587        (
17588            "hello world",
17589            &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
17590        ),
17591        (
17592            "hello, world",
17593            &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
17594        ),
17595        (
17596            "  hello world",
17597            &[
17598                whitespace("  ", 2),
17599                word("hello", 5),
17600                whitespace(" ", 1),
17601                word("world", 5),
17602            ],
17603        ),
17604        (
17605            "这是什么 \n 钢笔",
17606            &[
17607                word("", 1),
17608                word("", 1),
17609                word("", 1),
17610                word("", 1),
17611                whitespace(" ", 1),
17612                newline(),
17613                whitespace(" ", 1),
17614                word("", 1),
17615                word("", 1),
17616            ],
17617        ),
17618        (" mutton", &[whitespace("", 1), word("mutton", 6)]),
17619    ];
17620
17621    fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
17622        WordBreakToken::Word {
17623            token,
17624            grapheme_len,
17625        }
17626    }
17627
17628    fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
17629        WordBreakToken::InlineWhitespace {
17630            token,
17631            grapheme_len,
17632        }
17633    }
17634
17635    fn newline() -> WordBreakToken<'static> {
17636        WordBreakToken::Newline
17637    }
17638
17639    for (input, result) in tests {
17640        assert_eq!(
17641            WordBreakingTokenizer::new(input)
17642                .collect::<Vec<_>>()
17643                .as_slice(),
17644            *result,
17645        );
17646    }
17647}
17648
17649fn wrap_with_prefix(
17650    line_prefix: String,
17651    unwrapped_text: String,
17652    wrap_column: usize,
17653    tab_size: NonZeroU32,
17654    preserve_existing_whitespace: bool,
17655) -> String {
17656    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
17657    let mut wrapped_text = String::new();
17658    let mut current_line = line_prefix.clone();
17659
17660    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
17661    let mut current_line_len = line_prefix_len;
17662    let mut in_whitespace = false;
17663    for token in tokenizer {
17664        let have_preceding_whitespace = in_whitespace;
17665        match token {
17666            WordBreakToken::Word {
17667                token,
17668                grapheme_len,
17669            } => {
17670                in_whitespace = false;
17671                if current_line_len + grapheme_len > wrap_column
17672                    && current_line_len != line_prefix_len
17673                {
17674                    wrapped_text.push_str(current_line.trim_end());
17675                    wrapped_text.push('\n');
17676                    current_line.truncate(line_prefix.len());
17677                    current_line_len = line_prefix_len;
17678                }
17679                current_line.push_str(token);
17680                current_line_len += grapheme_len;
17681            }
17682            WordBreakToken::InlineWhitespace {
17683                mut token,
17684                mut grapheme_len,
17685            } => {
17686                in_whitespace = true;
17687                if have_preceding_whitespace && !preserve_existing_whitespace {
17688                    continue;
17689                }
17690                if !preserve_existing_whitespace {
17691                    token = " ";
17692                    grapheme_len = 1;
17693                }
17694                if current_line_len + grapheme_len > wrap_column {
17695                    wrapped_text.push_str(current_line.trim_end());
17696                    wrapped_text.push('\n');
17697                    current_line.truncate(line_prefix.len());
17698                    current_line_len = line_prefix_len;
17699                } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
17700                    current_line.push_str(token);
17701                    current_line_len += grapheme_len;
17702                }
17703            }
17704            WordBreakToken::Newline => {
17705                in_whitespace = true;
17706                if preserve_existing_whitespace {
17707                    wrapped_text.push_str(current_line.trim_end());
17708                    wrapped_text.push('\n');
17709                    current_line.truncate(line_prefix.len());
17710                    current_line_len = line_prefix_len;
17711                } else if have_preceding_whitespace {
17712                    continue;
17713                } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
17714                {
17715                    wrapped_text.push_str(current_line.trim_end());
17716                    wrapped_text.push('\n');
17717                    current_line.truncate(line_prefix.len());
17718                    current_line_len = line_prefix_len;
17719                } else if current_line_len != line_prefix_len {
17720                    current_line.push(' ');
17721                    current_line_len += 1;
17722                }
17723            }
17724        }
17725    }
17726
17727    if !current_line.is_empty() {
17728        wrapped_text.push_str(&current_line);
17729    }
17730    wrapped_text
17731}
17732
17733#[test]
17734fn test_wrap_with_prefix() {
17735    assert_eq!(
17736        wrap_with_prefix(
17737            "# ".to_string(),
17738            "abcdefg".to_string(),
17739            4,
17740            NonZeroU32::new(4).unwrap(),
17741            false,
17742        ),
17743        "# abcdefg"
17744    );
17745    assert_eq!(
17746        wrap_with_prefix(
17747            "".to_string(),
17748            "\thello world".to_string(),
17749            8,
17750            NonZeroU32::new(4).unwrap(),
17751            false,
17752        ),
17753        "hello\nworld"
17754    );
17755    assert_eq!(
17756        wrap_with_prefix(
17757            "// ".to_string(),
17758            "xx \nyy zz aa bb cc".to_string(),
17759            12,
17760            NonZeroU32::new(4).unwrap(),
17761            false,
17762        ),
17763        "// xx yy zz\n// aa bb cc"
17764    );
17765    assert_eq!(
17766        wrap_with_prefix(
17767            String::new(),
17768            "这是什么 \n 钢笔".to_string(),
17769            3,
17770            NonZeroU32::new(4).unwrap(),
17771            false,
17772        ),
17773        "这是什\n么 钢\n"
17774    );
17775}
17776
17777pub trait CollaborationHub {
17778    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
17779    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
17780    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
17781}
17782
17783impl CollaborationHub for Entity<Project> {
17784    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
17785        self.read(cx).collaborators()
17786    }
17787
17788    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
17789        self.read(cx).user_store().read(cx).participant_indices()
17790    }
17791
17792    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
17793        let this = self.read(cx);
17794        let user_ids = this.collaborators().values().map(|c| c.user_id);
17795        this.user_store().read_with(cx, |user_store, cx| {
17796            user_store.participant_names(user_ids, cx)
17797        })
17798    }
17799}
17800
17801pub trait SemanticsProvider {
17802    fn hover(
17803        &self,
17804        buffer: &Entity<Buffer>,
17805        position: text::Anchor,
17806        cx: &mut App,
17807    ) -> Option<Task<Vec<project::Hover>>>;
17808
17809    fn inlay_hints(
17810        &self,
17811        buffer_handle: Entity<Buffer>,
17812        range: Range<text::Anchor>,
17813        cx: &mut App,
17814    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
17815
17816    fn resolve_inlay_hint(
17817        &self,
17818        hint: InlayHint,
17819        buffer_handle: Entity<Buffer>,
17820        server_id: LanguageServerId,
17821        cx: &mut App,
17822    ) -> Option<Task<anyhow::Result<InlayHint>>>;
17823
17824    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
17825
17826    fn document_highlights(
17827        &self,
17828        buffer: &Entity<Buffer>,
17829        position: text::Anchor,
17830        cx: &mut App,
17831    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
17832
17833    fn definitions(
17834        &self,
17835        buffer: &Entity<Buffer>,
17836        position: text::Anchor,
17837        kind: GotoDefinitionKind,
17838        cx: &mut App,
17839    ) -> Option<Task<Result<Vec<LocationLink>>>>;
17840
17841    fn range_for_rename(
17842        &self,
17843        buffer: &Entity<Buffer>,
17844        position: text::Anchor,
17845        cx: &mut App,
17846    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
17847
17848    fn perform_rename(
17849        &self,
17850        buffer: &Entity<Buffer>,
17851        position: text::Anchor,
17852        new_name: String,
17853        cx: &mut App,
17854    ) -> Option<Task<Result<ProjectTransaction>>>;
17855}
17856
17857pub trait CompletionProvider {
17858    fn completions(
17859        &self,
17860        buffer: &Entity<Buffer>,
17861        buffer_position: text::Anchor,
17862        trigger: CompletionContext,
17863        window: &mut Window,
17864        cx: &mut Context<Editor>,
17865    ) -> Task<Result<Option<Vec<Completion>>>>;
17866
17867    fn resolve_completions(
17868        &self,
17869        buffer: Entity<Buffer>,
17870        completion_indices: Vec<usize>,
17871        completions: Rc<RefCell<Box<[Completion]>>>,
17872        cx: &mut Context<Editor>,
17873    ) -> Task<Result<bool>>;
17874
17875    fn apply_additional_edits_for_completion(
17876        &self,
17877        _buffer: Entity<Buffer>,
17878        _completions: Rc<RefCell<Box<[Completion]>>>,
17879        _completion_index: usize,
17880        _push_to_history: bool,
17881        _cx: &mut Context<Editor>,
17882    ) -> Task<Result<Option<language::Transaction>>> {
17883        Task::ready(Ok(None))
17884    }
17885
17886    fn is_completion_trigger(
17887        &self,
17888        buffer: &Entity<Buffer>,
17889        position: language::Anchor,
17890        text: &str,
17891        trigger_in_words: bool,
17892        cx: &mut Context<Editor>,
17893    ) -> bool;
17894
17895    fn sort_completions(&self) -> bool {
17896        true
17897    }
17898}
17899
17900pub trait CodeActionProvider {
17901    fn id(&self) -> Arc<str>;
17902
17903    fn code_actions(
17904        &self,
17905        buffer: &Entity<Buffer>,
17906        range: Range<text::Anchor>,
17907        window: &mut Window,
17908        cx: &mut App,
17909    ) -> Task<Result<Vec<CodeAction>>>;
17910
17911    fn apply_code_action(
17912        &self,
17913        buffer_handle: Entity<Buffer>,
17914        action: CodeAction,
17915        excerpt_id: ExcerptId,
17916        push_to_history: bool,
17917        window: &mut Window,
17918        cx: &mut App,
17919    ) -> Task<Result<ProjectTransaction>>;
17920}
17921
17922impl CodeActionProvider for Entity<Project> {
17923    fn id(&self) -> Arc<str> {
17924        "project".into()
17925    }
17926
17927    fn code_actions(
17928        &self,
17929        buffer: &Entity<Buffer>,
17930        range: Range<text::Anchor>,
17931        _window: &mut Window,
17932        cx: &mut App,
17933    ) -> Task<Result<Vec<CodeAction>>> {
17934        self.update(cx, |project, cx| {
17935            let code_lens = project.code_lens(buffer, range.clone(), cx);
17936            let code_actions = project.code_actions(buffer, range, None, cx);
17937            cx.background_spawn(async move {
17938                let (code_lens, code_actions) = join(code_lens, code_actions).await;
17939                Ok(code_lens
17940                    .context("code lens fetch")?
17941                    .into_iter()
17942                    .chain(code_actions.context("code action fetch")?)
17943                    .collect())
17944            })
17945        })
17946    }
17947
17948    fn apply_code_action(
17949        &self,
17950        buffer_handle: Entity<Buffer>,
17951        action: CodeAction,
17952        _excerpt_id: ExcerptId,
17953        push_to_history: bool,
17954        _window: &mut Window,
17955        cx: &mut App,
17956    ) -> Task<Result<ProjectTransaction>> {
17957        self.update(cx, |project, cx| {
17958            project.apply_code_action(buffer_handle, action, push_to_history, cx)
17959        })
17960    }
17961}
17962
17963fn snippet_completions(
17964    project: &Project,
17965    buffer: &Entity<Buffer>,
17966    buffer_position: text::Anchor,
17967    cx: &mut App,
17968) -> Task<Result<Vec<Completion>>> {
17969    let language = buffer.read(cx).language_at(buffer_position);
17970    let language_name = language.as_ref().map(|language| language.lsp_id());
17971    let snippet_store = project.snippets().read(cx);
17972    let snippets = snippet_store.snippets_for(language_name, cx);
17973
17974    if snippets.is_empty() {
17975        return Task::ready(Ok(vec![]));
17976    }
17977    let snapshot = buffer.read(cx).text_snapshot();
17978    let chars: String = snapshot
17979        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
17980        .collect();
17981
17982    let scope = language.map(|language| language.default_scope());
17983    let executor = cx.background_executor().clone();
17984
17985    cx.background_spawn(async move {
17986        let classifier = CharClassifier::new(scope).for_completion(true);
17987        let mut last_word = chars
17988            .chars()
17989            .take_while(|c| classifier.is_word(*c))
17990            .collect::<String>();
17991        last_word = last_word.chars().rev().collect();
17992
17993        if last_word.is_empty() {
17994            return Ok(vec![]);
17995        }
17996
17997        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
17998        let to_lsp = |point: &text::Anchor| {
17999            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
18000            point_to_lsp(end)
18001        };
18002        let lsp_end = to_lsp(&buffer_position);
18003
18004        let candidates = snippets
18005            .iter()
18006            .enumerate()
18007            .flat_map(|(ix, snippet)| {
18008                snippet
18009                    .prefix
18010                    .iter()
18011                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
18012            })
18013            .collect::<Vec<StringMatchCandidate>>();
18014
18015        let mut matches = fuzzy::match_strings(
18016            &candidates,
18017            &last_word,
18018            last_word.chars().any(|c| c.is_uppercase()),
18019            100,
18020            &Default::default(),
18021            executor,
18022        )
18023        .await;
18024
18025        // Remove all candidates where the query's start does not match the start of any word in the candidate
18026        if let Some(query_start) = last_word.chars().next() {
18027            matches.retain(|string_match| {
18028                split_words(&string_match.string).any(|word| {
18029                    // Check that the first codepoint of the word as lowercase matches the first
18030                    // codepoint of the query as lowercase
18031                    word.chars()
18032                        .flat_map(|codepoint| codepoint.to_lowercase())
18033                        .zip(query_start.to_lowercase())
18034                        .all(|(word_cp, query_cp)| word_cp == query_cp)
18035                })
18036            });
18037        }
18038
18039        let matched_strings = matches
18040            .into_iter()
18041            .map(|m| m.string)
18042            .collect::<HashSet<_>>();
18043
18044        let result: Vec<Completion> = snippets
18045            .into_iter()
18046            .filter_map(|snippet| {
18047                let matching_prefix = snippet
18048                    .prefix
18049                    .iter()
18050                    .find(|prefix| matched_strings.contains(*prefix))?;
18051                let start = as_offset - last_word.len();
18052                let start = snapshot.anchor_before(start);
18053                let range = start..buffer_position;
18054                let lsp_start = to_lsp(&start);
18055                let lsp_range = lsp::Range {
18056                    start: lsp_start,
18057                    end: lsp_end,
18058                };
18059                Some(Completion {
18060                    old_range: range,
18061                    new_text: snippet.body.clone(),
18062                    source: CompletionSource::Lsp {
18063                        server_id: LanguageServerId(usize::MAX),
18064                        resolved: true,
18065                        lsp_completion: Box::new(lsp::CompletionItem {
18066                            label: snippet.prefix.first().unwrap().clone(),
18067                            kind: Some(CompletionItemKind::SNIPPET),
18068                            label_details: snippet.description.as_ref().map(|description| {
18069                                lsp::CompletionItemLabelDetails {
18070                                    detail: Some(description.clone()),
18071                                    description: None,
18072                                }
18073                            }),
18074                            insert_text_format: Some(InsertTextFormat::SNIPPET),
18075                            text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
18076                                lsp::InsertReplaceEdit {
18077                                    new_text: snippet.body.clone(),
18078                                    insert: lsp_range,
18079                                    replace: lsp_range,
18080                                },
18081                            )),
18082                            filter_text: Some(snippet.body.clone()),
18083                            sort_text: Some(char::MAX.to_string()),
18084                            ..lsp::CompletionItem::default()
18085                        }),
18086                        lsp_defaults: None,
18087                    },
18088                    label: CodeLabel {
18089                        text: matching_prefix.clone(),
18090                        runs: Vec::new(),
18091                        filter_range: 0..matching_prefix.len(),
18092                    },
18093                    documentation: snippet
18094                        .description
18095                        .clone()
18096                        .map(|description| CompletionDocumentation::SingleLine(description.into())),
18097                    confirm: None,
18098                })
18099            })
18100            .collect();
18101
18102        Ok(result)
18103    })
18104}
18105
18106impl CompletionProvider for Entity<Project> {
18107    fn completions(
18108        &self,
18109        buffer: &Entity<Buffer>,
18110        buffer_position: text::Anchor,
18111        options: CompletionContext,
18112        _window: &mut Window,
18113        cx: &mut Context<Editor>,
18114    ) -> Task<Result<Option<Vec<Completion>>>> {
18115        self.update(cx, |project, cx| {
18116            let snippets = snippet_completions(project, buffer, buffer_position, cx);
18117            let project_completions = project.completions(buffer, buffer_position, options, cx);
18118            cx.background_spawn(async move {
18119                let snippets_completions = snippets.await?;
18120                match project_completions.await? {
18121                    Some(mut completions) => {
18122                        completions.extend(snippets_completions);
18123                        Ok(Some(completions))
18124                    }
18125                    None => {
18126                        if snippets_completions.is_empty() {
18127                            Ok(None)
18128                        } else {
18129                            Ok(Some(snippets_completions))
18130                        }
18131                    }
18132                }
18133            })
18134        })
18135    }
18136
18137    fn resolve_completions(
18138        &self,
18139        buffer: Entity<Buffer>,
18140        completion_indices: Vec<usize>,
18141        completions: Rc<RefCell<Box<[Completion]>>>,
18142        cx: &mut Context<Editor>,
18143    ) -> Task<Result<bool>> {
18144        self.update(cx, |project, cx| {
18145            project.lsp_store().update(cx, |lsp_store, cx| {
18146                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
18147            })
18148        })
18149    }
18150
18151    fn apply_additional_edits_for_completion(
18152        &self,
18153        buffer: Entity<Buffer>,
18154        completions: Rc<RefCell<Box<[Completion]>>>,
18155        completion_index: usize,
18156        push_to_history: bool,
18157        cx: &mut Context<Editor>,
18158    ) -> Task<Result<Option<language::Transaction>>> {
18159        self.update(cx, |project, cx| {
18160            project.lsp_store().update(cx, |lsp_store, cx| {
18161                lsp_store.apply_additional_edits_for_completion(
18162                    buffer,
18163                    completions,
18164                    completion_index,
18165                    push_to_history,
18166                    cx,
18167                )
18168            })
18169        })
18170    }
18171
18172    fn is_completion_trigger(
18173        &self,
18174        buffer: &Entity<Buffer>,
18175        position: language::Anchor,
18176        text: &str,
18177        trigger_in_words: bool,
18178        cx: &mut Context<Editor>,
18179    ) -> bool {
18180        let mut chars = text.chars();
18181        let char = if let Some(char) = chars.next() {
18182            char
18183        } else {
18184            return false;
18185        };
18186        if chars.next().is_some() {
18187            return false;
18188        }
18189
18190        let buffer = buffer.read(cx);
18191        let snapshot = buffer.snapshot();
18192        if !snapshot.settings_at(position, cx).show_completions_on_input {
18193            return false;
18194        }
18195        let classifier = snapshot.char_classifier_at(position).for_completion(true);
18196        if trigger_in_words && classifier.is_word(char) {
18197            return true;
18198        }
18199
18200        buffer.completion_triggers().contains(text)
18201    }
18202}
18203
18204impl SemanticsProvider for Entity<Project> {
18205    fn hover(
18206        &self,
18207        buffer: &Entity<Buffer>,
18208        position: text::Anchor,
18209        cx: &mut App,
18210    ) -> Option<Task<Vec<project::Hover>>> {
18211        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
18212    }
18213
18214    fn document_highlights(
18215        &self,
18216        buffer: &Entity<Buffer>,
18217        position: text::Anchor,
18218        cx: &mut App,
18219    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
18220        Some(self.update(cx, |project, cx| {
18221            project.document_highlights(buffer, position, cx)
18222        }))
18223    }
18224
18225    fn definitions(
18226        &self,
18227        buffer: &Entity<Buffer>,
18228        position: text::Anchor,
18229        kind: GotoDefinitionKind,
18230        cx: &mut App,
18231    ) -> Option<Task<Result<Vec<LocationLink>>>> {
18232        Some(self.update(cx, |project, cx| match kind {
18233            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
18234            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
18235            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
18236            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
18237        }))
18238    }
18239
18240    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
18241        // TODO: make this work for remote projects
18242        self.update(cx, |this, cx| {
18243            buffer.update(cx, |buffer, cx| {
18244                this.any_language_server_supports_inlay_hints(buffer, cx)
18245            })
18246        })
18247    }
18248
18249    fn inlay_hints(
18250        &self,
18251        buffer_handle: Entity<Buffer>,
18252        range: Range<text::Anchor>,
18253        cx: &mut App,
18254    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
18255        Some(self.update(cx, |project, cx| {
18256            project.inlay_hints(buffer_handle, range, cx)
18257        }))
18258    }
18259
18260    fn resolve_inlay_hint(
18261        &self,
18262        hint: InlayHint,
18263        buffer_handle: Entity<Buffer>,
18264        server_id: LanguageServerId,
18265        cx: &mut App,
18266    ) -> Option<Task<anyhow::Result<InlayHint>>> {
18267        Some(self.update(cx, |project, cx| {
18268            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
18269        }))
18270    }
18271
18272    fn range_for_rename(
18273        &self,
18274        buffer: &Entity<Buffer>,
18275        position: text::Anchor,
18276        cx: &mut App,
18277    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
18278        Some(self.update(cx, |project, cx| {
18279            let buffer = buffer.clone();
18280            let task = project.prepare_rename(buffer.clone(), position, cx);
18281            cx.spawn(async move |_, cx| {
18282                Ok(match task.await? {
18283                    PrepareRenameResponse::Success(range) => Some(range),
18284                    PrepareRenameResponse::InvalidPosition => None,
18285                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
18286                        // Fallback on using TreeSitter info to determine identifier range
18287                        buffer.update(cx, |buffer, _| {
18288                            let snapshot = buffer.snapshot();
18289                            let (range, kind) = snapshot.surrounding_word(position);
18290                            if kind != Some(CharKind::Word) {
18291                                return None;
18292                            }
18293                            Some(
18294                                snapshot.anchor_before(range.start)
18295                                    ..snapshot.anchor_after(range.end),
18296                            )
18297                        })?
18298                    }
18299                })
18300            })
18301        }))
18302    }
18303
18304    fn perform_rename(
18305        &self,
18306        buffer: &Entity<Buffer>,
18307        position: text::Anchor,
18308        new_name: String,
18309        cx: &mut App,
18310    ) -> Option<Task<Result<ProjectTransaction>>> {
18311        Some(self.update(cx, |project, cx| {
18312            project.perform_rename(buffer.clone(), position, new_name, cx)
18313        }))
18314    }
18315}
18316
18317fn inlay_hint_settings(
18318    location: Anchor,
18319    snapshot: &MultiBufferSnapshot,
18320    cx: &mut Context<Editor>,
18321) -> InlayHintSettings {
18322    let file = snapshot.file_at(location);
18323    let language = snapshot.language_at(location).map(|l| l.name());
18324    language_settings(language, file, cx).inlay_hints
18325}
18326
18327fn consume_contiguous_rows(
18328    contiguous_row_selections: &mut Vec<Selection<Point>>,
18329    selection: &Selection<Point>,
18330    display_map: &DisplaySnapshot,
18331    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
18332) -> (MultiBufferRow, MultiBufferRow) {
18333    contiguous_row_selections.push(selection.clone());
18334    let start_row = MultiBufferRow(selection.start.row);
18335    let mut end_row = ending_row(selection, display_map);
18336
18337    while let Some(next_selection) = selections.peek() {
18338        if next_selection.start.row <= end_row.0 {
18339            end_row = ending_row(next_selection, display_map);
18340            contiguous_row_selections.push(selections.next().unwrap().clone());
18341        } else {
18342            break;
18343        }
18344    }
18345    (start_row, end_row)
18346}
18347
18348fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
18349    if next_selection.end.column > 0 || next_selection.is_empty() {
18350        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
18351    } else {
18352        MultiBufferRow(next_selection.end.row)
18353    }
18354}
18355
18356impl EditorSnapshot {
18357    pub fn remote_selections_in_range<'a>(
18358        &'a self,
18359        range: &'a Range<Anchor>,
18360        collaboration_hub: &dyn CollaborationHub,
18361        cx: &'a App,
18362    ) -> impl 'a + Iterator<Item = RemoteSelection> {
18363        let participant_names = collaboration_hub.user_names(cx);
18364        let participant_indices = collaboration_hub.user_participant_indices(cx);
18365        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
18366        let collaborators_by_replica_id = collaborators_by_peer_id
18367            .iter()
18368            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
18369            .collect::<HashMap<_, _>>();
18370        self.buffer_snapshot
18371            .selections_in_range(range, false)
18372            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
18373                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
18374                let participant_index = participant_indices.get(&collaborator.user_id).copied();
18375                let user_name = participant_names.get(&collaborator.user_id).cloned();
18376                Some(RemoteSelection {
18377                    replica_id,
18378                    selection,
18379                    cursor_shape,
18380                    line_mode,
18381                    participant_index,
18382                    peer_id: collaborator.peer_id,
18383                    user_name,
18384                })
18385            })
18386    }
18387
18388    pub fn hunks_for_ranges(
18389        &self,
18390        ranges: impl IntoIterator<Item = Range<Point>>,
18391    ) -> Vec<MultiBufferDiffHunk> {
18392        let mut hunks = Vec::new();
18393        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
18394            HashMap::default();
18395        for query_range in ranges {
18396            let query_rows =
18397                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
18398            for hunk in self.buffer_snapshot.diff_hunks_in_range(
18399                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
18400            ) {
18401                // Include deleted hunks that are adjacent to the query range, because
18402                // otherwise they would be missed.
18403                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
18404                if hunk.status().is_deleted() {
18405                    intersects_range |= hunk.row_range.start == query_rows.end;
18406                    intersects_range |= hunk.row_range.end == query_rows.start;
18407                }
18408                if intersects_range {
18409                    if !processed_buffer_rows
18410                        .entry(hunk.buffer_id)
18411                        .or_default()
18412                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
18413                    {
18414                        continue;
18415                    }
18416                    hunks.push(hunk);
18417                }
18418            }
18419        }
18420
18421        hunks
18422    }
18423
18424    fn display_diff_hunks_for_rows<'a>(
18425        &'a self,
18426        display_rows: Range<DisplayRow>,
18427        folded_buffers: &'a HashSet<BufferId>,
18428    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
18429        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
18430        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
18431
18432        self.buffer_snapshot
18433            .diff_hunks_in_range(buffer_start..buffer_end)
18434            .filter_map(|hunk| {
18435                if folded_buffers.contains(&hunk.buffer_id) {
18436                    return None;
18437                }
18438
18439                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
18440                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
18441
18442                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
18443                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
18444
18445                let display_hunk = if hunk_display_start.column() != 0 {
18446                    DisplayDiffHunk::Folded {
18447                        display_row: hunk_display_start.row(),
18448                    }
18449                } else {
18450                    let mut end_row = hunk_display_end.row();
18451                    if hunk_display_end.column() > 0 {
18452                        end_row.0 += 1;
18453                    }
18454                    let is_created_file = hunk.is_created_file();
18455                    DisplayDiffHunk::Unfolded {
18456                        status: hunk.status(),
18457                        diff_base_byte_range: hunk.diff_base_byte_range,
18458                        display_row_range: hunk_display_start.row()..end_row,
18459                        multi_buffer_range: Anchor::range_in_buffer(
18460                            hunk.excerpt_id,
18461                            hunk.buffer_id,
18462                            hunk.buffer_range,
18463                        ),
18464                        is_created_file,
18465                    }
18466                };
18467
18468                Some(display_hunk)
18469            })
18470    }
18471
18472    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
18473        self.display_snapshot.buffer_snapshot.language_at(position)
18474    }
18475
18476    pub fn is_focused(&self) -> bool {
18477        self.is_focused
18478    }
18479
18480    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
18481        self.placeholder_text.as_ref()
18482    }
18483
18484    pub fn scroll_position(&self) -> gpui::Point<f32> {
18485        self.scroll_anchor.scroll_position(&self.display_snapshot)
18486    }
18487
18488    fn gutter_dimensions(
18489        &self,
18490        font_id: FontId,
18491        font_size: Pixels,
18492        max_line_number_width: Pixels,
18493        cx: &App,
18494    ) -> Option<GutterDimensions> {
18495        if !self.show_gutter {
18496            return None;
18497        }
18498
18499        let descent = cx.text_system().descent(font_id, font_size);
18500        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
18501        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
18502
18503        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
18504            matches!(
18505                ProjectSettings::get_global(cx).git.git_gutter,
18506                Some(GitGutterSetting::TrackedFiles)
18507            )
18508        });
18509        let gutter_settings = EditorSettings::get_global(cx).gutter;
18510        let show_line_numbers = self
18511            .show_line_numbers
18512            .unwrap_or(gutter_settings.line_numbers);
18513        let line_gutter_width = if show_line_numbers {
18514            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
18515            let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
18516            max_line_number_width.max(min_width_for_number_on_gutter)
18517        } else {
18518            0.0.into()
18519        };
18520
18521        let show_code_actions = self
18522            .show_code_actions
18523            .unwrap_or(gutter_settings.code_actions);
18524
18525        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
18526        let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
18527
18528        let git_blame_entries_width =
18529            self.git_blame_gutter_max_author_length
18530                .map(|max_author_length| {
18531                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
18532
18533                    /// The number of characters to dedicate to gaps and margins.
18534                    const SPACING_WIDTH: usize = 4;
18535
18536                    let max_char_count = max_author_length
18537                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
18538                        + ::git::SHORT_SHA_LENGTH
18539                        + MAX_RELATIVE_TIMESTAMP.len()
18540                        + SPACING_WIDTH;
18541
18542                    em_advance * max_char_count
18543                });
18544
18545        let is_singleton = self.buffer_snapshot.is_singleton();
18546
18547        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
18548        left_padding += if !is_singleton {
18549            em_width * 4.0
18550        } else if show_code_actions || show_runnables || show_breakpoints {
18551            em_width * 3.0
18552        } else if show_git_gutter && show_line_numbers {
18553            em_width * 2.0
18554        } else if show_git_gutter || show_line_numbers {
18555            em_width
18556        } else {
18557            px(0.)
18558        };
18559
18560        let shows_folds = is_singleton && gutter_settings.folds;
18561
18562        let right_padding = if shows_folds && show_line_numbers {
18563            em_width * 4.0
18564        } else if shows_folds || (!is_singleton && show_line_numbers) {
18565            em_width * 3.0
18566        } else if show_line_numbers {
18567            em_width
18568        } else {
18569            px(0.)
18570        };
18571
18572        Some(GutterDimensions {
18573            left_padding,
18574            right_padding,
18575            width: line_gutter_width + left_padding + right_padding,
18576            margin: -descent,
18577            git_blame_entries_width,
18578        })
18579    }
18580
18581    pub fn render_crease_toggle(
18582        &self,
18583        buffer_row: MultiBufferRow,
18584        row_contains_cursor: bool,
18585        editor: Entity<Editor>,
18586        window: &mut Window,
18587        cx: &mut App,
18588    ) -> Option<AnyElement> {
18589        let folded = self.is_line_folded(buffer_row);
18590        let mut is_foldable = false;
18591
18592        if let Some(crease) = self
18593            .crease_snapshot
18594            .query_row(buffer_row, &self.buffer_snapshot)
18595        {
18596            is_foldable = true;
18597            match crease {
18598                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
18599                    if let Some(render_toggle) = render_toggle {
18600                        let toggle_callback =
18601                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
18602                                if folded {
18603                                    editor.update(cx, |editor, cx| {
18604                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
18605                                    });
18606                                } else {
18607                                    editor.update(cx, |editor, cx| {
18608                                        editor.unfold_at(
18609                                            &crate::UnfoldAt { buffer_row },
18610                                            window,
18611                                            cx,
18612                                        )
18613                                    });
18614                                }
18615                            });
18616                        return Some((render_toggle)(
18617                            buffer_row,
18618                            folded,
18619                            toggle_callback,
18620                            window,
18621                            cx,
18622                        ));
18623                    }
18624                }
18625            }
18626        }
18627
18628        is_foldable |= self.starts_indent(buffer_row);
18629
18630        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
18631            Some(
18632                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
18633                    .toggle_state(folded)
18634                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
18635                        if folded {
18636                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
18637                        } else {
18638                            this.fold_at(&FoldAt { buffer_row }, window, cx);
18639                        }
18640                    }))
18641                    .into_any_element(),
18642            )
18643        } else {
18644            None
18645        }
18646    }
18647
18648    pub fn render_crease_trailer(
18649        &self,
18650        buffer_row: MultiBufferRow,
18651        window: &mut Window,
18652        cx: &mut App,
18653    ) -> Option<AnyElement> {
18654        let folded = self.is_line_folded(buffer_row);
18655        if let Crease::Inline { render_trailer, .. } = self
18656            .crease_snapshot
18657            .query_row(buffer_row, &self.buffer_snapshot)?
18658        {
18659            let render_trailer = render_trailer.as_ref()?;
18660            Some(render_trailer(buffer_row, folded, window, cx))
18661        } else {
18662            None
18663        }
18664    }
18665}
18666
18667impl Deref for EditorSnapshot {
18668    type Target = DisplaySnapshot;
18669
18670    fn deref(&self) -> &Self::Target {
18671        &self.display_snapshot
18672    }
18673}
18674
18675#[derive(Clone, Debug, PartialEq, Eq)]
18676pub enum EditorEvent {
18677    InputIgnored {
18678        text: Arc<str>,
18679    },
18680    InputHandled {
18681        utf16_range_to_replace: Option<Range<isize>>,
18682        text: Arc<str>,
18683    },
18684    ExcerptsAdded {
18685        buffer: Entity<Buffer>,
18686        predecessor: ExcerptId,
18687        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
18688    },
18689    ExcerptsRemoved {
18690        ids: Vec<ExcerptId>,
18691    },
18692    BufferFoldToggled {
18693        ids: Vec<ExcerptId>,
18694        folded: bool,
18695    },
18696    ExcerptsEdited {
18697        ids: Vec<ExcerptId>,
18698    },
18699    ExcerptsExpanded {
18700        ids: Vec<ExcerptId>,
18701    },
18702    BufferEdited,
18703    Edited {
18704        transaction_id: clock::Lamport,
18705    },
18706    Reparsed(BufferId),
18707    Focused,
18708    FocusedIn,
18709    Blurred,
18710    DirtyChanged,
18711    Saved,
18712    TitleChanged,
18713    DiffBaseChanged,
18714    SelectionsChanged {
18715        local: bool,
18716    },
18717    ScrollPositionChanged {
18718        local: bool,
18719        autoscroll: bool,
18720    },
18721    Closed,
18722    TransactionUndone {
18723        transaction_id: clock::Lamport,
18724    },
18725    TransactionBegun {
18726        transaction_id: clock::Lamport,
18727    },
18728    Reloaded,
18729    CursorShapeChanged,
18730    PushedToNavHistory {
18731        anchor: Anchor,
18732        is_deactivate: bool,
18733    },
18734}
18735
18736impl EventEmitter<EditorEvent> for Editor {}
18737
18738impl Focusable for Editor {
18739    fn focus_handle(&self, _cx: &App) -> FocusHandle {
18740        self.focus_handle.clone()
18741    }
18742}
18743
18744impl Render for Editor {
18745    fn render(&mut self, _: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
18746        let settings = ThemeSettings::get_global(cx);
18747
18748        let mut text_style = match self.mode {
18749            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
18750                color: cx.theme().colors().editor_foreground,
18751                font_family: settings.ui_font.family.clone(),
18752                font_features: settings.ui_font.features.clone(),
18753                font_fallbacks: settings.ui_font.fallbacks.clone(),
18754                font_size: rems(0.875).into(),
18755                font_weight: settings.ui_font.weight,
18756                line_height: relative(settings.buffer_line_height.value()),
18757                ..Default::default()
18758            },
18759            EditorMode::Full => TextStyle {
18760                color: cx.theme().colors().editor_foreground,
18761                font_family: settings.buffer_font.family.clone(),
18762                font_features: settings.buffer_font.features.clone(),
18763                font_fallbacks: settings.buffer_font.fallbacks.clone(),
18764                font_size: settings.buffer_font_size(cx).into(),
18765                font_weight: settings.buffer_font.weight,
18766                line_height: relative(settings.buffer_line_height.value()),
18767                ..Default::default()
18768            },
18769        };
18770        if let Some(text_style_refinement) = &self.text_style_refinement {
18771            text_style.refine(text_style_refinement)
18772        }
18773
18774        let background = match self.mode {
18775            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
18776            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
18777            EditorMode::Full => cx.theme().colors().editor_background,
18778        };
18779
18780        EditorElement::new(
18781            &cx.entity(),
18782            EditorStyle {
18783                background,
18784                local_player: cx.theme().players().local(),
18785                text: text_style,
18786                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
18787                syntax: cx.theme().syntax().clone(),
18788                status: cx.theme().status().clone(),
18789                inlay_hints_style: make_inlay_hints_style(cx),
18790                inline_completion_styles: make_suggestion_styles(cx),
18791                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
18792            },
18793        )
18794    }
18795}
18796
18797impl EntityInputHandler for Editor {
18798    fn text_for_range(
18799        &mut self,
18800        range_utf16: Range<usize>,
18801        adjusted_range: &mut Option<Range<usize>>,
18802        _: &mut Window,
18803        cx: &mut Context<Self>,
18804    ) -> Option<String> {
18805        let snapshot = self.buffer.read(cx).read(cx);
18806        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
18807        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
18808        if (start.0..end.0) != range_utf16 {
18809            adjusted_range.replace(start.0..end.0);
18810        }
18811        Some(snapshot.text_for_range(start..end).collect())
18812    }
18813
18814    fn selected_text_range(
18815        &mut self,
18816        ignore_disabled_input: bool,
18817        _: &mut Window,
18818        cx: &mut Context<Self>,
18819    ) -> Option<UTF16Selection> {
18820        // Prevent the IME menu from appearing when holding down an alphabetic key
18821        // while input is disabled.
18822        if !ignore_disabled_input && !self.input_enabled {
18823            return None;
18824        }
18825
18826        let selection = self.selections.newest::<OffsetUtf16>(cx);
18827        let range = selection.range();
18828
18829        Some(UTF16Selection {
18830            range: range.start.0..range.end.0,
18831            reversed: selection.reversed,
18832        })
18833    }
18834
18835    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
18836        let snapshot = self.buffer.read(cx).read(cx);
18837        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
18838        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
18839    }
18840
18841    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
18842        self.clear_highlights::<InputComposition>(cx);
18843        self.ime_transaction.take();
18844    }
18845
18846    fn replace_text_in_range(
18847        &mut self,
18848        range_utf16: Option<Range<usize>>,
18849        text: &str,
18850        window: &mut Window,
18851        cx: &mut Context<Self>,
18852    ) {
18853        if !self.input_enabled {
18854            cx.emit(EditorEvent::InputIgnored { text: text.into() });
18855            return;
18856        }
18857
18858        self.transact(window, cx, |this, window, cx| {
18859            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
18860                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
18861                Some(this.selection_replacement_ranges(range_utf16, cx))
18862            } else {
18863                this.marked_text_ranges(cx)
18864            };
18865
18866            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
18867                let newest_selection_id = this.selections.newest_anchor().id;
18868                this.selections
18869                    .all::<OffsetUtf16>(cx)
18870                    .iter()
18871                    .zip(ranges_to_replace.iter())
18872                    .find_map(|(selection, range)| {
18873                        if selection.id == newest_selection_id {
18874                            Some(
18875                                (range.start.0 as isize - selection.head().0 as isize)
18876                                    ..(range.end.0 as isize - selection.head().0 as isize),
18877                            )
18878                        } else {
18879                            None
18880                        }
18881                    })
18882            });
18883
18884            cx.emit(EditorEvent::InputHandled {
18885                utf16_range_to_replace: range_to_replace,
18886                text: text.into(),
18887            });
18888
18889            if let Some(new_selected_ranges) = new_selected_ranges {
18890                this.change_selections(None, window, cx, |selections| {
18891                    selections.select_ranges(new_selected_ranges)
18892                });
18893                this.backspace(&Default::default(), window, cx);
18894            }
18895
18896            this.handle_input(text, window, cx);
18897        });
18898
18899        if let Some(transaction) = self.ime_transaction {
18900            self.buffer.update(cx, |buffer, cx| {
18901                buffer.group_until_transaction(transaction, cx);
18902            });
18903        }
18904
18905        self.unmark_text(window, cx);
18906    }
18907
18908    fn replace_and_mark_text_in_range(
18909        &mut self,
18910        range_utf16: Option<Range<usize>>,
18911        text: &str,
18912        new_selected_range_utf16: Option<Range<usize>>,
18913        window: &mut Window,
18914        cx: &mut Context<Self>,
18915    ) {
18916        if !self.input_enabled {
18917            return;
18918        }
18919
18920        let transaction = self.transact(window, cx, |this, window, cx| {
18921            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
18922                let snapshot = this.buffer.read(cx).read(cx);
18923                if let Some(relative_range_utf16) = range_utf16.as_ref() {
18924                    for marked_range in &mut marked_ranges {
18925                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
18926                        marked_range.start.0 += relative_range_utf16.start;
18927                        marked_range.start =
18928                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
18929                        marked_range.end =
18930                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
18931                    }
18932                }
18933                Some(marked_ranges)
18934            } else if let Some(range_utf16) = range_utf16 {
18935                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
18936                Some(this.selection_replacement_ranges(range_utf16, cx))
18937            } else {
18938                None
18939            };
18940
18941            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
18942                let newest_selection_id = this.selections.newest_anchor().id;
18943                this.selections
18944                    .all::<OffsetUtf16>(cx)
18945                    .iter()
18946                    .zip(ranges_to_replace.iter())
18947                    .find_map(|(selection, range)| {
18948                        if selection.id == newest_selection_id {
18949                            Some(
18950                                (range.start.0 as isize - selection.head().0 as isize)
18951                                    ..(range.end.0 as isize - selection.head().0 as isize),
18952                            )
18953                        } else {
18954                            None
18955                        }
18956                    })
18957            });
18958
18959            cx.emit(EditorEvent::InputHandled {
18960                utf16_range_to_replace: range_to_replace,
18961                text: text.into(),
18962            });
18963
18964            if let Some(ranges) = ranges_to_replace {
18965                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
18966            }
18967
18968            let marked_ranges = {
18969                let snapshot = this.buffer.read(cx).read(cx);
18970                this.selections
18971                    .disjoint_anchors()
18972                    .iter()
18973                    .map(|selection| {
18974                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
18975                    })
18976                    .collect::<Vec<_>>()
18977            };
18978
18979            if text.is_empty() {
18980                this.unmark_text(window, cx);
18981            } else {
18982                this.highlight_text::<InputComposition>(
18983                    marked_ranges.clone(),
18984                    HighlightStyle {
18985                        underline: Some(UnderlineStyle {
18986                            thickness: px(1.),
18987                            color: None,
18988                            wavy: false,
18989                        }),
18990                        ..Default::default()
18991                    },
18992                    cx,
18993                );
18994            }
18995
18996            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
18997            let use_autoclose = this.use_autoclose;
18998            let use_auto_surround = this.use_auto_surround;
18999            this.set_use_autoclose(false);
19000            this.set_use_auto_surround(false);
19001            this.handle_input(text, window, cx);
19002            this.set_use_autoclose(use_autoclose);
19003            this.set_use_auto_surround(use_auto_surround);
19004
19005            if let Some(new_selected_range) = new_selected_range_utf16 {
19006                let snapshot = this.buffer.read(cx).read(cx);
19007                let new_selected_ranges = marked_ranges
19008                    .into_iter()
19009                    .map(|marked_range| {
19010                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
19011                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
19012                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
19013                        snapshot.clip_offset_utf16(new_start, Bias::Left)
19014                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
19015                    })
19016                    .collect::<Vec<_>>();
19017
19018                drop(snapshot);
19019                this.change_selections(None, window, cx, |selections| {
19020                    selections.select_ranges(new_selected_ranges)
19021                });
19022            }
19023        });
19024
19025        self.ime_transaction = self.ime_transaction.or(transaction);
19026        if let Some(transaction) = self.ime_transaction {
19027            self.buffer.update(cx, |buffer, cx| {
19028                buffer.group_until_transaction(transaction, cx);
19029            });
19030        }
19031
19032        if self.text_highlights::<InputComposition>(cx).is_none() {
19033            self.ime_transaction.take();
19034        }
19035    }
19036
19037    fn bounds_for_range(
19038        &mut self,
19039        range_utf16: Range<usize>,
19040        element_bounds: gpui::Bounds<Pixels>,
19041        window: &mut Window,
19042        cx: &mut Context<Self>,
19043    ) -> Option<gpui::Bounds<Pixels>> {
19044        let text_layout_details = self.text_layout_details(window);
19045        let gpui::Size {
19046            width: em_width,
19047            height: line_height,
19048        } = self.character_size(window);
19049
19050        let snapshot = self.snapshot(window, cx);
19051        let scroll_position = snapshot.scroll_position();
19052        let scroll_left = scroll_position.x * em_width;
19053
19054        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
19055        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
19056            + self.gutter_dimensions.width
19057            + self.gutter_dimensions.margin;
19058        let y = line_height * (start.row().as_f32() - scroll_position.y);
19059
19060        Some(Bounds {
19061            origin: element_bounds.origin + point(x, y),
19062            size: size(em_width, line_height),
19063        })
19064    }
19065
19066    fn character_index_for_point(
19067        &mut self,
19068        point: gpui::Point<Pixels>,
19069        _window: &mut Window,
19070        _cx: &mut Context<Self>,
19071    ) -> Option<usize> {
19072        let position_map = self.last_position_map.as_ref()?;
19073        if !position_map.text_hitbox.contains(&point) {
19074            return None;
19075        }
19076        let display_point = position_map.point_for_position(point).previous_valid;
19077        let anchor = position_map
19078            .snapshot
19079            .display_point_to_anchor(display_point, Bias::Left);
19080        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
19081        Some(utf16_offset.0)
19082    }
19083}
19084
19085trait SelectionExt {
19086    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
19087    fn spanned_rows(
19088        &self,
19089        include_end_if_at_line_start: bool,
19090        map: &DisplaySnapshot,
19091    ) -> Range<MultiBufferRow>;
19092}
19093
19094impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
19095    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
19096        let start = self
19097            .start
19098            .to_point(&map.buffer_snapshot)
19099            .to_display_point(map);
19100        let end = self
19101            .end
19102            .to_point(&map.buffer_snapshot)
19103            .to_display_point(map);
19104        if self.reversed {
19105            end..start
19106        } else {
19107            start..end
19108        }
19109    }
19110
19111    fn spanned_rows(
19112        &self,
19113        include_end_if_at_line_start: bool,
19114        map: &DisplaySnapshot,
19115    ) -> Range<MultiBufferRow> {
19116        let start = self.start.to_point(&map.buffer_snapshot);
19117        let mut end = self.end.to_point(&map.buffer_snapshot);
19118        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
19119            end.row -= 1;
19120        }
19121
19122        let buffer_start = map.prev_line_boundary(start).0;
19123        let buffer_end = map.next_line_boundary(end).0;
19124        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
19125    }
19126}
19127
19128impl<T: InvalidationRegion> InvalidationStack<T> {
19129    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
19130    where
19131        S: Clone + ToOffset,
19132    {
19133        while let Some(region) = self.last() {
19134            let all_selections_inside_invalidation_ranges =
19135                if selections.len() == region.ranges().len() {
19136                    selections
19137                        .iter()
19138                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
19139                        .all(|(selection, invalidation_range)| {
19140                            let head = selection.head().to_offset(buffer);
19141                            invalidation_range.start <= head && invalidation_range.end >= head
19142                        })
19143                } else {
19144                    false
19145                };
19146
19147            if all_selections_inside_invalidation_ranges {
19148                break;
19149            } else {
19150                self.pop();
19151            }
19152        }
19153    }
19154}
19155
19156impl<T> Default for InvalidationStack<T> {
19157    fn default() -> Self {
19158        Self(Default::default())
19159    }
19160}
19161
19162impl<T> Deref for InvalidationStack<T> {
19163    type Target = Vec<T>;
19164
19165    fn deref(&self) -> &Self::Target {
19166        &self.0
19167    }
19168}
19169
19170impl<T> DerefMut for InvalidationStack<T> {
19171    fn deref_mut(&mut self) -> &mut Self::Target {
19172        &mut self.0
19173    }
19174}
19175
19176impl InvalidationRegion for SnippetState {
19177    fn ranges(&self) -> &[Range<Anchor>] {
19178        &self.ranges[self.active_index]
19179    }
19180}
19181
19182pub fn diagnostic_block_renderer(
19183    diagnostic: Diagnostic,
19184    max_message_rows: Option<u8>,
19185    allow_closing: bool,
19186) -> RenderBlock {
19187    let (text_without_backticks, code_ranges) =
19188        highlight_diagnostic_message(&diagnostic, max_message_rows);
19189
19190    Arc::new(move |cx: &mut BlockContext| {
19191        let group_id: SharedString = cx.block_id.to_string().into();
19192
19193        let mut text_style = cx.window.text_style().clone();
19194        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
19195        let theme_settings = ThemeSettings::get_global(cx);
19196        text_style.font_family = theme_settings.buffer_font.family.clone();
19197        text_style.font_style = theme_settings.buffer_font.style;
19198        text_style.font_features = theme_settings.buffer_font.features.clone();
19199        text_style.font_weight = theme_settings.buffer_font.weight;
19200
19201        let multi_line_diagnostic = diagnostic.message.contains('\n');
19202
19203        let buttons = |diagnostic: &Diagnostic| {
19204            if multi_line_diagnostic {
19205                v_flex()
19206            } else {
19207                h_flex()
19208            }
19209            .when(allow_closing, |div| {
19210                div.children(diagnostic.is_primary.then(|| {
19211                    IconButton::new("close-block", IconName::XCircle)
19212                        .icon_color(Color::Muted)
19213                        .size(ButtonSize::Compact)
19214                        .style(ButtonStyle::Transparent)
19215                        .visible_on_hover(group_id.clone())
19216                        .on_click(move |_click, window, cx| {
19217                            window.dispatch_action(Box::new(Cancel), cx)
19218                        })
19219                        .tooltip(|window, cx| {
19220                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
19221                        })
19222                }))
19223            })
19224            .child(
19225                IconButton::new("copy-block", IconName::Copy)
19226                    .icon_color(Color::Muted)
19227                    .size(ButtonSize::Compact)
19228                    .style(ButtonStyle::Transparent)
19229                    .visible_on_hover(group_id.clone())
19230                    .on_click({
19231                        let message = diagnostic.message.clone();
19232                        move |_click, _, cx| {
19233                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
19234                        }
19235                    })
19236                    .tooltip(Tooltip::text("Copy diagnostic message")),
19237            )
19238        };
19239
19240        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
19241            AvailableSpace::min_size(),
19242            cx.window,
19243            cx.app,
19244        );
19245
19246        h_flex()
19247            .id(cx.block_id)
19248            .group(group_id.clone())
19249            .relative()
19250            .size_full()
19251            .block_mouse_down()
19252            .pl(cx.gutter_dimensions.width)
19253            .w(cx.max_width - cx.gutter_dimensions.full_width())
19254            .child(
19255                div()
19256                    .flex()
19257                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
19258                    .flex_shrink(),
19259            )
19260            .child(buttons(&diagnostic))
19261            .child(div().flex().flex_shrink_0().child(
19262                StyledText::new(text_without_backticks.clone()).with_default_highlights(
19263                    &text_style,
19264                    code_ranges.iter().map(|range| {
19265                        (
19266                            range.clone(),
19267                            HighlightStyle {
19268                                font_weight: Some(FontWeight::BOLD),
19269                                ..Default::default()
19270                            },
19271                        )
19272                    }),
19273                ),
19274            ))
19275            .into_any_element()
19276    })
19277}
19278
19279fn inline_completion_edit_text(
19280    current_snapshot: &BufferSnapshot,
19281    edits: &[(Range<Anchor>, String)],
19282    edit_preview: &EditPreview,
19283    include_deletions: bool,
19284    cx: &App,
19285) -> HighlightedText {
19286    let edits = edits
19287        .iter()
19288        .map(|(anchor, text)| {
19289            (
19290                anchor.start.text_anchor..anchor.end.text_anchor,
19291                text.clone(),
19292            )
19293        })
19294        .collect::<Vec<_>>();
19295
19296    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
19297}
19298
19299pub fn highlight_diagnostic_message(
19300    diagnostic: &Diagnostic,
19301    mut max_message_rows: Option<u8>,
19302) -> (SharedString, Vec<Range<usize>>) {
19303    let mut text_without_backticks = String::new();
19304    let mut code_ranges = Vec::new();
19305
19306    if let Some(source) = &diagnostic.source {
19307        text_without_backticks.push_str(source);
19308        code_ranges.push(0..source.len());
19309        text_without_backticks.push_str(": ");
19310    }
19311
19312    let mut prev_offset = 0;
19313    let mut in_code_block = false;
19314    let has_row_limit = max_message_rows.is_some();
19315    let mut newline_indices = diagnostic
19316        .message
19317        .match_indices('\n')
19318        .filter(|_| has_row_limit)
19319        .map(|(ix, _)| ix)
19320        .fuse()
19321        .peekable();
19322
19323    for (quote_ix, _) in diagnostic
19324        .message
19325        .match_indices('`')
19326        .chain([(diagnostic.message.len(), "")])
19327    {
19328        let mut first_newline_ix = None;
19329        let mut last_newline_ix = None;
19330        while let Some(newline_ix) = newline_indices.peek() {
19331            if *newline_ix < quote_ix {
19332                if first_newline_ix.is_none() {
19333                    first_newline_ix = Some(*newline_ix);
19334                }
19335                last_newline_ix = Some(*newline_ix);
19336
19337                if let Some(rows_left) = &mut max_message_rows {
19338                    if *rows_left == 0 {
19339                        break;
19340                    } else {
19341                        *rows_left -= 1;
19342                    }
19343                }
19344                let _ = newline_indices.next();
19345            } else {
19346                break;
19347            }
19348        }
19349        let prev_len = text_without_backticks.len();
19350        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
19351        text_without_backticks.push_str(new_text);
19352        if in_code_block {
19353            code_ranges.push(prev_len..text_without_backticks.len());
19354        }
19355        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
19356        in_code_block = !in_code_block;
19357        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
19358            text_without_backticks.push_str("...");
19359            break;
19360        }
19361    }
19362
19363    (text_without_backticks.into(), code_ranges)
19364}
19365
19366fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
19367    match severity {
19368        DiagnosticSeverity::ERROR => colors.error,
19369        DiagnosticSeverity::WARNING => colors.warning,
19370        DiagnosticSeverity::INFORMATION => colors.info,
19371        DiagnosticSeverity::HINT => colors.info,
19372        _ => colors.ignored,
19373    }
19374}
19375
19376pub fn styled_runs_for_code_label<'a>(
19377    label: &'a CodeLabel,
19378    syntax_theme: &'a theme::SyntaxTheme,
19379) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
19380    let fade_out = HighlightStyle {
19381        fade_out: Some(0.35),
19382        ..Default::default()
19383    };
19384
19385    let mut prev_end = label.filter_range.end;
19386    label
19387        .runs
19388        .iter()
19389        .enumerate()
19390        .flat_map(move |(ix, (range, highlight_id))| {
19391            let style = if let Some(style) = highlight_id.style(syntax_theme) {
19392                style
19393            } else {
19394                return Default::default();
19395            };
19396            let mut muted_style = style;
19397            muted_style.highlight(fade_out);
19398
19399            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
19400            if range.start >= label.filter_range.end {
19401                if range.start > prev_end {
19402                    runs.push((prev_end..range.start, fade_out));
19403                }
19404                runs.push((range.clone(), muted_style));
19405            } else if range.end <= label.filter_range.end {
19406                runs.push((range.clone(), style));
19407            } else {
19408                runs.push((range.start..label.filter_range.end, style));
19409                runs.push((label.filter_range.end..range.end, muted_style));
19410            }
19411            prev_end = cmp::max(prev_end, range.end);
19412
19413            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
19414                runs.push((prev_end..label.text.len(), fade_out));
19415            }
19416
19417            runs
19418        })
19419}
19420
19421pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
19422    let mut prev_index = 0;
19423    let mut prev_codepoint: Option<char> = None;
19424    text.char_indices()
19425        .chain([(text.len(), '\0')])
19426        .filter_map(move |(index, codepoint)| {
19427            let prev_codepoint = prev_codepoint.replace(codepoint)?;
19428            let is_boundary = index == text.len()
19429                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
19430                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
19431            if is_boundary {
19432                let chunk = &text[prev_index..index];
19433                prev_index = index;
19434                Some(chunk)
19435            } else {
19436                None
19437            }
19438        })
19439}
19440
19441pub trait RangeToAnchorExt: Sized {
19442    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
19443
19444    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
19445        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
19446        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
19447    }
19448}
19449
19450impl<T: ToOffset> RangeToAnchorExt for Range<T> {
19451    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
19452        let start_offset = self.start.to_offset(snapshot);
19453        let end_offset = self.end.to_offset(snapshot);
19454        if start_offset == end_offset {
19455            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
19456        } else {
19457            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
19458        }
19459    }
19460}
19461
19462pub trait RowExt {
19463    fn as_f32(&self) -> f32;
19464
19465    fn next_row(&self) -> Self;
19466
19467    fn previous_row(&self) -> Self;
19468
19469    fn minus(&self, other: Self) -> u32;
19470}
19471
19472impl RowExt for DisplayRow {
19473    fn as_f32(&self) -> f32 {
19474        self.0 as f32
19475    }
19476
19477    fn next_row(&self) -> Self {
19478        Self(self.0 + 1)
19479    }
19480
19481    fn previous_row(&self) -> Self {
19482        Self(self.0.saturating_sub(1))
19483    }
19484
19485    fn minus(&self, other: Self) -> u32 {
19486        self.0 - other.0
19487    }
19488}
19489
19490impl RowExt for MultiBufferRow {
19491    fn as_f32(&self) -> f32 {
19492        self.0 as f32
19493    }
19494
19495    fn next_row(&self) -> Self {
19496        Self(self.0 + 1)
19497    }
19498
19499    fn previous_row(&self) -> Self {
19500        Self(self.0.saturating_sub(1))
19501    }
19502
19503    fn minus(&self, other: Self) -> u32 {
19504        self.0 - other.0
19505    }
19506}
19507
19508trait RowRangeExt {
19509    type Row;
19510
19511    fn len(&self) -> usize;
19512
19513    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
19514}
19515
19516impl RowRangeExt for Range<MultiBufferRow> {
19517    type Row = MultiBufferRow;
19518
19519    fn len(&self) -> usize {
19520        (self.end.0 - self.start.0) as usize
19521    }
19522
19523    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
19524        (self.start.0..self.end.0).map(MultiBufferRow)
19525    }
19526}
19527
19528impl RowRangeExt for Range<DisplayRow> {
19529    type Row = DisplayRow;
19530
19531    fn len(&self) -> usize {
19532        (self.end.0 - self.start.0) as usize
19533    }
19534
19535    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
19536        (self.start.0..self.end.0).map(DisplayRow)
19537    }
19538}
19539
19540/// If select range has more than one line, we
19541/// just point the cursor to range.start.
19542fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
19543    if range.start.row == range.end.row {
19544        range
19545    } else {
19546        range.start..range.start
19547    }
19548}
19549pub struct KillRing(ClipboardItem);
19550impl Global for KillRing {}
19551
19552const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
19553
19554struct BreakpointPromptEditor {
19555    pub(crate) prompt: Entity<Editor>,
19556    editor: WeakEntity<Editor>,
19557    breakpoint_anchor: Anchor,
19558    kind: BreakpointKind,
19559    block_ids: HashSet<CustomBlockId>,
19560    gutter_dimensions: Arc<Mutex<GutterDimensions>>,
19561    _subscriptions: Vec<Subscription>,
19562}
19563
19564impl BreakpointPromptEditor {
19565    const MAX_LINES: u8 = 4;
19566
19567    fn new(
19568        editor: WeakEntity<Editor>,
19569        breakpoint_anchor: Anchor,
19570        kind: BreakpointKind,
19571        window: &mut Window,
19572        cx: &mut Context<Self>,
19573    ) -> Self {
19574        let buffer = cx.new(|cx| {
19575            Buffer::local(
19576                kind.log_message()
19577                    .map(|msg| msg.to_string())
19578                    .unwrap_or_default(),
19579                cx,
19580            )
19581        });
19582        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
19583
19584        let prompt = cx.new(|cx| {
19585            let mut prompt = Editor::new(
19586                EditorMode::AutoHeight {
19587                    max_lines: Self::MAX_LINES as usize,
19588                },
19589                buffer,
19590                None,
19591                window,
19592                cx,
19593            );
19594            prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
19595            prompt.set_show_cursor_when_unfocused(false, cx);
19596            prompt.set_placeholder_text(
19597                "Message to log when breakpoint is hit. Expressions within {} are interpolated.",
19598                cx,
19599            );
19600
19601            prompt
19602        });
19603
19604        Self {
19605            prompt,
19606            editor,
19607            breakpoint_anchor,
19608            kind,
19609            gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
19610            block_ids: Default::default(),
19611            _subscriptions: vec![],
19612        }
19613    }
19614
19615    pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
19616        self.block_ids.extend(block_ids)
19617    }
19618
19619    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
19620        if let Some(editor) = self.editor.upgrade() {
19621            let log_message = self
19622                .prompt
19623                .read(cx)
19624                .buffer
19625                .read(cx)
19626                .as_singleton()
19627                .expect("A multi buffer in breakpoint prompt isn't possible")
19628                .read(cx)
19629                .as_rope()
19630                .to_string();
19631
19632            editor.update(cx, |editor, cx| {
19633                editor.edit_breakpoint_at_anchor(
19634                    self.breakpoint_anchor,
19635                    self.kind.clone(),
19636                    BreakpointEditAction::EditLogMessage(log_message.into()),
19637                    cx,
19638                );
19639
19640                editor.remove_blocks(self.block_ids.clone(), None, cx);
19641                cx.focus_self(window);
19642            });
19643        }
19644    }
19645
19646    fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
19647        self.editor
19648            .update(cx, |editor, cx| {
19649                editor.remove_blocks(self.block_ids.clone(), None, cx);
19650                window.focus(&editor.focus_handle);
19651            })
19652            .log_err();
19653    }
19654
19655    fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
19656        let settings = ThemeSettings::get_global(cx);
19657        let text_style = TextStyle {
19658            color: if self.prompt.read(cx).read_only(cx) {
19659                cx.theme().colors().text_disabled
19660            } else {
19661                cx.theme().colors().text
19662            },
19663            font_family: settings.buffer_font.family.clone(),
19664            font_fallbacks: settings.buffer_font.fallbacks.clone(),
19665            font_size: settings.buffer_font_size(cx).into(),
19666            font_weight: settings.buffer_font.weight,
19667            line_height: relative(settings.buffer_line_height.value()),
19668            ..Default::default()
19669        };
19670        EditorElement::new(
19671            &self.prompt,
19672            EditorStyle {
19673                background: cx.theme().colors().editor_background,
19674                local_player: cx.theme().players().local(),
19675                text: text_style,
19676                ..Default::default()
19677            },
19678        )
19679    }
19680}
19681
19682impl Render for BreakpointPromptEditor {
19683    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19684        let gutter_dimensions = *self.gutter_dimensions.lock();
19685        h_flex()
19686            .key_context("Editor")
19687            .bg(cx.theme().colors().editor_background)
19688            .border_y_1()
19689            .border_color(cx.theme().status().info_border)
19690            .size_full()
19691            .py(window.line_height() / 2.5)
19692            .on_action(cx.listener(Self::confirm))
19693            .on_action(cx.listener(Self::cancel))
19694            .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
19695            .child(div().flex_1().child(self.render_prompt_editor(cx)))
19696    }
19697}
19698
19699impl Focusable for BreakpointPromptEditor {
19700    fn focus_handle(&self, cx: &App) -> FocusHandle {
19701        self.prompt.focus_handle(cx)
19702    }
19703}
19704
19705fn all_edits_insertions_or_deletions(
19706    edits: &Vec<(Range<Anchor>, String)>,
19707    snapshot: &MultiBufferSnapshot,
19708) -> bool {
19709    let mut all_insertions = true;
19710    let mut all_deletions = true;
19711
19712    for (range, new_text) in edits.iter() {
19713        let range_is_empty = range.to_offset(&snapshot).is_empty();
19714        let text_is_empty = new_text.is_empty();
19715
19716        if range_is_empty != text_is_empty {
19717            if range_is_empty {
19718                all_deletions = false;
19719            } else {
19720                all_insertions = false;
19721            }
19722        } else {
19723            return false;
19724        }
19725
19726        if !all_insertions && !all_deletions {
19727            return false;
19728        }
19729    }
19730    all_insertions || all_deletions
19731}
19732
19733struct MissingEditPredictionKeybindingTooltip;
19734
19735impl Render for MissingEditPredictionKeybindingTooltip {
19736    fn render(&mut self, window: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
19737        ui::tooltip_container(window, cx, |container, _, cx| {
19738            container
19739                .flex_shrink_0()
19740                .max_w_80()
19741                .min_h(rems_from_px(124.))
19742                .justify_between()
19743                .child(
19744                    v_flex()
19745                        .flex_1()
19746                        .text_ui_sm(cx)
19747                        .child(Label::new("Conflict with Accept Keybinding"))
19748                        .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
19749                )
19750                .child(
19751                    h_flex()
19752                        .pb_1()
19753                        .gap_1()
19754                        .items_end()
19755                        .w_full()
19756                        .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
19757                            window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
19758                        }))
19759                        .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
19760                            cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
19761                        })),
19762                )
19763        })
19764    }
19765}
19766
19767#[derive(Debug, Clone, Copy, PartialEq)]
19768pub struct LineHighlight {
19769    pub background: Background,
19770    pub border: Option<gpui::Hsla>,
19771}
19772
19773impl From<Hsla> for LineHighlight {
19774    fn from(hsla: Hsla) -> Self {
19775        Self {
19776            background: hsla.into(),
19777            border: None,
19778        }
19779    }
19780}
19781
19782impl From<Background> for LineHighlight {
19783    fn from(background: Background) -> Self {
19784        Self {
19785            background,
19786            border: None,
19787        }
19788    }
19789}