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 futures::{
   72    future::{self, join, Shared},
   73    FutureExt,
   74};
   75use fuzzy::StringMatchCandidate;
   76
   77use ::git::Restore;
   78use code_context_menus::{
   79    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   80    CompletionsMenu, ContextMenuOrigin,
   81};
   82use git::blame::GitBlame;
   83use gpui::{
   84    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
   85    AnimationExt, AnyElement, App, AppContext, AsyncWindowContext, AvailableSpace, Background,
   86    Bounds, ClipboardEntry, ClipboardItem, Context, DispatchPhase, Edges, Entity,
   87    EntityInputHandler, EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight,
   88    Global, HighlightStyle, Hsla, KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad,
   89    ParentElement, Pixels, Render, SharedString, Size, Stateful, Styled, StyledText, Subscription,
   90    Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
   91    WeakEntity, WeakFocusHandle, Window,
   92};
   93use highlight_matching_bracket::refresh_matching_bracket_highlights;
   94use hover_popover::{hide_hover, HoverState};
   95use indent_guides::ActiveIndentGuidesState;
   96use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   97pub use inline_completion::Direction;
   98use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
   99pub use items::MAX_TAB_TITLE_LEN;
  100use itertools::Itertools;
  101use language::{
  102    language_settings::{
  103        self, all_language_settings, language_settings, InlayHintSettings, RewrapBehavior,
  104        WordsCompletionMode,
  105    },
  106    point_from_lsp, text_diff_with_options, AutoindentMode, BracketMatch, BracketPair, Buffer,
  107    Capability, CharKind, CodeLabel, CursorShape, Diagnostic, DiffOptions, EditPredictionsMode,
  108    EditPreview, HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point,
  109    Selection, SelectionGoal, TextObject, TransactionId, TreeSitterOptions, WordsQuery,
  110};
  111use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  112use linked_editing_ranges::refresh_linked_ranges;
  113use mouse_context_menu::MouseContextMenu;
  114use persistence::DB;
  115pub use proposed_changes_editor::{
  116    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  117};
  118use smallvec::smallvec;
  119use std::iter::Peekable;
  120use task::{ResolvedTask, TaskTemplate, TaskVariables};
  121
  122use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  123pub use lsp::CompletionContext;
  124use lsp::{
  125    CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
  126    InsertTextFormat, LanguageServerId, LanguageServerName,
  127};
  128
  129use language::BufferSnapshot;
  130use movement::TextLayoutDetails;
  131pub use multi_buffer::{
  132    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  133    ToOffset, ToPoint,
  134};
  135use multi_buffer::{
  136    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  137    MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
  138};
  139use project::{
  140    lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  141    project_settings::{GitGutterSetting, ProjectSettings},
  142    CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
  143    Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
  144    TaskSourceKind,
  145};
  146use rand::prelude::*;
  147use rpc::{proto::*, ErrorExt};
  148use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  149use selections_collection::{
  150    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  151};
  152use serde::{Deserialize, Serialize};
  153use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  154use smallvec::SmallVec;
  155use snippet::Snippet;
  156use std::{
  157    any::TypeId,
  158    borrow::Cow,
  159    cell::RefCell,
  160    cmp::{self, Ordering, Reverse},
  161    mem,
  162    num::NonZeroU32,
  163    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  164    path::{Path, PathBuf},
  165    rc::Rc,
  166    sync::Arc,
  167    time::{Duration, Instant},
  168};
  169pub use sum_tree::Bias;
  170use sum_tree::TreeMap;
  171use text::{BufferId, OffsetUtf16, Rope};
  172use theme::{
  173    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  174    ThemeColors, ThemeSettings,
  175};
  176use ui::{
  177    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
  178    Tooltip,
  179};
  180use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  181use workspace::{
  182    item::{ItemHandle, PreviewTabsSettings},
  183    ItemId, RestoreOnStartupBehavior,
  184};
  185use workspace::{
  186    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  187    WorkspaceSettings,
  188};
  189use workspace::{
  190    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  191};
  192use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  193
  194use crate::hover_links::{find_url, find_url_from_range};
  195use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  196
  197pub const FILE_HEADER_HEIGHT: u32 = 2;
  198pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  199pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  200const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  201const MAX_LINE_LEN: usize = 1024;
  202const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  203const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  204pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  205#[doc(hidden)]
  206pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  207
  208pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
  209pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
  210pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  211
  212pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  213pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  214
  215const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  216    alt: true,
  217    shift: true,
  218    control: false,
  219    platform: false,
  220    function: false,
  221};
  222
  223#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  224pub enum InlayId {
  225    InlineCompletion(usize),
  226    Hint(usize),
  227}
  228
  229impl InlayId {
  230    fn id(&self) -> usize {
  231        match self {
  232            Self::InlineCompletion(id) => *id,
  233            Self::Hint(id) => *id,
  234        }
  235    }
  236}
  237
  238enum DocumentHighlightRead {}
  239enum DocumentHighlightWrite {}
  240enum InputComposition {}
  241enum SelectedTextHighlight {}
  242
  243#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  244pub enum Navigated {
  245    Yes,
  246    No,
  247}
  248
  249impl Navigated {
  250    pub fn from_bool(yes: bool) -> Navigated {
  251        if yes {
  252            Navigated::Yes
  253        } else {
  254            Navigated::No
  255        }
  256    }
  257}
  258
  259#[derive(Debug, Clone, PartialEq, Eq)]
  260enum DisplayDiffHunk {
  261    Folded {
  262        display_row: DisplayRow,
  263    },
  264    Unfolded {
  265        is_created_file: bool,
  266        diff_base_byte_range: Range<usize>,
  267        display_row_range: Range<DisplayRow>,
  268        multi_buffer_range: Range<Anchor>,
  269        status: DiffHunkStatus,
  270    },
  271}
  272
  273pub fn init_settings(cx: &mut App) {
  274    EditorSettings::register(cx);
  275}
  276
  277pub fn init(cx: &mut App) {
  278    init_settings(cx);
  279
  280    workspace::register_project_item::<Editor>(cx);
  281    workspace::FollowableViewRegistry::register::<Editor>(cx);
  282    workspace::register_serializable_item::<Editor>(cx);
  283
  284    cx.observe_new(
  285        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  286            workspace.register_action(Editor::new_file);
  287            workspace.register_action(Editor::new_file_vertical);
  288            workspace.register_action(Editor::new_file_horizontal);
  289            workspace.register_action(Editor::cancel_language_server_work);
  290        },
  291    )
  292    .detach();
  293
  294    cx.on_action(move |_: &workspace::NewFile, cx| {
  295        let app_state = workspace::AppState::global(cx);
  296        if let Some(app_state) = app_state.upgrade() {
  297            workspace::open_new(
  298                Default::default(),
  299                app_state,
  300                cx,
  301                |workspace, window, cx| {
  302                    Editor::new_file(workspace, &Default::default(), window, cx)
  303                },
  304            )
  305            .detach();
  306        }
  307    });
  308    cx.on_action(move |_: &workspace::NewWindow, cx| {
  309        let app_state = workspace::AppState::global(cx);
  310        if let Some(app_state) = app_state.upgrade() {
  311            workspace::open_new(
  312                Default::default(),
  313                app_state,
  314                cx,
  315                |workspace, window, cx| {
  316                    cx.activate(true);
  317                    Editor::new_file(workspace, &Default::default(), window, cx)
  318                },
  319            )
  320            .detach();
  321        }
  322    });
  323}
  324
  325pub struct SearchWithinRange;
  326
  327trait InvalidationRegion {
  328    fn ranges(&self) -> &[Range<Anchor>];
  329}
  330
  331#[derive(Clone, Debug, PartialEq)]
  332pub enum SelectPhase {
  333    Begin {
  334        position: DisplayPoint,
  335        add: bool,
  336        click_count: usize,
  337    },
  338    BeginColumnar {
  339        position: DisplayPoint,
  340        reset: bool,
  341        goal_column: u32,
  342    },
  343    Extend {
  344        position: DisplayPoint,
  345        click_count: usize,
  346    },
  347    Update {
  348        position: DisplayPoint,
  349        goal_column: u32,
  350        scroll_delta: gpui::Point<f32>,
  351    },
  352    End,
  353}
  354
  355#[derive(Clone, Debug)]
  356pub enum SelectMode {
  357    Character,
  358    Word(Range<Anchor>),
  359    Line(Range<Anchor>),
  360    All,
  361}
  362
  363#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  364pub enum EditorMode {
  365    SingleLine { auto_width: bool },
  366    AutoHeight { max_lines: usize },
  367    Full,
  368}
  369
  370#[derive(Copy, Clone, Debug)]
  371pub enum SoftWrap {
  372    /// Prefer not to wrap at all.
  373    ///
  374    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  375    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  376    GitDiff,
  377    /// Prefer a single line generally, unless an overly long line is encountered.
  378    None,
  379    /// Soft wrap lines that exceed the editor width.
  380    EditorWidth,
  381    /// Soft wrap lines at the preferred line length.
  382    Column(u32),
  383    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  384    Bounded(u32),
  385}
  386
  387#[derive(Clone)]
  388pub struct EditorStyle {
  389    pub background: Hsla,
  390    pub local_player: PlayerColor,
  391    pub text: TextStyle,
  392    pub scrollbar_width: Pixels,
  393    pub syntax: Arc<SyntaxTheme>,
  394    pub status: StatusColors,
  395    pub inlay_hints_style: HighlightStyle,
  396    pub inline_completion_styles: InlineCompletionStyles,
  397    pub unnecessary_code_fade: f32,
  398}
  399
  400impl Default for EditorStyle {
  401    fn default() -> Self {
  402        Self {
  403            background: Hsla::default(),
  404            local_player: PlayerColor::default(),
  405            text: TextStyle::default(),
  406            scrollbar_width: Pixels::default(),
  407            syntax: Default::default(),
  408            // HACK: Status colors don't have a real default.
  409            // We should look into removing the status colors from the editor
  410            // style and retrieve them directly from the theme.
  411            status: StatusColors::dark(),
  412            inlay_hints_style: HighlightStyle::default(),
  413            inline_completion_styles: InlineCompletionStyles {
  414                insertion: HighlightStyle::default(),
  415                whitespace: HighlightStyle::default(),
  416            },
  417            unnecessary_code_fade: Default::default(),
  418        }
  419    }
  420}
  421
  422pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  423    let show_background = language_settings::language_settings(None, None, cx)
  424        .inlay_hints
  425        .show_background;
  426
  427    HighlightStyle {
  428        color: Some(cx.theme().status().hint),
  429        background_color: show_background.then(|| cx.theme().status().hint_background),
  430        ..HighlightStyle::default()
  431    }
  432}
  433
  434pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  435    InlineCompletionStyles {
  436        insertion: HighlightStyle {
  437            color: Some(cx.theme().status().predictive),
  438            ..HighlightStyle::default()
  439        },
  440        whitespace: HighlightStyle {
  441            background_color: Some(cx.theme().status().created_background),
  442            ..HighlightStyle::default()
  443        },
  444    }
  445}
  446
  447type CompletionId = usize;
  448
  449pub(crate) enum EditDisplayMode {
  450    TabAccept,
  451    DiffPopover,
  452    Inline,
  453}
  454
  455enum InlineCompletion {
  456    Edit {
  457        edits: Vec<(Range<Anchor>, String)>,
  458        edit_preview: Option<EditPreview>,
  459        display_mode: EditDisplayMode,
  460        snapshot: BufferSnapshot,
  461    },
  462    Move {
  463        target: Anchor,
  464        snapshot: BufferSnapshot,
  465    },
  466}
  467
  468struct InlineCompletionState {
  469    inlay_ids: Vec<InlayId>,
  470    completion: InlineCompletion,
  471    completion_id: Option<SharedString>,
  472    invalidation_range: Range<Anchor>,
  473}
  474
  475enum EditPredictionSettings {
  476    Disabled,
  477    Enabled {
  478        show_in_menu: bool,
  479        preview_requires_modifier: bool,
  480    },
  481}
  482
  483enum InlineCompletionHighlight {}
  484
  485#[derive(Debug, Clone)]
  486struct InlineDiagnostic {
  487    message: SharedString,
  488    group_id: usize,
  489    is_primary: bool,
  490    start: Point,
  491    severity: DiagnosticSeverity,
  492}
  493
  494pub enum MenuInlineCompletionsPolicy {
  495    Never,
  496    ByProvider,
  497}
  498
  499pub enum EditPredictionPreview {
  500    /// Modifier is not pressed
  501    Inactive { released_too_fast: bool },
  502    /// Modifier pressed
  503    Active {
  504        since: Instant,
  505        previous_scroll_position: Option<ScrollAnchor>,
  506    },
  507}
  508
  509impl EditPredictionPreview {
  510    pub fn released_too_fast(&self) -> bool {
  511        match self {
  512            EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
  513            EditPredictionPreview::Active { .. } => false,
  514        }
  515    }
  516
  517    pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
  518        if let EditPredictionPreview::Active {
  519            previous_scroll_position,
  520            ..
  521        } = self
  522        {
  523            *previous_scroll_position = scroll_position;
  524        }
  525    }
  526}
  527
  528#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  529struct EditorActionId(usize);
  530
  531impl EditorActionId {
  532    pub fn post_inc(&mut self) -> Self {
  533        let answer = self.0;
  534
  535        *self = Self(answer + 1);
  536
  537        Self(answer)
  538    }
  539}
  540
  541// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  542// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  543
  544type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  545type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  546
  547#[derive(Default)]
  548struct ScrollbarMarkerState {
  549    scrollbar_size: Size<Pixels>,
  550    dirty: bool,
  551    markers: Arc<[PaintQuad]>,
  552    pending_refresh: Option<Task<Result<()>>>,
  553}
  554
  555impl ScrollbarMarkerState {
  556    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  557        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  558    }
  559}
  560
  561#[derive(Clone, Debug)]
  562struct RunnableTasks {
  563    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  564    offset: multi_buffer::Anchor,
  565    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  566    column: u32,
  567    // Values of all named captures, including those starting with '_'
  568    extra_variables: HashMap<String, String>,
  569    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  570    context_range: Range<BufferOffset>,
  571}
  572
  573impl RunnableTasks {
  574    fn resolve<'a>(
  575        &'a self,
  576        cx: &'a task::TaskContext,
  577    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  578        self.templates.iter().filter_map(|(kind, template)| {
  579            template
  580                .resolve_task(&kind.to_id_base(), cx)
  581                .map(|task| (kind.clone(), task))
  582        })
  583    }
  584}
  585
  586#[derive(Clone)]
  587struct ResolvedTasks {
  588    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  589    position: Anchor,
  590}
  591#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  592struct BufferOffset(usize);
  593
  594// Addons allow storing per-editor state in other crates (e.g. Vim)
  595pub trait Addon: 'static {
  596    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  597
  598    fn render_buffer_header_controls(
  599        &self,
  600        _: &ExcerptInfo,
  601        _: &Window,
  602        _: &App,
  603    ) -> Option<AnyElement> {
  604        None
  605    }
  606
  607    fn to_any(&self) -> &dyn std::any::Any;
  608}
  609
  610/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  611///
  612/// See the [module level documentation](self) for more information.
  613pub struct Editor {
  614    focus_handle: FocusHandle,
  615    last_focused_descendant: Option<WeakFocusHandle>,
  616    /// The text buffer being edited
  617    buffer: Entity<MultiBuffer>,
  618    /// Map of how text in the buffer should be displayed.
  619    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  620    pub display_map: Entity<DisplayMap>,
  621    pub selections: SelectionsCollection,
  622    pub scroll_manager: ScrollManager,
  623    /// When inline assist editors are linked, they all render cursors because
  624    /// typing enters text into each of them, even the ones that aren't focused.
  625    pub(crate) show_cursor_when_unfocused: bool,
  626    columnar_selection_tail: Option<Anchor>,
  627    add_selections_state: Option<AddSelectionsState>,
  628    select_next_state: Option<SelectNextState>,
  629    select_prev_state: Option<SelectNextState>,
  630    selection_history: SelectionHistory,
  631    autoclose_regions: Vec<AutocloseRegion>,
  632    snippet_stack: InvalidationStack<SnippetState>,
  633    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  634    ime_transaction: Option<TransactionId>,
  635    active_diagnostics: Option<ActiveDiagnosticGroup>,
  636    show_inline_diagnostics: bool,
  637    inline_diagnostics_update: Task<()>,
  638    inline_diagnostics_enabled: bool,
  639    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  640    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  641    hard_wrap: Option<usize>,
  642
  643    // TODO: make this a access method
  644    pub project: Option<Entity<Project>>,
  645    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  646    completion_provider: Option<Box<dyn CompletionProvider>>,
  647    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  648    blink_manager: Entity<BlinkManager>,
  649    show_cursor_names: bool,
  650    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  651    pub show_local_selections: bool,
  652    mode: EditorMode,
  653    show_breadcrumbs: bool,
  654    show_gutter: bool,
  655    show_scrollbars: bool,
  656    show_line_numbers: Option<bool>,
  657    use_relative_line_numbers: Option<bool>,
  658    show_git_diff_gutter: Option<bool>,
  659    show_code_actions: Option<bool>,
  660    show_runnables: Option<bool>,
  661    show_wrap_guides: Option<bool>,
  662    show_indent_guides: Option<bool>,
  663    placeholder_text: Option<Arc<str>>,
  664    highlight_order: usize,
  665    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  666    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  667    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  668    scrollbar_marker_state: ScrollbarMarkerState,
  669    active_indent_guides_state: ActiveIndentGuidesState,
  670    nav_history: Option<ItemNavHistory>,
  671    context_menu: RefCell<Option<CodeContextMenu>>,
  672    mouse_context_menu: Option<MouseContextMenu>,
  673    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  674    signature_help_state: SignatureHelpState,
  675    auto_signature_help: Option<bool>,
  676    find_all_references_task_sources: Vec<Anchor>,
  677    next_completion_id: CompletionId,
  678    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  679    code_actions_task: Option<Task<Result<()>>>,
  680    selection_highlight_task: Option<Task<()>>,
  681    document_highlights_task: Option<Task<()>>,
  682    linked_editing_range_task: Option<Task<Option<()>>>,
  683    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  684    pending_rename: Option<RenameState>,
  685    searchable: bool,
  686    cursor_shape: CursorShape,
  687    current_line_highlight: Option<CurrentLineHighlight>,
  688    collapse_matches: bool,
  689    autoindent_mode: Option<AutoindentMode>,
  690    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  691    input_enabled: bool,
  692    use_modal_editing: bool,
  693    read_only: bool,
  694    leader_peer_id: Option<PeerId>,
  695    remote_id: Option<ViewId>,
  696    hover_state: HoverState,
  697    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  698    gutter_hovered: bool,
  699    hovered_link_state: Option<HoveredLinkState>,
  700    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  701    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  702    active_inline_completion: Option<InlineCompletionState>,
  703    /// Used to prevent flickering as the user types while the menu is open
  704    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  705    edit_prediction_settings: EditPredictionSettings,
  706    inline_completions_hidden_for_vim_mode: bool,
  707    show_inline_completions_override: Option<bool>,
  708    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  709    edit_prediction_preview: EditPredictionPreview,
  710    edit_prediction_indent_conflict: bool,
  711    edit_prediction_requires_modifier_in_indent_conflict: bool,
  712    inlay_hint_cache: InlayHintCache,
  713    next_inlay_id: usize,
  714    _subscriptions: Vec<Subscription>,
  715    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  716    gutter_dimensions: GutterDimensions,
  717    style: Option<EditorStyle>,
  718    text_style_refinement: Option<TextStyleRefinement>,
  719    next_editor_action_id: EditorActionId,
  720    editor_actions:
  721        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  722    use_autoclose: bool,
  723    use_auto_surround: bool,
  724    auto_replace_emoji_shortcode: bool,
  725    jsx_tag_auto_close_enabled_in_any_buffer: bool,
  726    show_git_blame_gutter: bool,
  727    show_git_blame_inline: bool,
  728    show_git_blame_inline_delay_task: Option<Task<()>>,
  729    git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
  730    git_blame_inline_enabled: bool,
  731    serialize_dirty_buffers: bool,
  732    show_selection_menu: Option<bool>,
  733    blame: Option<Entity<GitBlame>>,
  734    blame_subscription: Option<Subscription>,
  735    custom_context_menu: Option<
  736        Box<
  737            dyn 'static
  738                + Fn(
  739                    &mut Self,
  740                    DisplayPoint,
  741                    &mut Window,
  742                    &mut Context<Self>,
  743                ) -> Option<Entity<ui::ContextMenu>>,
  744        >,
  745    >,
  746    last_bounds: Option<Bounds<Pixels>>,
  747    last_position_map: Option<Rc<PositionMap>>,
  748    expect_bounds_change: Option<Bounds<Pixels>>,
  749    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  750    tasks_update_task: Option<Task<()>>,
  751    in_project_search: bool,
  752    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  753    breadcrumb_header: Option<String>,
  754    focused_block: Option<FocusedBlock>,
  755    next_scroll_position: NextScrollCursorCenterTopBottom,
  756    addons: HashMap<TypeId, Box<dyn Addon>>,
  757    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  758    load_diff_task: Option<Shared<Task<()>>>,
  759    selection_mark_mode: bool,
  760    toggle_fold_multiple_buffers: Task<()>,
  761    _scroll_cursor_center_top_bottom_task: Task<()>,
  762    serialize_selections: Task<()>,
  763}
  764
  765#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  766enum NextScrollCursorCenterTopBottom {
  767    #[default]
  768    Center,
  769    Top,
  770    Bottom,
  771}
  772
  773impl NextScrollCursorCenterTopBottom {
  774    fn next(&self) -> Self {
  775        match self {
  776            Self::Center => Self::Top,
  777            Self::Top => Self::Bottom,
  778            Self::Bottom => Self::Center,
  779        }
  780    }
  781}
  782
  783#[derive(Clone)]
  784pub struct EditorSnapshot {
  785    pub mode: EditorMode,
  786    show_gutter: bool,
  787    show_line_numbers: Option<bool>,
  788    show_git_diff_gutter: Option<bool>,
  789    show_code_actions: Option<bool>,
  790    show_runnables: Option<bool>,
  791    git_blame_gutter_max_author_length: Option<usize>,
  792    pub display_snapshot: DisplaySnapshot,
  793    pub placeholder_text: Option<Arc<str>>,
  794    is_focused: bool,
  795    scroll_anchor: ScrollAnchor,
  796    ongoing_scroll: OngoingScroll,
  797    current_line_highlight: CurrentLineHighlight,
  798    gutter_hovered: bool,
  799}
  800
  801const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  802
  803#[derive(Default, Debug, Clone, Copy)]
  804pub struct GutterDimensions {
  805    pub left_padding: Pixels,
  806    pub right_padding: Pixels,
  807    pub width: Pixels,
  808    pub margin: Pixels,
  809    pub git_blame_entries_width: Option<Pixels>,
  810}
  811
  812impl GutterDimensions {
  813    /// The full width of the space taken up by the gutter.
  814    pub fn full_width(&self) -> Pixels {
  815        self.margin + self.width
  816    }
  817
  818    /// The width of the space reserved for the fold indicators,
  819    /// use alongside 'justify_end' and `gutter_width` to
  820    /// right align content with the line numbers
  821    pub fn fold_area_width(&self) -> Pixels {
  822        self.margin + self.right_padding
  823    }
  824}
  825
  826#[derive(Debug)]
  827pub struct RemoteSelection {
  828    pub replica_id: ReplicaId,
  829    pub selection: Selection<Anchor>,
  830    pub cursor_shape: CursorShape,
  831    pub peer_id: PeerId,
  832    pub line_mode: bool,
  833    pub participant_index: Option<ParticipantIndex>,
  834    pub user_name: Option<SharedString>,
  835}
  836
  837#[derive(Clone, Debug)]
  838struct SelectionHistoryEntry {
  839    selections: Arc<[Selection<Anchor>]>,
  840    select_next_state: Option<SelectNextState>,
  841    select_prev_state: Option<SelectNextState>,
  842    add_selections_state: Option<AddSelectionsState>,
  843}
  844
  845enum SelectionHistoryMode {
  846    Normal,
  847    Undoing,
  848    Redoing,
  849}
  850
  851#[derive(Clone, PartialEq, Eq, Hash)]
  852struct HoveredCursor {
  853    replica_id: u16,
  854    selection_id: usize,
  855}
  856
  857impl Default for SelectionHistoryMode {
  858    fn default() -> Self {
  859        Self::Normal
  860    }
  861}
  862
  863#[derive(Default)]
  864struct SelectionHistory {
  865    #[allow(clippy::type_complexity)]
  866    selections_by_transaction:
  867        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  868    mode: SelectionHistoryMode,
  869    undo_stack: VecDeque<SelectionHistoryEntry>,
  870    redo_stack: VecDeque<SelectionHistoryEntry>,
  871}
  872
  873impl SelectionHistory {
  874    fn insert_transaction(
  875        &mut self,
  876        transaction_id: TransactionId,
  877        selections: Arc<[Selection<Anchor>]>,
  878    ) {
  879        self.selections_by_transaction
  880            .insert(transaction_id, (selections, None));
  881    }
  882
  883    #[allow(clippy::type_complexity)]
  884    fn transaction(
  885        &self,
  886        transaction_id: TransactionId,
  887    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  888        self.selections_by_transaction.get(&transaction_id)
  889    }
  890
  891    #[allow(clippy::type_complexity)]
  892    fn transaction_mut(
  893        &mut self,
  894        transaction_id: TransactionId,
  895    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  896        self.selections_by_transaction.get_mut(&transaction_id)
  897    }
  898
  899    fn push(&mut self, entry: SelectionHistoryEntry) {
  900        if !entry.selections.is_empty() {
  901            match self.mode {
  902                SelectionHistoryMode::Normal => {
  903                    self.push_undo(entry);
  904                    self.redo_stack.clear();
  905                }
  906                SelectionHistoryMode::Undoing => self.push_redo(entry),
  907                SelectionHistoryMode::Redoing => self.push_undo(entry),
  908            }
  909        }
  910    }
  911
  912    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  913        if self
  914            .undo_stack
  915            .back()
  916            .map_or(true, |e| e.selections != entry.selections)
  917        {
  918            self.undo_stack.push_back(entry);
  919            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  920                self.undo_stack.pop_front();
  921            }
  922        }
  923    }
  924
  925    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  926        if self
  927            .redo_stack
  928            .back()
  929            .map_or(true, |e| e.selections != entry.selections)
  930        {
  931            self.redo_stack.push_back(entry);
  932            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  933                self.redo_stack.pop_front();
  934            }
  935        }
  936    }
  937}
  938
  939struct RowHighlight {
  940    index: usize,
  941    range: Range<Anchor>,
  942    color: Hsla,
  943    should_autoscroll: bool,
  944}
  945
  946#[derive(Clone, Debug)]
  947struct AddSelectionsState {
  948    above: bool,
  949    stack: Vec<usize>,
  950}
  951
  952#[derive(Clone)]
  953struct SelectNextState {
  954    query: AhoCorasick,
  955    wordwise: bool,
  956    done: bool,
  957}
  958
  959impl std::fmt::Debug for SelectNextState {
  960    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  961        f.debug_struct(std::any::type_name::<Self>())
  962            .field("wordwise", &self.wordwise)
  963            .field("done", &self.done)
  964            .finish()
  965    }
  966}
  967
  968#[derive(Debug)]
  969struct AutocloseRegion {
  970    selection_id: usize,
  971    range: Range<Anchor>,
  972    pair: BracketPair,
  973}
  974
  975#[derive(Debug)]
  976struct SnippetState {
  977    ranges: Vec<Vec<Range<Anchor>>>,
  978    active_index: usize,
  979    choices: Vec<Option<Vec<String>>>,
  980}
  981
  982#[doc(hidden)]
  983pub struct RenameState {
  984    pub range: Range<Anchor>,
  985    pub old_name: Arc<str>,
  986    pub editor: Entity<Editor>,
  987    block_id: CustomBlockId,
  988}
  989
  990struct InvalidationStack<T>(Vec<T>);
  991
  992struct RegisteredInlineCompletionProvider {
  993    provider: Arc<dyn InlineCompletionProviderHandle>,
  994    _subscription: Subscription,
  995}
  996
  997#[derive(Debug, PartialEq, Eq)]
  998struct ActiveDiagnosticGroup {
  999    primary_range: Range<Anchor>,
 1000    primary_message: String,
 1001    group_id: usize,
 1002    blocks: HashMap<CustomBlockId, Diagnostic>,
 1003    is_valid: bool,
 1004}
 1005
 1006#[derive(Serialize, Deserialize, Clone, Debug)]
 1007pub struct ClipboardSelection {
 1008    /// The number of bytes in this selection.
 1009    pub len: usize,
 1010    /// Whether this was a full-line selection.
 1011    pub is_entire_line: bool,
 1012    /// The indentation of the first line when this content was originally copied.
 1013    pub first_line_indent: u32,
 1014}
 1015
 1016#[derive(Debug)]
 1017pub(crate) struct NavigationData {
 1018    cursor_anchor: Anchor,
 1019    cursor_position: Point,
 1020    scroll_anchor: ScrollAnchor,
 1021    scroll_top_row: u32,
 1022}
 1023
 1024#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1025pub enum GotoDefinitionKind {
 1026    Symbol,
 1027    Declaration,
 1028    Type,
 1029    Implementation,
 1030}
 1031
 1032#[derive(Debug, Clone)]
 1033enum InlayHintRefreshReason {
 1034    ModifiersChanged(bool),
 1035    Toggle(bool),
 1036    SettingsChange(InlayHintSettings),
 1037    NewLinesShown,
 1038    BufferEdited(HashSet<Arc<Language>>),
 1039    RefreshRequested,
 1040    ExcerptsRemoved(Vec<ExcerptId>),
 1041}
 1042
 1043impl InlayHintRefreshReason {
 1044    fn description(&self) -> &'static str {
 1045        match self {
 1046            Self::ModifiersChanged(_) => "modifiers changed",
 1047            Self::Toggle(_) => "toggle",
 1048            Self::SettingsChange(_) => "settings change",
 1049            Self::NewLinesShown => "new lines shown",
 1050            Self::BufferEdited(_) => "buffer edited",
 1051            Self::RefreshRequested => "refresh requested",
 1052            Self::ExcerptsRemoved(_) => "excerpts removed",
 1053        }
 1054    }
 1055}
 1056
 1057pub enum FormatTarget {
 1058    Buffers,
 1059    Ranges(Vec<Range<MultiBufferPoint>>),
 1060}
 1061
 1062pub(crate) struct FocusedBlock {
 1063    id: BlockId,
 1064    focus_handle: WeakFocusHandle,
 1065}
 1066
 1067#[derive(Clone)]
 1068enum JumpData {
 1069    MultiBufferRow {
 1070        row: MultiBufferRow,
 1071        line_offset_from_top: u32,
 1072    },
 1073    MultiBufferPoint {
 1074        excerpt_id: ExcerptId,
 1075        position: Point,
 1076        anchor: text::Anchor,
 1077        line_offset_from_top: u32,
 1078    },
 1079}
 1080
 1081pub enum MultibufferSelectionMode {
 1082    First,
 1083    All,
 1084}
 1085
 1086impl Editor {
 1087    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1088        let buffer = cx.new(|cx| Buffer::local("", cx));
 1089        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1090        Self::new(
 1091            EditorMode::SingleLine { auto_width: false },
 1092            buffer,
 1093            None,
 1094            window,
 1095            cx,
 1096        )
 1097    }
 1098
 1099    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1100        let buffer = cx.new(|cx| Buffer::local("", cx));
 1101        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1102        Self::new(EditorMode::Full, buffer, None, window, cx)
 1103    }
 1104
 1105    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1106        let buffer = cx.new(|cx| Buffer::local("", cx));
 1107        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1108        Self::new(
 1109            EditorMode::SingleLine { auto_width: true },
 1110            buffer,
 1111            None,
 1112            window,
 1113            cx,
 1114        )
 1115    }
 1116
 1117    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1118        let buffer = cx.new(|cx| Buffer::local("", cx));
 1119        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1120        Self::new(
 1121            EditorMode::AutoHeight { max_lines },
 1122            buffer,
 1123            None,
 1124            window,
 1125            cx,
 1126        )
 1127    }
 1128
 1129    pub fn for_buffer(
 1130        buffer: Entity<Buffer>,
 1131        project: Option<Entity<Project>>,
 1132        window: &mut Window,
 1133        cx: &mut Context<Self>,
 1134    ) -> Self {
 1135        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1136        Self::new(EditorMode::Full, buffer, project, window, cx)
 1137    }
 1138
 1139    pub fn for_multibuffer(
 1140        buffer: Entity<MultiBuffer>,
 1141        project: Option<Entity<Project>>,
 1142        window: &mut Window,
 1143        cx: &mut Context<Self>,
 1144    ) -> Self {
 1145        Self::new(EditorMode::Full, buffer, project, window, cx)
 1146    }
 1147
 1148    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1149        let mut clone = Self::new(
 1150            self.mode,
 1151            self.buffer.clone(),
 1152            self.project.clone(),
 1153            window,
 1154            cx,
 1155        );
 1156        self.display_map.update(cx, |display_map, cx| {
 1157            let snapshot = display_map.snapshot(cx);
 1158            clone.display_map.update(cx, |display_map, cx| {
 1159                display_map.set_state(&snapshot, cx);
 1160            });
 1161        });
 1162        clone.selections.clone_state(&self.selections);
 1163        clone.scroll_manager.clone_state(&self.scroll_manager);
 1164        clone.searchable = self.searchable;
 1165        clone
 1166    }
 1167
 1168    pub fn new(
 1169        mode: EditorMode,
 1170        buffer: Entity<MultiBuffer>,
 1171        project: Option<Entity<Project>>,
 1172        window: &mut Window,
 1173        cx: &mut Context<Self>,
 1174    ) -> Self {
 1175        let style = window.text_style();
 1176        let font_size = style.font_size.to_pixels(window.rem_size());
 1177        let editor = cx.entity().downgrade();
 1178        let fold_placeholder = FoldPlaceholder {
 1179            constrain_width: true,
 1180            render: Arc::new(move |fold_id, fold_range, cx| {
 1181                let editor = editor.clone();
 1182                div()
 1183                    .id(fold_id)
 1184                    .bg(cx.theme().colors().ghost_element_background)
 1185                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1186                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1187                    .rounded_xs()
 1188                    .size_full()
 1189                    .cursor_pointer()
 1190                    .child("")
 1191                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1192                    .on_click(move |_, _window, cx| {
 1193                        editor
 1194                            .update(cx, |editor, cx| {
 1195                                editor.unfold_ranges(
 1196                                    &[fold_range.start..fold_range.end],
 1197                                    true,
 1198                                    false,
 1199                                    cx,
 1200                                );
 1201                                cx.stop_propagation();
 1202                            })
 1203                            .ok();
 1204                    })
 1205                    .into_any()
 1206            }),
 1207            merge_adjacent: true,
 1208            ..Default::default()
 1209        };
 1210        let display_map = cx.new(|cx| {
 1211            DisplayMap::new(
 1212                buffer.clone(),
 1213                style.font(),
 1214                font_size,
 1215                None,
 1216                FILE_HEADER_HEIGHT,
 1217                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1218                fold_placeholder,
 1219                cx,
 1220            )
 1221        });
 1222
 1223        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1224
 1225        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1226
 1227        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1228            .then(|| language_settings::SoftWrap::None);
 1229
 1230        let mut project_subscriptions = Vec::new();
 1231        if mode == EditorMode::Full {
 1232            if let Some(project) = project.as_ref() {
 1233                project_subscriptions.push(cx.subscribe_in(
 1234                    project,
 1235                    window,
 1236                    |editor, _, event, window, cx| match event {
 1237                        project::Event::RefreshCodeLens => {
 1238                            // we always query lens with actions, without storing them, always refreshing them
 1239                        }
 1240                        project::Event::RefreshInlayHints => {
 1241                            editor
 1242                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1243                        }
 1244                        project::Event::SnippetEdit(id, snippet_edits) => {
 1245                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1246                                let focus_handle = editor.focus_handle(cx);
 1247                                if focus_handle.is_focused(window) {
 1248                                    let snapshot = buffer.read(cx).snapshot();
 1249                                    for (range, snippet) in snippet_edits {
 1250                                        let editor_range =
 1251                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1252                                        editor
 1253                                            .insert_snippet(
 1254                                                &[editor_range],
 1255                                                snippet.clone(),
 1256                                                window,
 1257                                                cx,
 1258                                            )
 1259                                            .ok();
 1260                                    }
 1261                                }
 1262                            }
 1263                        }
 1264                        _ => {}
 1265                    },
 1266                ));
 1267                if let Some(task_inventory) = project
 1268                    .read(cx)
 1269                    .task_store()
 1270                    .read(cx)
 1271                    .task_inventory()
 1272                    .cloned()
 1273                {
 1274                    project_subscriptions.push(cx.observe_in(
 1275                        &task_inventory,
 1276                        window,
 1277                        |editor, _, window, cx| {
 1278                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1279                        },
 1280                    ));
 1281                }
 1282            }
 1283        }
 1284
 1285        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1286
 1287        let inlay_hint_settings =
 1288            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1289        let focus_handle = cx.focus_handle();
 1290        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1291            .detach();
 1292        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1293            .detach();
 1294        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1295            .detach();
 1296        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1297            .detach();
 1298
 1299        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1300            Some(false)
 1301        } else {
 1302            None
 1303        };
 1304
 1305        let mut code_action_providers = Vec::new();
 1306        let mut load_uncommitted_diff = None;
 1307        if let Some(project) = project.clone() {
 1308            load_uncommitted_diff = Some(
 1309                get_uncommitted_diff_for_buffer(
 1310                    &project,
 1311                    buffer.read(cx).all_buffers(),
 1312                    buffer.clone(),
 1313                    cx,
 1314                )
 1315                .shared(),
 1316            );
 1317            code_action_providers.push(Rc::new(project) as Rc<_>);
 1318        }
 1319
 1320        let mut this = Self {
 1321            focus_handle,
 1322            show_cursor_when_unfocused: false,
 1323            last_focused_descendant: None,
 1324            buffer: buffer.clone(),
 1325            display_map: display_map.clone(),
 1326            selections,
 1327            scroll_manager: ScrollManager::new(cx),
 1328            columnar_selection_tail: None,
 1329            add_selections_state: None,
 1330            select_next_state: None,
 1331            select_prev_state: None,
 1332            selection_history: Default::default(),
 1333            autoclose_regions: Default::default(),
 1334            snippet_stack: Default::default(),
 1335            select_larger_syntax_node_stack: Vec::new(),
 1336            ime_transaction: Default::default(),
 1337            active_diagnostics: None,
 1338            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1339            inline_diagnostics_update: Task::ready(()),
 1340            inline_diagnostics: Vec::new(),
 1341            soft_wrap_mode_override,
 1342            hard_wrap: None,
 1343            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1344            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1345            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1346            project,
 1347            blink_manager: blink_manager.clone(),
 1348            show_local_selections: true,
 1349            show_scrollbars: true,
 1350            mode,
 1351            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1352            show_gutter: mode == EditorMode::Full,
 1353            show_line_numbers: None,
 1354            use_relative_line_numbers: None,
 1355            show_git_diff_gutter: None,
 1356            show_code_actions: None,
 1357            show_runnables: None,
 1358            show_wrap_guides: None,
 1359            show_indent_guides,
 1360            placeholder_text: None,
 1361            highlight_order: 0,
 1362            highlighted_rows: HashMap::default(),
 1363            background_highlights: Default::default(),
 1364            gutter_highlights: TreeMap::default(),
 1365            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1366            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1367            nav_history: None,
 1368            context_menu: RefCell::new(None),
 1369            mouse_context_menu: None,
 1370            completion_tasks: Default::default(),
 1371            signature_help_state: SignatureHelpState::default(),
 1372            auto_signature_help: None,
 1373            find_all_references_task_sources: Vec::new(),
 1374            next_completion_id: 0,
 1375            next_inlay_id: 0,
 1376            code_action_providers,
 1377            available_code_actions: Default::default(),
 1378            code_actions_task: Default::default(),
 1379            selection_highlight_task: Default::default(),
 1380            document_highlights_task: Default::default(),
 1381            linked_editing_range_task: Default::default(),
 1382            pending_rename: Default::default(),
 1383            searchable: true,
 1384            cursor_shape: EditorSettings::get_global(cx)
 1385                .cursor_shape
 1386                .unwrap_or_default(),
 1387            current_line_highlight: None,
 1388            autoindent_mode: Some(AutoindentMode::EachLine),
 1389            collapse_matches: false,
 1390            workspace: None,
 1391            input_enabled: true,
 1392            use_modal_editing: mode == EditorMode::Full,
 1393            read_only: false,
 1394            use_autoclose: true,
 1395            use_auto_surround: true,
 1396            auto_replace_emoji_shortcode: false,
 1397            jsx_tag_auto_close_enabled_in_any_buffer: false,
 1398            leader_peer_id: None,
 1399            remote_id: None,
 1400            hover_state: Default::default(),
 1401            pending_mouse_down: None,
 1402            hovered_link_state: Default::default(),
 1403            edit_prediction_provider: None,
 1404            active_inline_completion: None,
 1405            stale_inline_completion_in_menu: None,
 1406            edit_prediction_preview: EditPredictionPreview::Inactive {
 1407                released_too_fast: false,
 1408            },
 1409            inline_diagnostics_enabled: mode == EditorMode::Full,
 1410            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1411
 1412            gutter_hovered: false,
 1413            pixel_position_of_newest_cursor: None,
 1414            last_bounds: None,
 1415            last_position_map: None,
 1416            expect_bounds_change: None,
 1417            gutter_dimensions: GutterDimensions::default(),
 1418            style: None,
 1419            show_cursor_names: false,
 1420            hovered_cursors: Default::default(),
 1421            next_editor_action_id: EditorActionId::default(),
 1422            editor_actions: Rc::default(),
 1423            inline_completions_hidden_for_vim_mode: false,
 1424            show_inline_completions_override: None,
 1425            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1426            edit_prediction_settings: EditPredictionSettings::Disabled,
 1427            edit_prediction_indent_conflict: false,
 1428            edit_prediction_requires_modifier_in_indent_conflict: true,
 1429            custom_context_menu: None,
 1430            show_git_blame_gutter: false,
 1431            show_git_blame_inline: false,
 1432            show_selection_menu: None,
 1433            show_git_blame_inline_delay_task: None,
 1434            git_blame_inline_tooltip: None,
 1435            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1436            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1437                .session
 1438                .restore_unsaved_buffers,
 1439            blame: None,
 1440            blame_subscription: None,
 1441            tasks: Default::default(),
 1442            _subscriptions: vec![
 1443                cx.observe(&buffer, Self::on_buffer_changed),
 1444                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1445                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1446                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1447                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1448                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1449                cx.observe_window_activation(window, |editor, window, cx| {
 1450                    let active = window.is_window_active();
 1451                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1452                        if active {
 1453                            blink_manager.enable(cx);
 1454                        } else {
 1455                            blink_manager.disable(cx);
 1456                        }
 1457                    });
 1458                }),
 1459            ],
 1460            tasks_update_task: None,
 1461            linked_edit_ranges: Default::default(),
 1462            in_project_search: false,
 1463            previous_search_ranges: None,
 1464            breadcrumb_header: None,
 1465            focused_block: None,
 1466            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1467            addons: HashMap::default(),
 1468            registered_buffers: HashMap::default(),
 1469            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1470            selection_mark_mode: false,
 1471            toggle_fold_multiple_buffers: Task::ready(()),
 1472            serialize_selections: Task::ready(()),
 1473            text_style_refinement: None,
 1474            load_diff_task: load_uncommitted_diff,
 1475        };
 1476        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1477        this._subscriptions.extend(project_subscriptions);
 1478
 1479        this.end_selection(window, cx);
 1480        this.scroll_manager.show_scrollbar(window, cx);
 1481        jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
 1482
 1483        if mode == EditorMode::Full {
 1484            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1485            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1486
 1487            if this.git_blame_inline_enabled {
 1488                this.git_blame_inline_enabled = true;
 1489                this.start_git_blame_inline(false, window, cx);
 1490            }
 1491
 1492            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1493                if let Some(project) = this.project.as_ref() {
 1494                    let handle = project.update(cx, |project, cx| {
 1495                        project.register_buffer_with_language_servers(&buffer, cx)
 1496                    });
 1497                    this.registered_buffers
 1498                        .insert(buffer.read(cx).remote_id(), handle);
 1499                }
 1500            }
 1501        }
 1502
 1503        this.report_editor_event("Editor Opened", None, cx);
 1504        this
 1505    }
 1506
 1507    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1508        self.mouse_context_menu
 1509            .as_ref()
 1510            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1511    }
 1512
 1513    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1514        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1515    }
 1516
 1517    fn key_context_internal(
 1518        &self,
 1519        has_active_edit_prediction: bool,
 1520        window: &Window,
 1521        cx: &App,
 1522    ) -> KeyContext {
 1523        let mut key_context = KeyContext::new_with_defaults();
 1524        key_context.add("Editor");
 1525        let mode = match self.mode {
 1526            EditorMode::SingleLine { .. } => "single_line",
 1527            EditorMode::AutoHeight { .. } => "auto_height",
 1528            EditorMode::Full => "full",
 1529        };
 1530
 1531        if EditorSettings::jupyter_enabled(cx) {
 1532            key_context.add("jupyter");
 1533        }
 1534
 1535        key_context.set("mode", mode);
 1536        if self.pending_rename.is_some() {
 1537            key_context.add("renaming");
 1538        }
 1539
 1540        match self.context_menu.borrow().as_ref() {
 1541            Some(CodeContextMenu::Completions(_)) => {
 1542                key_context.add("menu");
 1543                key_context.add("showing_completions");
 1544            }
 1545            Some(CodeContextMenu::CodeActions(_)) => {
 1546                key_context.add("menu");
 1547                key_context.add("showing_code_actions")
 1548            }
 1549            None => {}
 1550        }
 1551
 1552        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1553        if !self.focus_handle(cx).contains_focused(window, cx)
 1554            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1555        {
 1556            for addon in self.addons.values() {
 1557                addon.extend_key_context(&mut key_context, cx)
 1558            }
 1559        }
 1560
 1561        if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
 1562            if let Some(extension) = singleton_buffer
 1563                .read(cx)
 1564                .file()
 1565                .and_then(|file| file.path().extension()?.to_str())
 1566            {
 1567                key_context.set("extension", extension.to_string());
 1568            }
 1569        } else {
 1570            key_context.add("multibuffer");
 1571        }
 1572
 1573        if has_active_edit_prediction {
 1574            if self.edit_prediction_in_conflict() {
 1575                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1576            } else {
 1577                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1578                key_context.add("copilot_suggestion");
 1579            }
 1580        }
 1581
 1582        if self.selection_mark_mode {
 1583            key_context.add("selection_mode");
 1584        }
 1585
 1586        key_context
 1587    }
 1588
 1589    pub fn edit_prediction_in_conflict(&self) -> bool {
 1590        if !self.show_edit_predictions_in_menu() {
 1591            return false;
 1592        }
 1593
 1594        let showing_completions = self
 1595            .context_menu
 1596            .borrow()
 1597            .as_ref()
 1598            .map_or(false, |context| {
 1599                matches!(context, CodeContextMenu::Completions(_))
 1600            });
 1601
 1602        showing_completions
 1603            || self.edit_prediction_requires_modifier()
 1604            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1605            // bindings to insert tab characters.
 1606            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 1607    }
 1608
 1609    pub fn accept_edit_prediction_keybind(
 1610        &self,
 1611        window: &Window,
 1612        cx: &App,
 1613    ) -> AcceptEditPredictionBinding {
 1614        let key_context = self.key_context_internal(true, window, cx);
 1615        let in_conflict = self.edit_prediction_in_conflict();
 1616
 1617        AcceptEditPredictionBinding(
 1618            window
 1619                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1620                .into_iter()
 1621                .filter(|binding| {
 1622                    !in_conflict
 1623                        || binding
 1624                            .keystrokes()
 1625                            .first()
 1626                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1627                })
 1628                .rev()
 1629                .min_by_key(|binding| {
 1630                    binding
 1631                        .keystrokes()
 1632                        .first()
 1633                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1634                }),
 1635        )
 1636    }
 1637
 1638    pub fn new_file(
 1639        workspace: &mut Workspace,
 1640        _: &workspace::NewFile,
 1641        window: &mut Window,
 1642        cx: &mut Context<Workspace>,
 1643    ) {
 1644        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1645            "Failed to create buffer",
 1646            window,
 1647            cx,
 1648            |e, _, _| match e.error_code() {
 1649                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1650                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1651                e.error_tag("required").unwrap_or("the latest version")
 1652            )),
 1653                _ => None,
 1654            },
 1655        );
 1656    }
 1657
 1658    pub fn new_in_workspace(
 1659        workspace: &mut Workspace,
 1660        window: &mut Window,
 1661        cx: &mut Context<Workspace>,
 1662    ) -> Task<Result<Entity<Editor>>> {
 1663        let project = workspace.project().clone();
 1664        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1665
 1666        cx.spawn_in(window, |workspace, mut cx| async move {
 1667            let buffer = create.await?;
 1668            workspace.update_in(&mut cx, |workspace, window, cx| {
 1669                let editor =
 1670                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1671                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1672                editor
 1673            })
 1674        })
 1675    }
 1676
 1677    fn new_file_vertical(
 1678        workspace: &mut Workspace,
 1679        _: &workspace::NewFileSplitVertical,
 1680        window: &mut Window,
 1681        cx: &mut Context<Workspace>,
 1682    ) {
 1683        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1684    }
 1685
 1686    fn new_file_horizontal(
 1687        workspace: &mut Workspace,
 1688        _: &workspace::NewFileSplitHorizontal,
 1689        window: &mut Window,
 1690        cx: &mut Context<Workspace>,
 1691    ) {
 1692        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1693    }
 1694
 1695    fn new_file_in_direction(
 1696        workspace: &mut Workspace,
 1697        direction: SplitDirection,
 1698        window: &mut Window,
 1699        cx: &mut Context<Workspace>,
 1700    ) {
 1701        let project = workspace.project().clone();
 1702        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1703
 1704        cx.spawn_in(window, |workspace, mut cx| async move {
 1705            let buffer = create.await?;
 1706            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1707                workspace.split_item(
 1708                    direction,
 1709                    Box::new(
 1710                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1711                    ),
 1712                    window,
 1713                    cx,
 1714                )
 1715            })?;
 1716            anyhow::Ok(())
 1717        })
 1718        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1719            match e.error_code() {
 1720                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1721                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1722                e.error_tag("required").unwrap_or("the latest version")
 1723            )),
 1724                _ => None,
 1725            }
 1726        });
 1727    }
 1728
 1729    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1730        self.leader_peer_id
 1731    }
 1732
 1733    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1734        &self.buffer
 1735    }
 1736
 1737    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1738        self.workspace.as_ref()?.0.upgrade()
 1739    }
 1740
 1741    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1742        self.buffer().read(cx).title(cx)
 1743    }
 1744
 1745    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1746        let git_blame_gutter_max_author_length = self
 1747            .render_git_blame_gutter(cx)
 1748            .then(|| {
 1749                if let Some(blame) = self.blame.as_ref() {
 1750                    let max_author_length =
 1751                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1752                    Some(max_author_length)
 1753                } else {
 1754                    None
 1755                }
 1756            })
 1757            .flatten();
 1758
 1759        EditorSnapshot {
 1760            mode: self.mode,
 1761            show_gutter: self.show_gutter,
 1762            show_line_numbers: self.show_line_numbers,
 1763            show_git_diff_gutter: self.show_git_diff_gutter,
 1764            show_code_actions: self.show_code_actions,
 1765            show_runnables: self.show_runnables,
 1766            git_blame_gutter_max_author_length,
 1767            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1768            scroll_anchor: self.scroll_manager.anchor(),
 1769            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1770            placeholder_text: self.placeholder_text.clone(),
 1771            is_focused: self.focus_handle.is_focused(window),
 1772            current_line_highlight: self
 1773                .current_line_highlight
 1774                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1775            gutter_hovered: self.gutter_hovered,
 1776        }
 1777    }
 1778
 1779    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1780        self.buffer.read(cx).language_at(point, cx)
 1781    }
 1782
 1783    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1784        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1785    }
 1786
 1787    pub fn active_excerpt(
 1788        &self,
 1789        cx: &App,
 1790    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1791        self.buffer
 1792            .read(cx)
 1793            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1794    }
 1795
 1796    pub fn mode(&self) -> EditorMode {
 1797        self.mode
 1798    }
 1799
 1800    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1801        self.collaboration_hub.as_deref()
 1802    }
 1803
 1804    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1805        self.collaboration_hub = Some(hub);
 1806    }
 1807
 1808    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1809        self.in_project_search = in_project_search;
 1810    }
 1811
 1812    pub fn set_custom_context_menu(
 1813        &mut self,
 1814        f: impl 'static
 1815            + Fn(
 1816                &mut Self,
 1817                DisplayPoint,
 1818                &mut Window,
 1819                &mut Context<Self>,
 1820            ) -> Option<Entity<ui::ContextMenu>>,
 1821    ) {
 1822        self.custom_context_menu = Some(Box::new(f))
 1823    }
 1824
 1825    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1826        self.completion_provider = provider;
 1827    }
 1828
 1829    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1830        self.semantics_provider.clone()
 1831    }
 1832
 1833    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1834        self.semantics_provider = provider;
 1835    }
 1836
 1837    pub fn set_edit_prediction_provider<T>(
 1838        &mut self,
 1839        provider: Option<Entity<T>>,
 1840        window: &mut Window,
 1841        cx: &mut Context<Self>,
 1842    ) where
 1843        T: EditPredictionProvider,
 1844    {
 1845        self.edit_prediction_provider =
 1846            provider.map(|provider| RegisteredInlineCompletionProvider {
 1847                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1848                    if this.focus_handle.is_focused(window) {
 1849                        this.update_visible_inline_completion(window, cx);
 1850                    }
 1851                }),
 1852                provider: Arc::new(provider),
 1853            });
 1854        self.update_edit_prediction_settings(cx);
 1855        self.refresh_inline_completion(false, false, window, cx);
 1856    }
 1857
 1858    pub fn placeholder_text(&self) -> Option<&str> {
 1859        self.placeholder_text.as_deref()
 1860    }
 1861
 1862    pub fn set_placeholder_text(
 1863        &mut self,
 1864        placeholder_text: impl Into<Arc<str>>,
 1865        cx: &mut Context<Self>,
 1866    ) {
 1867        let placeholder_text = Some(placeholder_text.into());
 1868        if self.placeholder_text != placeholder_text {
 1869            self.placeholder_text = placeholder_text;
 1870            cx.notify();
 1871        }
 1872    }
 1873
 1874    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1875        self.cursor_shape = cursor_shape;
 1876
 1877        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1878        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1879
 1880        cx.notify();
 1881    }
 1882
 1883    pub fn set_current_line_highlight(
 1884        &mut self,
 1885        current_line_highlight: Option<CurrentLineHighlight>,
 1886    ) {
 1887        self.current_line_highlight = current_line_highlight;
 1888    }
 1889
 1890    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1891        self.collapse_matches = collapse_matches;
 1892    }
 1893
 1894    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1895        let buffers = self.buffer.read(cx).all_buffers();
 1896        let Some(project) = self.project.as_ref() else {
 1897            return;
 1898        };
 1899        project.update(cx, |project, cx| {
 1900            for buffer in buffers {
 1901                self.registered_buffers
 1902                    .entry(buffer.read(cx).remote_id())
 1903                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 1904            }
 1905        })
 1906    }
 1907
 1908    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1909        if self.collapse_matches {
 1910            return range.start..range.start;
 1911        }
 1912        range.clone()
 1913    }
 1914
 1915    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1916        if self.display_map.read(cx).clip_at_line_ends != clip {
 1917            self.display_map
 1918                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1919        }
 1920    }
 1921
 1922    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1923        self.input_enabled = input_enabled;
 1924    }
 1925
 1926    pub fn set_inline_completions_hidden_for_vim_mode(
 1927        &mut self,
 1928        hidden: bool,
 1929        window: &mut Window,
 1930        cx: &mut Context<Self>,
 1931    ) {
 1932        if hidden != self.inline_completions_hidden_for_vim_mode {
 1933            self.inline_completions_hidden_for_vim_mode = hidden;
 1934            if hidden {
 1935                self.update_visible_inline_completion(window, cx);
 1936            } else {
 1937                self.refresh_inline_completion(true, false, window, cx);
 1938            }
 1939        }
 1940    }
 1941
 1942    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1943        self.menu_inline_completions_policy = value;
 1944    }
 1945
 1946    pub fn set_autoindent(&mut self, autoindent: bool) {
 1947        if autoindent {
 1948            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1949        } else {
 1950            self.autoindent_mode = None;
 1951        }
 1952    }
 1953
 1954    pub fn read_only(&self, cx: &App) -> bool {
 1955        self.read_only || self.buffer.read(cx).read_only()
 1956    }
 1957
 1958    pub fn set_read_only(&mut self, read_only: bool) {
 1959        self.read_only = read_only;
 1960    }
 1961
 1962    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1963        self.use_autoclose = autoclose;
 1964    }
 1965
 1966    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1967        self.use_auto_surround = auto_surround;
 1968    }
 1969
 1970    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1971        self.auto_replace_emoji_shortcode = auto_replace;
 1972    }
 1973
 1974    pub fn toggle_edit_predictions(
 1975        &mut self,
 1976        _: &ToggleEditPrediction,
 1977        window: &mut Window,
 1978        cx: &mut Context<Self>,
 1979    ) {
 1980        if self.show_inline_completions_override.is_some() {
 1981            self.set_show_edit_predictions(None, window, cx);
 1982        } else {
 1983            let show_edit_predictions = !self.edit_predictions_enabled();
 1984            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 1985        }
 1986    }
 1987
 1988    pub fn set_show_edit_predictions(
 1989        &mut self,
 1990        show_edit_predictions: Option<bool>,
 1991        window: &mut Window,
 1992        cx: &mut Context<Self>,
 1993    ) {
 1994        self.show_inline_completions_override = show_edit_predictions;
 1995        self.update_edit_prediction_settings(cx);
 1996
 1997        if let Some(false) = show_edit_predictions {
 1998            self.discard_inline_completion(false, cx);
 1999        } else {
 2000            self.refresh_inline_completion(false, true, window, cx);
 2001        }
 2002    }
 2003
 2004    fn inline_completions_disabled_in_scope(
 2005        &self,
 2006        buffer: &Entity<Buffer>,
 2007        buffer_position: language::Anchor,
 2008        cx: &App,
 2009    ) -> bool {
 2010        let snapshot = buffer.read(cx).snapshot();
 2011        let settings = snapshot.settings_at(buffer_position, cx);
 2012
 2013        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2014            return false;
 2015        };
 2016
 2017        scope.override_name().map_or(false, |scope_name| {
 2018            settings
 2019                .edit_predictions_disabled_in
 2020                .iter()
 2021                .any(|s| s == scope_name)
 2022        })
 2023    }
 2024
 2025    pub fn set_use_modal_editing(&mut self, to: bool) {
 2026        self.use_modal_editing = to;
 2027    }
 2028
 2029    pub fn use_modal_editing(&self) -> bool {
 2030        self.use_modal_editing
 2031    }
 2032
 2033    fn selections_did_change(
 2034        &mut self,
 2035        local: bool,
 2036        old_cursor_position: &Anchor,
 2037        show_completions: bool,
 2038        window: &mut Window,
 2039        cx: &mut Context<Self>,
 2040    ) {
 2041        window.invalidate_character_coordinates();
 2042
 2043        // Copy selections to primary selection buffer
 2044        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2045        if local {
 2046            let selections = self.selections.all::<usize>(cx);
 2047            let buffer_handle = self.buffer.read(cx).read(cx);
 2048
 2049            let mut text = String::new();
 2050            for (index, selection) in selections.iter().enumerate() {
 2051                let text_for_selection = buffer_handle
 2052                    .text_for_range(selection.start..selection.end)
 2053                    .collect::<String>();
 2054
 2055                text.push_str(&text_for_selection);
 2056                if index != selections.len() - 1 {
 2057                    text.push('\n');
 2058                }
 2059            }
 2060
 2061            if !text.is_empty() {
 2062                cx.write_to_primary(ClipboardItem::new_string(text));
 2063            }
 2064        }
 2065
 2066        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2067            self.buffer.update(cx, |buffer, cx| {
 2068                buffer.set_active_selections(
 2069                    &self.selections.disjoint_anchors(),
 2070                    self.selections.line_mode,
 2071                    self.cursor_shape,
 2072                    cx,
 2073                )
 2074            });
 2075        }
 2076        let display_map = self
 2077            .display_map
 2078            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2079        let buffer = &display_map.buffer_snapshot;
 2080        self.add_selections_state = None;
 2081        self.select_next_state = None;
 2082        self.select_prev_state = None;
 2083        self.select_larger_syntax_node_stack.clear();
 2084        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2085        self.snippet_stack
 2086            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2087        self.take_rename(false, window, cx);
 2088
 2089        let new_cursor_position = self.selections.newest_anchor().head();
 2090
 2091        self.push_to_nav_history(
 2092            *old_cursor_position,
 2093            Some(new_cursor_position.to_point(buffer)),
 2094            cx,
 2095        );
 2096
 2097        if local {
 2098            let new_cursor_position = self.selections.newest_anchor().head();
 2099            let mut context_menu = self.context_menu.borrow_mut();
 2100            let completion_menu = match context_menu.as_ref() {
 2101                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2102                _ => {
 2103                    *context_menu = None;
 2104                    None
 2105                }
 2106            };
 2107            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2108                if !self.registered_buffers.contains_key(&buffer_id) {
 2109                    if let Some(project) = self.project.as_ref() {
 2110                        project.update(cx, |project, cx| {
 2111                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2112                                return;
 2113                            };
 2114                            self.registered_buffers.insert(
 2115                                buffer_id,
 2116                                project.register_buffer_with_language_servers(&buffer, cx),
 2117                            );
 2118                        })
 2119                    }
 2120                }
 2121            }
 2122
 2123            if let Some(completion_menu) = completion_menu {
 2124                let cursor_position = new_cursor_position.to_offset(buffer);
 2125                let (word_range, kind) =
 2126                    buffer.surrounding_word(completion_menu.initial_position, true);
 2127                if kind == Some(CharKind::Word)
 2128                    && word_range.to_inclusive().contains(&cursor_position)
 2129                {
 2130                    let mut completion_menu = completion_menu.clone();
 2131                    drop(context_menu);
 2132
 2133                    let query = Self::completion_query(buffer, cursor_position);
 2134                    cx.spawn(move |this, mut cx| async move {
 2135                        completion_menu
 2136                            .filter(query.as_deref(), cx.background_executor().clone())
 2137                            .await;
 2138
 2139                        this.update(&mut cx, |this, cx| {
 2140                            let mut context_menu = this.context_menu.borrow_mut();
 2141                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2142                            else {
 2143                                return;
 2144                            };
 2145
 2146                            if menu.id > completion_menu.id {
 2147                                return;
 2148                            }
 2149
 2150                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2151                            drop(context_menu);
 2152                            cx.notify();
 2153                        })
 2154                    })
 2155                    .detach();
 2156
 2157                    if show_completions {
 2158                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2159                    }
 2160                } else {
 2161                    drop(context_menu);
 2162                    self.hide_context_menu(window, cx);
 2163                }
 2164            } else {
 2165                drop(context_menu);
 2166            }
 2167
 2168            hide_hover(self, cx);
 2169
 2170            if old_cursor_position.to_display_point(&display_map).row()
 2171                != new_cursor_position.to_display_point(&display_map).row()
 2172            {
 2173                self.available_code_actions.take();
 2174            }
 2175            self.refresh_code_actions(window, cx);
 2176            self.refresh_document_highlights(cx);
 2177            self.refresh_selected_text_highlights(window, cx);
 2178            refresh_matching_bracket_highlights(self, window, cx);
 2179            self.update_visible_inline_completion(window, cx);
 2180            self.edit_prediction_requires_modifier_in_indent_conflict = true;
 2181            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2182            if self.git_blame_inline_enabled {
 2183                self.start_inline_blame_timer(window, cx);
 2184            }
 2185        }
 2186
 2187        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2188        cx.emit(EditorEvent::SelectionsChanged { local });
 2189
 2190        let selections = &self.selections.disjoint;
 2191        if selections.len() == 1 {
 2192            cx.emit(SearchEvent::ActiveMatchChanged)
 2193        }
 2194        if local
 2195            && self.is_singleton(cx)
 2196            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
 2197        {
 2198            if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
 2199                let background_executor = cx.background_executor().clone();
 2200                let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2201                let snapshot = self.buffer().read(cx).snapshot(cx);
 2202                let selections = selections.clone();
 2203                self.serialize_selections = cx.background_spawn(async move {
 2204                    background_executor.timer(Duration::from_millis(100)).await;
 2205                    let selections = selections
 2206                        .iter()
 2207                        .map(|selection| {
 2208                            (
 2209                                selection.start.to_offset(&snapshot),
 2210                                selection.end.to_offset(&snapshot),
 2211                            )
 2212                        })
 2213                        .collect();
 2214                    DB.save_editor_selections(editor_id, workspace_id, selections)
 2215                        .await
 2216                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2217                        .log_err();
 2218                });
 2219            }
 2220        }
 2221
 2222        cx.notify();
 2223    }
 2224
 2225    pub fn sync_selections(
 2226        &mut self,
 2227        other: Entity<Editor>,
 2228        cx: &mut Context<Self>,
 2229    ) -> gpui::Subscription {
 2230        let other_selections = other.read(cx).selections.disjoint.to_vec();
 2231        self.selections.change_with(cx, |selections| {
 2232            selections.select_anchors(other_selections);
 2233        });
 2234
 2235        let other_subscription =
 2236            cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
 2237                EditorEvent::SelectionsChanged { local: true } => {
 2238                    let other_selections = other.read(cx).selections.disjoint.to_vec();
 2239                    if other_selections.is_empty() {
 2240                        return;
 2241                    }
 2242                    this.selections.change_with(cx, |selections| {
 2243                        selections.select_anchors(other_selections);
 2244                    });
 2245                }
 2246                _ => {}
 2247            });
 2248
 2249        let this_subscription =
 2250            cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
 2251                EditorEvent::SelectionsChanged { local: true } => {
 2252                    let these_selections = this.selections.disjoint.to_vec();
 2253                    if these_selections.is_empty() {
 2254                        return;
 2255                    }
 2256                    other.update(cx, |other_editor, cx| {
 2257                        other_editor.selections.change_with(cx, |selections| {
 2258                            selections.select_anchors(these_selections);
 2259                        })
 2260                    });
 2261                }
 2262                _ => {}
 2263            });
 2264
 2265        Subscription::join(other_subscription, this_subscription)
 2266    }
 2267
 2268    pub fn change_selections<R>(
 2269        &mut self,
 2270        autoscroll: Option<Autoscroll>,
 2271        window: &mut Window,
 2272        cx: &mut Context<Self>,
 2273        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2274    ) -> R {
 2275        self.change_selections_inner(autoscroll, true, window, cx, change)
 2276    }
 2277
 2278    fn change_selections_inner<R>(
 2279        &mut self,
 2280        autoscroll: Option<Autoscroll>,
 2281        request_completions: bool,
 2282        window: &mut Window,
 2283        cx: &mut Context<Self>,
 2284        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2285    ) -> R {
 2286        let old_cursor_position = self.selections.newest_anchor().head();
 2287        self.push_to_selection_history();
 2288
 2289        let (changed, result) = self.selections.change_with(cx, change);
 2290
 2291        if changed {
 2292            if let Some(autoscroll) = autoscroll {
 2293                self.request_autoscroll(autoscroll, cx);
 2294            }
 2295            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2296
 2297            if self.should_open_signature_help_automatically(
 2298                &old_cursor_position,
 2299                self.signature_help_state.backspace_pressed(),
 2300                cx,
 2301            ) {
 2302                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2303            }
 2304            self.signature_help_state.set_backspace_pressed(false);
 2305        }
 2306
 2307        result
 2308    }
 2309
 2310    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2311    where
 2312        I: IntoIterator<Item = (Range<S>, T)>,
 2313        S: ToOffset,
 2314        T: Into<Arc<str>>,
 2315    {
 2316        if self.read_only(cx) {
 2317            return;
 2318        }
 2319
 2320        self.buffer
 2321            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2322    }
 2323
 2324    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2325    where
 2326        I: IntoIterator<Item = (Range<S>, T)>,
 2327        S: ToOffset,
 2328        T: Into<Arc<str>>,
 2329    {
 2330        if self.read_only(cx) {
 2331            return;
 2332        }
 2333
 2334        self.buffer.update(cx, |buffer, cx| {
 2335            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2336        });
 2337    }
 2338
 2339    pub fn edit_with_block_indent<I, S, T>(
 2340        &mut self,
 2341        edits: I,
 2342        original_indent_columns: Vec<Option<u32>>,
 2343        cx: &mut Context<Self>,
 2344    ) where
 2345        I: IntoIterator<Item = (Range<S>, T)>,
 2346        S: ToOffset,
 2347        T: Into<Arc<str>>,
 2348    {
 2349        if self.read_only(cx) {
 2350            return;
 2351        }
 2352
 2353        self.buffer.update(cx, |buffer, cx| {
 2354            buffer.edit(
 2355                edits,
 2356                Some(AutoindentMode::Block {
 2357                    original_indent_columns,
 2358                }),
 2359                cx,
 2360            )
 2361        });
 2362    }
 2363
 2364    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2365        self.hide_context_menu(window, cx);
 2366
 2367        match phase {
 2368            SelectPhase::Begin {
 2369                position,
 2370                add,
 2371                click_count,
 2372            } => self.begin_selection(position, add, click_count, window, cx),
 2373            SelectPhase::BeginColumnar {
 2374                position,
 2375                goal_column,
 2376                reset,
 2377            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2378            SelectPhase::Extend {
 2379                position,
 2380                click_count,
 2381            } => self.extend_selection(position, click_count, window, cx),
 2382            SelectPhase::Update {
 2383                position,
 2384                goal_column,
 2385                scroll_delta,
 2386            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2387            SelectPhase::End => self.end_selection(window, cx),
 2388        }
 2389    }
 2390
 2391    fn extend_selection(
 2392        &mut self,
 2393        position: DisplayPoint,
 2394        click_count: usize,
 2395        window: &mut Window,
 2396        cx: &mut Context<Self>,
 2397    ) {
 2398        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2399        let tail = self.selections.newest::<usize>(cx).tail();
 2400        self.begin_selection(position, false, click_count, window, cx);
 2401
 2402        let position = position.to_offset(&display_map, Bias::Left);
 2403        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2404
 2405        let mut pending_selection = self
 2406            .selections
 2407            .pending_anchor()
 2408            .expect("extend_selection not called with pending selection");
 2409        if position >= tail {
 2410            pending_selection.start = tail_anchor;
 2411        } else {
 2412            pending_selection.end = tail_anchor;
 2413            pending_selection.reversed = true;
 2414        }
 2415
 2416        let mut pending_mode = self.selections.pending_mode().unwrap();
 2417        match &mut pending_mode {
 2418            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2419            _ => {}
 2420        }
 2421
 2422        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2423            s.set_pending(pending_selection, pending_mode)
 2424        });
 2425    }
 2426
 2427    fn begin_selection(
 2428        &mut self,
 2429        position: DisplayPoint,
 2430        add: bool,
 2431        click_count: usize,
 2432        window: &mut Window,
 2433        cx: &mut Context<Self>,
 2434    ) {
 2435        if !self.focus_handle.is_focused(window) {
 2436            self.last_focused_descendant = None;
 2437            window.focus(&self.focus_handle);
 2438        }
 2439
 2440        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2441        let buffer = &display_map.buffer_snapshot;
 2442        let newest_selection = self.selections.newest_anchor().clone();
 2443        let position = display_map.clip_point(position, Bias::Left);
 2444
 2445        let start;
 2446        let end;
 2447        let mode;
 2448        let mut auto_scroll;
 2449        match click_count {
 2450            1 => {
 2451                start = buffer.anchor_before(position.to_point(&display_map));
 2452                end = start;
 2453                mode = SelectMode::Character;
 2454                auto_scroll = true;
 2455            }
 2456            2 => {
 2457                let range = movement::surrounding_word(&display_map, position);
 2458                start = buffer.anchor_before(range.start.to_point(&display_map));
 2459                end = buffer.anchor_before(range.end.to_point(&display_map));
 2460                mode = SelectMode::Word(start..end);
 2461                auto_scroll = true;
 2462            }
 2463            3 => {
 2464                let position = display_map
 2465                    .clip_point(position, Bias::Left)
 2466                    .to_point(&display_map);
 2467                let line_start = display_map.prev_line_boundary(position).0;
 2468                let next_line_start = buffer.clip_point(
 2469                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2470                    Bias::Left,
 2471                );
 2472                start = buffer.anchor_before(line_start);
 2473                end = buffer.anchor_before(next_line_start);
 2474                mode = SelectMode::Line(start..end);
 2475                auto_scroll = true;
 2476            }
 2477            _ => {
 2478                start = buffer.anchor_before(0);
 2479                end = buffer.anchor_before(buffer.len());
 2480                mode = SelectMode::All;
 2481                auto_scroll = false;
 2482            }
 2483        }
 2484        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2485
 2486        let point_to_delete: Option<usize> = {
 2487            let selected_points: Vec<Selection<Point>> =
 2488                self.selections.disjoint_in_range(start..end, cx);
 2489
 2490            if !add || click_count > 1 {
 2491                None
 2492            } else if !selected_points.is_empty() {
 2493                Some(selected_points[0].id)
 2494            } else {
 2495                let clicked_point_already_selected =
 2496                    self.selections.disjoint.iter().find(|selection| {
 2497                        selection.start.to_point(buffer) == start.to_point(buffer)
 2498                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2499                    });
 2500
 2501                clicked_point_already_selected.map(|selection| selection.id)
 2502            }
 2503        };
 2504
 2505        let selections_count = self.selections.count();
 2506
 2507        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2508            if let Some(point_to_delete) = point_to_delete {
 2509                s.delete(point_to_delete);
 2510
 2511                if selections_count == 1 {
 2512                    s.set_pending_anchor_range(start..end, mode);
 2513                }
 2514            } else {
 2515                if !add {
 2516                    s.clear_disjoint();
 2517                } else if click_count > 1 {
 2518                    s.delete(newest_selection.id)
 2519                }
 2520
 2521                s.set_pending_anchor_range(start..end, mode);
 2522            }
 2523        });
 2524    }
 2525
 2526    fn begin_columnar_selection(
 2527        &mut self,
 2528        position: DisplayPoint,
 2529        goal_column: u32,
 2530        reset: bool,
 2531        window: &mut Window,
 2532        cx: &mut Context<Self>,
 2533    ) {
 2534        if !self.focus_handle.is_focused(window) {
 2535            self.last_focused_descendant = None;
 2536            window.focus(&self.focus_handle);
 2537        }
 2538
 2539        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2540
 2541        if reset {
 2542            let pointer_position = display_map
 2543                .buffer_snapshot
 2544                .anchor_before(position.to_point(&display_map));
 2545
 2546            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2547                s.clear_disjoint();
 2548                s.set_pending_anchor_range(
 2549                    pointer_position..pointer_position,
 2550                    SelectMode::Character,
 2551                );
 2552            });
 2553        }
 2554
 2555        let tail = self.selections.newest::<Point>(cx).tail();
 2556        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2557
 2558        if !reset {
 2559            self.select_columns(
 2560                tail.to_display_point(&display_map),
 2561                position,
 2562                goal_column,
 2563                &display_map,
 2564                window,
 2565                cx,
 2566            );
 2567        }
 2568    }
 2569
 2570    fn update_selection(
 2571        &mut self,
 2572        position: DisplayPoint,
 2573        goal_column: u32,
 2574        scroll_delta: gpui::Point<f32>,
 2575        window: &mut Window,
 2576        cx: &mut Context<Self>,
 2577    ) {
 2578        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2579
 2580        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2581            let tail = tail.to_display_point(&display_map);
 2582            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2583        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2584            let buffer = self.buffer.read(cx).snapshot(cx);
 2585            let head;
 2586            let tail;
 2587            let mode = self.selections.pending_mode().unwrap();
 2588            match &mode {
 2589                SelectMode::Character => {
 2590                    head = position.to_point(&display_map);
 2591                    tail = pending.tail().to_point(&buffer);
 2592                }
 2593                SelectMode::Word(original_range) => {
 2594                    let original_display_range = original_range.start.to_display_point(&display_map)
 2595                        ..original_range.end.to_display_point(&display_map);
 2596                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2597                        ..original_display_range.end.to_point(&display_map);
 2598                    if movement::is_inside_word(&display_map, position)
 2599                        || original_display_range.contains(&position)
 2600                    {
 2601                        let word_range = movement::surrounding_word(&display_map, position);
 2602                        if word_range.start < original_display_range.start {
 2603                            head = word_range.start.to_point(&display_map);
 2604                        } else {
 2605                            head = word_range.end.to_point(&display_map);
 2606                        }
 2607                    } else {
 2608                        head = position.to_point(&display_map);
 2609                    }
 2610
 2611                    if head <= original_buffer_range.start {
 2612                        tail = original_buffer_range.end;
 2613                    } else {
 2614                        tail = original_buffer_range.start;
 2615                    }
 2616                }
 2617                SelectMode::Line(original_range) => {
 2618                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2619
 2620                    let position = display_map
 2621                        .clip_point(position, Bias::Left)
 2622                        .to_point(&display_map);
 2623                    let line_start = display_map.prev_line_boundary(position).0;
 2624                    let next_line_start = buffer.clip_point(
 2625                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2626                        Bias::Left,
 2627                    );
 2628
 2629                    if line_start < original_range.start {
 2630                        head = line_start
 2631                    } else {
 2632                        head = next_line_start
 2633                    }
 2634
 2635                    if head <= original_range.start {
 2636                        tail = original_range.end;
 2637                    } else {
 2638                        tail = original_range.start;
 2639                    }
 2640                }
 2641                SelectMode::All => {
 2642                    return;
 2643                }
 2644            };
 2645
 2646            if head < tail {
 2647                pending.start = buffer.anchor_before(head);
 2648                pending.end = buffer.anchor_before(tail);
 2649                pending.reversed = true;
 2650            } else {
 2651                pending.start = buffer.anchor_before(tail);
 2652                pending.end = buffer.anchor_before(head);
 2653                pending.reversed = false;
 2654            }
 2655
 2656            self.change_selections(None, window, cx, |s| {
 2657                s.set_pending(pending, mode);
 2658            });
 2659        } else {
 2660            log::error!("update_selection dispatched with no pending selection");
 2661            return;
 2662        }
 2663
 2664        self.apply_scroll_delta(scroll_delta, window, cx);
 2665        cx.notify();
 2666    }
 2667
 2668    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2669        self.columnar_selection_tail.take();
 2670        if self.selections.pending_anchor().is_some() {
 2671            let selections = self.selections.all::<usize>(cx);
 2672            self.change_selections(None, window, cx, |s| {
 2673                s.select(selections);
 2674                s.clear_pending();
 2675            });
 2676        }
 2677    }
 2678
 2679    fn select_columns(
 2680        &mut self,
 2681        tail: DisplayPoint,
 2682        head: DisplayPoint,
 2683        goal_column: u32,
 2684        display_map: &DisplaySnapshot,
 2685        window: &mut Window,
 2686        cx: &mut Context<Self>,
 2687    ) {
 2688        let start_row = cmp::min(tail.row(), head.row());
 2689        let end_row = cmp::max(tail.row(), head.row());
 2690        let start_column = cmp::min(tail.column(), goal_column);
 2691        let end_column = cmp::max(tail.column(), goal_column);
 2692        let reversed = start_column < tail.column();
 2693
 2694        let selection_ranges = (start_row.0..=end_row.0)
 2695            .map(DisplayRow)
 2696            .filter_map(|row| {
 2697                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2698                    let start = display_map
 2699                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2700                        .to_point(display_map);
 2701                    let end = display_map
 2702                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2703                        .to_point(display_map);
 2704                    if reversed {
 2705                        Some(end..start)
 2706                    } else {
 2707                        Some(start..end)
 2708                    }
 2709                } else {
 2710                    None
 2711                }
 2712            })
 2713            .collect::<Vec<_>>();
 2714
 2715        self.change_selections(None, window, cx, |s| {
 2716            s.select_ranges(selection_ranges);
 2717        });
 2718        cx.notify();
 2719    }
 2720
 2721    pub fn has_pending_nonempty_selection(&self) -> bool {
 2722        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2723            Some(Selection { start, end, .. }) => start != end,
 2724            None => false,
 2725        };
 2726
 2727        pending_nonempty_selection
 2728            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2729    }
 2730
 2731    pub fn has_pending_selection(&self) -> bool {
 2732        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2733    }
 2734
 2735    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2736        self.selection_mark_mode = false;
 2737
 2738        if self.clear_expanded_diff_hunks(cx) {
 2739            cx.notify();
 2740            return;
 2741        }
 2742        if self.dismiss_menus_and_popups(true, window, cx) {
 2743            return;
 2744        }
 2745
 2746        if self.mode == EditorMode::Full
 2747            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2748        {
 2749            return;
 2750        }
 2751
 2752        cx.propagate();
 2753    }
 2754
 2755    pub fn dismiss_menus_and_popups(
 2756        &mut self,
 2757        is_user_requested: bool,
 2758        window: &mut Window,
 2759        cx: &mut Context<Self>,
 2760    ) -> bool {
 2761        if self.take_rename(false, window, cx).is_some() {
 2762            return true;
 2763        }
 2764
 2765        if hide_hover(self, cx) {
 2766            return true;
 2767        }
 2768
 2769        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2770            return true;
 2771        }
 2772
 2773        if self.hide_context_menu(window, cx).is_some() {
 2774            return true;
 2775        }
 2776
 2777        if self.mouse_context_menu.take().is_some() {
 2778            return true;
 2779        }
 2780
 2781        if is_user_requested && self.discard_inline_completion(true, cx) {
 2782            return true;
 2783        }
 2784
 2785        if self.snippet_stack.pop().is_some() {
 2786            return true;
 2787        }
 2788
 2789        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2790            self.dismiss_diagnostics(cx);
 2791            return true;
 2792        }
 2793
 2794        false
 2795    }
 2796
 2797    fn linked_editing_ranges_for(
 2798        &self,
 2799        selection: Range<text::Anchor>,
 2800        cx: &App,
 2801    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2802        if self.linked_edit_ranges.is_empty() {
 2803            return None;
 2804        }
 2805        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2806            selection.end.buffer_id.and_then(|end_buffer_id| {
 2807                if selection.start.buffer_id != Some(end_buffer_id) {
 2808                    return None;
 2809                }
 2810                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2811                let snapshot = buffer.read(cx).snapshot();
 2812                self.linked_edit_ranges
 2813                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2814                    .map(|ranges| (ranges, snapshot, buffer))
 2815            })?;
 2816        use text::ToOffset as TO;
 2817        // find offset from the start of current range to current cursor position
 2818        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2819
 2820        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2821        let start_difference = start_offset - start_byte_offset;
 2822        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2823        let end_difference = end_offset - start_byte_offset;
 2824        // Current range has associated linked ranges.
 2825        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2826        for range in linked_ranges.iter() {
 2827            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2828            let end_offset = start_offset + end_difference;
 2829            let start_offset = start_offset + start_difference;
 2830            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2831                continue;
 2832            }
 2833            if self.selections.disjoint_anchor_ranges().any(|s| {
 2834                if s.start.buffer_id != selection.start.buffer_id
 2835                    || s.end.buffer_id != selection.end.buffer_id
 2836                {
 2837                    return false;
 2838                }
 2839                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2840                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2841            }) {
 2842                continue;
 2843            }
 2844            let start = buffer_snapshot.anchor_after(start_offset);
 2845            let end = buffer_snapshot.anchor_after(end_offset);
 2846            linked_edits
 2847                .entry(buffer.clone())
 2848                .or_default()
 2849                .push(start..end);
 2850        }
 2851        Some(linked_edits)
 2852    }
 2853
 2854    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2855        let text: Arc<str> = text.into();
 2856
 2857        if self.read_only(cx) {
 2858            return;
 2859        }
 2860
 2861        let selections = self.selections.all_adjusted(cx);
 2862        let mut bracket_inserted = false;
 2863        let mut edits = Vec::new();
 2864        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2865        let mut new_selections = Vec::with_capacity(selections.len());
 2866        let mut new_autoclose_regions = Vec::new();
 2867        let snapshot = self.buffer.read(cx).read(cx);
 2868
 2869        for (selection, autoclose_region) in
 2870            self.selections_with_autoclose_regions(selections, &snapshot)
 2871        {
 2872            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2873                // Determine if the inserted text matches the opening or closing
 2874                // bracket of any of this language's bracket pairs.
 2875                let mut bracket_pair = None;
 2876                let mut is_bracket_pair_start = false;
 2877                let mut is_bracket_pair_end = false;
 2878                if !text.is_empty() {
 2879                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2880                    //  and they are removing the character that triggered IME popup.
 2881                    for (pair, enabled) in scope.brackets() {
 2882                        if !pair.close && !pair.surround {
 2883                            continue;
 2884                        }
 2885
 2886                        if enabled && pair.start.ends_with(text.as_ref()) {
 2887                            let prefix_len = pair.start.len() - text.len();
 2888                            let preceding_text_matches_prefix = prefix_len == 0
 2889                                || (selection.start.column >= (prefix_len as u32)
 2890                                    && snapshot.contains_str_at(
 2891                                        Point::new(
 2892                                            selection.start.row,
 2893                                            selection.start.column - (prefix_len as u32),
 2894                                        ),
 2895                                        &pair.start[..prefix_len],
 2896                                    ));
 2897                            if preceding_text_matches_prefix {
 2898                                bracket_pair = Some(pair.clone());
 2899                                is_bracket_pair_start = true;
 2900                                break;
 2901                            }
 2902                        }
 2903                        if pair.end.as_str() == text.as_ref() {
 2904                            bracket_pair = Some(pair.clone());
 2905                            is_bracket_pair_end = true;
 2906                            break;
 2907                        }
 2908                    }
 2909                }
 2910
 2911                if let Some(bracket_pair) = bracket_pair {
 2912                    let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
 2913                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2914                    let auto_surround =
 2915                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2916                    if selection.is_empty() {
 2917                        if is_bracket_pair_start {
 2918                            // If the inserted text is a suffix of an opening bracket and the
 2919                            // selection is preceded by the rest of the opening bracket, then
 2920                            // insert the closing bracket.
 2921                            let following_text_allows_autoclose = snapshot
 2922                                .chars_at(selection.start)
 2923                                .next()
 2924                                .map_or(true, |c| scope.should_autoclose_before(c));
 2925
 2926                            let preceding_text_allows_autoclose = selection.start.column == 0
 2927                                || snapshot.reversed_chars_at(selection.start).next().map_or(
 2928                                    true,
 2929                                    |c| {
 2930                                        bracket_pair.start != bracket_pair.end
 2931                                            || !snapshot
 2932                                                .char_classifier_at(selection.start)
 2933                                                .is_word(c)
 2934                                    },
 2935                                );
 2936
 2937                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2938                                && bracket_pair.start.len() == 1
 2939                            {
 2940                                let target = bracket_pair.start.chars().next().unwrap();
 2941                                let current_line_count = snapshot
 2942                                    .reversed_chars_at(selection.start)
 2943                                    .take_while(|&c| c != '\n')
 2944                                    .filter(|&c| c == target)
 2945                                    .count();
 2946                                current_line_count % 2 == 1
 2947                            } else {
 2948                                false
 2949                            };
 2950
 2951                            if autoclose
 2952                                && bracket_pair.close
 2953                                && following_text_allows_autoclose
 2954                                && preceding_text_allows_autoclose
 2955                                && !is_closing_quote
 2956                            {
 2957                                let anchor = snapshot.anchor_before(selection.end);
 2958                                new_selections.push((selection.map(|_| anchor), text.len()));
 2959                                new_autoclose_regions.push((
 2960                                    anchor,
 2961                                    text.len(),
 2962                                    selection.id,
 2963                                    bracket_pair.clone(),
 2964                                ));
 2965                                edits.push((
 2966                                    selection.range(),
 2967                                    format!("{}{}", text, bracket_pair.end).into(),
 2968                                ));
 2969                                bracket_inserted = true;
 2970                                continue;
 2971                            }
 2972                        }
 2973
 2974                        if let Some(region) = autoclose_region {
 2975                            // If the selection is followed by an auto-inserted closing bracket,
 2976                            // then don't insert that closing bracket again; just move the selection
 2977                            // past the closing bracket.
 2978                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2979                                && text.as_ref() == region.pair.end.as_str();
 2980                            if should_skip {
 2981                                let anchor = snapshot.anchor_after(selection.end);
 2982                                new_selections
 2983                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2984                                continue;
 2985                            }
 2986                        }
 2987
 2988                        let always_treat_brackets_as_autoclosed = snapshot
 2989                            .language_settings_at(selection.start, cx)
 2990                            .always_treat_brackets_as_autoclosed;
 2991                        if always_treat_brackets_as_autoclosed
 2992                            && is_bracket_pair_end
 2993                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2994                        {
 2995                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2996                            // and the inserted text is a closing bracket and the selection is followed
 2997                            // by the closing bracket then move the selection past the closing bracket.
 2998                            let anchor = snapshot.anchor_after(selection.end);
 2999                            new_selections.push((selection.map(|_| anchor), text.len()));
 3000                            continue;
 3001                        }
 3002                    }
 3003                    // If an opening bracket is 1 character long and is typed while
 3004                    // text is selected, then surround that text with the bracket pair.
 3005                    else if auto_surround
 3006                        && bracket_pair.surround
 3007                        && is_bracket_pair_start
 3008                        && bracket_pair.start.chars().count() == 1
 3009                    {
 3010                        edits.push((selection.start..selection.start, text.clone()));
 3011                        edits.push((
 3012                            selection.end..selection.end,
 3013                            bracket_pair.end.as_str().into(),
 3014                        ));
 3015                        bracket_inserted = true;
 3016                        new_selections.push((
 3017                            Selection {
 3018                                id: selection.id,
 3019                                start: snapshot.anchor_after(selection.start),
 3020                                end: snapshot.anchor_before(selection.end),
 3021                                reversed: selection.reversed,
 3022                                goal: selection.goal,
 3023                            },
 3024                            0,
 3025                        ));
 3026                        continue;
 3027                    }
 3028                }
 3029            }
 3030
 3031            if self.auto_replace_emoji_shortcode
 3032                && selection.is_empty()
 3033                && text.as_ref().ends_with(':')
 3034            {
 3035                if let Some(possible_emoji_short_code) =
 3036                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3037                {
 3038                    if !possible_emoji_short_code.is_empty() {
 3039                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3040                            let emoji_shortcode_start = Point::new(
 3041                                selection.start.row,
 3042                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3043                            );
 3044
 3045                            // Remove shortcode from buffer
 3046                            edits.push((
 3047                                emoji_shortcode_start..selection.start,
 3048                                "".to_string().into(),
 3049                            ));
 3050                            new_selections.push((
 3051                                Selection {
 3052                                    id: selection.id,
 3053                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3054                                    end: snapshot.anchor_before(selection.start),
 3055                                    reversed: selection.reversed,
 3056                                    goal: selection.goal,
 3057                                },
 3058                                0,
 3059                            ));
 3060
 3061                            // Insert emoji
 3062                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3063                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3064                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3065
 3066                            continue;
 3067                        }
 3068                    }
 3069                }
 3070            }
 3071
 3072            // If not handling any auto-close operation, then just replace the selected
 3073            // text with the given input and move the selection to the end of the
 3074            // newly inserted text.
 3075            let anchor = snapshot.anchor_after(selection.end);
 3076            if !self.linked_edit_ranges.is_empty() {
 3077                let start_anchor = snapshot.anchor_before(selection.start);
 3078
 3079                let is_word_char = text.chars().next().map_or(true, |char| {
 3080                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3081                    classifier.is_word(char)
 3082                });
 3083
 3084                if is_word_char {
 3085                    if let Some(ranges) = self
 3086                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3087                    {
 3088                        for (buffer, edits) in ranges {
 3089                            linked_edits
 3090                                .entry(buffer.clone())
 3091                                .or_default()
 3092                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3093                        }
 3094                    }
 3095                }
 3096            }
 3097
 3098            new_selections.push((selection.map(|_| anchor), 0));
 3099            edits.push((selection.start..selection.end, text.clone()));
 3100        }
 3101
 3102        drop(snapshot);
 3103
 3104        self.transact(window, cx, |this, window, cx| {
 3105            let initial_buffer_versions =
 3106                jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
 3107
 3108            this.buffer.update(cx, |buffer, cx| {
 3109                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3110            });
 3111            for (buffer, edits) in linked_edits {
 3112                buffer.update(cx, |buffer, cx| {
 3113                    let snapshot = buffer.snapshot();
 3114                    let edits = edits
 3115                        .into_iter()
 3116                        .map(|(range, text)| {
 3117                            use text::ToPoint as TP;
 3118                            let end_point = TP::to_point(&range.end, &snapshot);
 3119                            let start_point = TP::to_point(&range.start, &snapshot);
 3120                            (start_point..end_point, text)
 3121                        })
 3122                        .sorted_by_key(|(range, _)| range.start)
 3123                        .collect::<Vec<_>>();
 3124                    buffer.edit(edits, None, cx);
 3125                })
 3126            }
 3127            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3128            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3129            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3130            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3131                .zip(new_selection_deltas)
 3132                .map(|(selection, delta)| Selection {
 3133                    id: selection.id,
 3134                    start: selection.start + delta,
 3135                    end: selection.end + delta,
 3136                    reversed: selection.reversed,
 3137                    goal: SelectionGoal::None,
 3138                })
 3139                .collect::<Vec<_>>();
 3140
 3141            let mut i = 0;
 3142            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3143                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3144                let start = map.buffer_snapshot.anchor_before(position);
 3145                let end = map.buffer_snapshot.anchor_after(position);
 3146                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3147                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3148                        Ordering::Less => i += 1,
 3149                        Ordering::Greater => break,
 3150                        Ordering::Equal => {
 3151                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3152                                Ordering::Less => i += 1,
 3153                                Ordering::Equal => break,
 3154                                Ordering::Greater => break,
 3155                            }
 3156                        }
 3157                    }
 3158                }
 3159                this.autoclose_regions.insert(
 3160                    i,
 3161                    AutocloseRegion {
 3162                        selection_id,
 3163                        range: start..end,
 3164                        pair,
 3165                    },
 3166                );
 3167            }
 3168
 3169            let had_active_inline_completion = this.has_active_inline_completion();
 3170            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3171                s.select(new_selections)
 3172            });
 3173
 3174            if !bracket_inserted {
 3175                if let Some(on_type_format_task) =
 3176                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3177                {
 3178                    on_type_format_task.detach_and_log_err(cx);
 3179                }
 3180            }
 3181
 3182            let editor_settings = EditorSettings::get_global(cx);
 3183            if bracket_inserted
 3184                && (editor_settings.auto_signature_help
 3185                    || editor_settings.show_signature_help_after_edits)
 3186            {
 3187                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3188            }
 3189
 3190            let trigger_in_words =
 3191                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3192            if this.hard_wrap.is_some() {
 3193                let latest: Range<Point> = this.selections.newest(cx).range();
 3194                if latest.is_empty()
 3195                    && this
 3196                        .buffer()
 3197                        .read(cx)
 3198                        .snapshot(cx)
 3199                        .line_len(MultiBufferRow(latest.start.row))
 3200                        == latest.start.column
 3201                {
 3202                    this.rewrap_impl(true, cx)
 3203                }
 3204            }
 3205            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3206            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3207            this.refresh_inline_completion(true, false, window, cx);
 3208            jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
 3209        });
 3210    }
 3211
 3212    fn find_possible_emoji_shortcode_at_position(
 3213        snapshot: &MultiBufferSnapshot,
 3214        position: Point,
 3215    ) -> Option<String> {
 3216        let mut chars = Vec::new();
 3217        let mut found_colon = false;
 3218        for char in snapshot.reversed_chars_at(position).take(100) {
 3219            // Found a possible emoji shortcode in the middle of the buffer
 3220            if found_colon {
 3221                if char.is_whitespace() {
 3222                    chars.reverse();
 3223                    return Some(chars.iter().collect());
 3224                }
 3225                // If the previous character is not a whitespace, we are in the middle of a word
 3226                // and we only want to complete the shortcode if the word is made up of other emojis
 3227                let mut containing_word = String::new();
 3228                for ch in snapshot
 3229                    .reversed_chars_at(position)
 3230                    .skip(chars.len() + 1)
 3231                    .take(100)
 3232                {
 3233                    if ch.is_whitespace() {
 3234                        break;
 3235                    }
 3236                    containing_word.push(ch);
 3237                }
 3238                let containing_word = containing_word.chars().rev().collect::<String>();
 3239                if util::word_consists_of_emojis(containing_word.as_str()) {
 3240                    chars.reverse();
 3241                    return Some(chars.iter().collect());
 3242                }
 3243            }
 3244
 3245            if char.is_whitespace() || !char.is_ascii() {
 3246                return None;
 3247            }
 3248            if char == ':' {
 3249                found_colon = true;
 3250            } else {
 3251                chars.push(char);
 3252            }
 3253        }
 3254        // Found a possible emoji shortcode at the beginning of the buffer
 3255        chars.reverse();
 3256        Some(chars.iter().collect())
 3257    }
 3258
 3259    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3260        self.transact(window, cx, |this, window, cx| {
 3261            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3262                let selections = this.selections.all::<usize>(cx);
 3263                let multi_buffer = this.buffer.read(cx);
 3264                let buffer = multi_buffer.snapshot(cx);
 3265                selections
 3266                    .iter()
 3267                    .map(|selection| {
 3268                        let start_point = selection.start.to_point(&buffer);
 3269                        let mut indent =
 3270                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3271                        indent.len = cmp::min(indent.len, start_point.column);
 3272                        let start = selection.start;
 3273                        let end = selection.end;
 3274                        let selection_is_empty = start == end;
 3275                        let language_scope = buffer.language_scope_at(start);
 3276                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3277                            &language_scope
 3278                        {
 3279                            let insert_extra_newline =
 3280                                insert_extra_newline_brackets(&buffer, start..end, language)
 3281                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3282
 3283                            // Comment extension on newline is allowed only for cursor selections
 3284                            let comment_delimiter = maybe!({
 3285                                if !selection_is_empty {
 3286                                    return None;
 3287                                }
 3288
 3289                                if !multi_buffer.language_settings(cx).extend_comment_on_newline {
 3290                                    return None;
 3291                                }
 3292
 3293                                let delimiters = language.line_comment_prefixes();
 3294                                let max_len_of_delimiter =
 3295                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3296                                let (snapshot, range) =
 3297                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3298
 3299                                let mut index_of_first_non_whitespace = 0;
 3300                                let comment_candidate = snapshot
 3301                                    .chars_for_range(range)
 3302                                    .skip_while(|c| {
 3303                                        let should_skip = c.is_whitespace();
 3304                                        if should_skip {
 3305                                            index_of_first_non_whitespace += 1;
 3306                                        }
 3307                                        should_skip
 3308                                    })
 3309                                    .take(max_len_of_delimiter)
 3310                                    .collect::<String>();
 3311                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3312                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3313                                })?;
 3314                                let cursor_is_placed_after_comment_marker =
 3315                                    index_of_first_non_whitespace + comment_prefix.len()
 3316                                        <= start_point.column as usize;
 3317                                if cursor_is_placed_after_comment_marker {
 3318                                    Some(comment_prefix.clone())
 3319                                } else {
 3320                                    None
 3321                                }
 3322                            });
 3323                            (comment_delimiter, insert_extra_newline)
 3324                        } else {
 3325                            (None, false)
 3326                        };
 3327
 3328                        let capacity_for_delimiter = comment_delimiter
 3329                            .as_deref()
 3330                            .map(str::len)
 3331                            .unwrap_or_default();
 3332                        let mut new_text =
 3333                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3334                        new_text.push('\n');
 3335                        new_text.extend(indent.chars());
 3336                        if let Some(delimiter) = &comment_delimiter {
 3337                            new_text.push_str(delimiter);
 3338                        }
 3339                        if insert_extra_newline {
 3340                            new_text = new_text.repeat(2);
 3341                        }
 3342
 3343                        let anchor = buffer.anchor_after(end);
 3344                        let new_selection = selection.map(|_| anchor);
 3345                        (
 3346                            (start..end, new_text),
 3347                            (insert_extra_newline, new_selection),
 3348                        )
 3349                    })
 3350                    .unzip()
 3351            };
 3352
 3353            this.edit_with_autoindent(edits, cx);
 3354            let buffer = this.buffer.read(cx).snapshot(cx);
 3355            let new_selections = selection_fixup_info
 3356                .into_iter()
 3357                .map(|(extra_newline_inserted, new_selection)| {
 3358                    let mut cursor = new_selection.end.to_point(&buffer);
 3359                    if extra_newline_inserted {
 3360                        cursor.row -= 1;
 3361                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3362                    }
 3363                    new_selection.map(|_| cursor)
 3364                })
 3365                .collect();
 3366
 3367            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3368                s.select(new_selections)
 3369            });
 3370            this.refresh_inline_completion(true, false, window, cx);
 3371        });
 3372    }
 3373
 3374    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3375        let buffer = self.buffer.read(cx);
 3376        let snapshot = buffer.snapshot(cx);
 3377
 3378        let mut edits = Vec::new();
 3379        let mut rows = Vec::new();
 3380
 3381        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3382            let cursor = selection.head();
 3383            let row = cursor.row;
 3384
 3385            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3386
 3387            let newline = "\n".to_string();
 3388            edits.push((start_of_line..start_of_line, newline));
 3389
 3390            rows.push(row + rows_inserted as u32);
 3391        }
 3392
 3393        self.transact(window, cx, |editor, window, cx| {
 3394            editor.edit(edits, cx);
 3395
 3396            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3397                let mut index = 0;
 3398                s.move_cursors_with(|map, _, _| {
 3399                    let row = rows[index];
 3400                    index += 1;
 3401
 3402                    let point = Point::new(row, 0);
 3403                    let boundary = map.next_line_boundary(point).1;
 3404                    let clipped = map.clip_point(boundary, Bias::Left);
 3405
 3406                    (clipped, SelectionGoal::None)
 3407                });
 3408            });
 3409
 3410            let mut indent_edits = Vec::new();
 3411            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3412            for row in rows {
 3413                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3414                for (row, indent) in indents {
 3415                    if indent.len == 0 {
 3416                        continue;
 3417                    }
 3418
 3419                    let text = match indent.kind {
 3420                        IndentKind::Space => " ".repeat(indent.len as usize),
 3421                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3422                    };
 3423                    let point = Point::new(row.0, 0);
 3424                    indent_edits.push((point..point, text));
 3425                }
 3426            }
 3427            editor.edit(indent_edits, cx);
 3428        });
 3429    }
 3430
 3431    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3432        let buffer = self.buffer.read(cx);
 3433        let snapshot = buffer.snapshot(cx);
 3434
 3435        let mut edits = Vec::new();
 3436        let mut rows = Vec::new();
 3437        let mut rows_inserted = 0;
 3438
 3439        for selection in self.selections.all_adjusted(cx) {
 3440            let cursor = selection.head();
 3441            let row = cursor.row;
 3442
 3443            let point = Point::new(row + 1, 0);
 3444            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3445
 3446            let newline = "\n".to_string();
 3447            edits.push((start_of_line..start_of_line, newline));
 3448
 3449            rows_inserted += 1;
 3450            rows.push(row + rows_inserted);
 3451        }
 3452
 3453        self.transact(window, cx, |editor, window, cx| {
 3454            editor.edit(edits, cx);
 3455
 3456            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3457                let mut index = 0;
 3458                s.move_cursors_with(|map, _, _| {
 3459                    let row = rows[index];
 3460                    index += 1;
 3461
 3462                    let point = Point::new(row, 0);
 3463                    let boundary = map.next_line_boundary(point).1;
 3464                    let clipped = map.clip_point(boundary, Bias::Left);
 3465
 3466                    (clipped, SelectionGoal::None)
 3467                });
 3468            });
 3469
 3470            let mut indent_edits = Vec::new();
 3471            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3472            for row in rows {
 3473                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3474                for (row, indent) in indents {
 3475                    if indent.len == 0 {
 3476                        continue;
 3477                    }
 3478
 3479                    let text = match indent.kind {
 3480                        IndentKind::Space => " ".repeat(indent.len as usize),
 3481                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3482                    };
 3483                    let point = Point::new(row.0, 0);
 3484                    indent_edits.push((point..point, text));
 3485                }
 3486            }
 3487            editor.edit(indent_edits, cx);
 3488        });
 3489    }
 3490
 3491    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3492        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3493            original_indent_columns: Vec::new(),
 3494        });
 3495        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3496    }
 3497
 3498    fn insert_with_autoindent_mode(
 3499        &mut self,
 3500        text: &str,
 3501        autoindent_mode: Option<AutoindentMode>,
 3502        window: &mut Window,
 3503        cx: &mut Context<Self>,
 3504    ) {
 3505        if self.read_only(cx) {
 3506            return;
 3507        }
 3508
 3509        let text: Arc<str> = text.into();
 3510        self.transact(window, cx, |this, window, cx| {
 3511            let old_selections = this.selections.all_adjusted(cx);
 3512            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3513                let anchors = {
 3514                    let snapshot = buffer.read(cx);
 3515                    old_selections
 3516                        .iter()
 3517                        .map(|s| {
 3518                            let anchor = snapshot.anchor_after(s.head());
 3519                            s.map(|_| anchor)
 3520                        })
 3521                        .collect::<Vec<_>>()
 3522                };
 3523                buffer.edit(
 3524                    old_selections
 3525                        .iter()
 3526                        .map(|s| (s.start..s.end, text.clone())),
 3527                    autoindent_mode,
 3528                    cx,
 3529                );
 3530                anchors
 3531            });
 3532
 3533            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3534                s.select_anchors(selection_anchors);
 3535            });
 3536
 3537            cx.notify();
 3538        });
 3539    }
 3540
 3541    fn trigger_completion_on_input(
 3542        &mut self,
 3543        text: &str,
 3544        trigger_in_words: bool,
 3545        window: &mut Window,
 3546        cx: &mut Context<Self>,
 3547    ) {
 3548        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3549            self.show_completions(
 3550                &ShowCompletions {
 3551                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3552                },
 3553                window,
 3554                cx,
 3555            );
 3556        } else {
 3557            self.hide_context_menu(window, cx);
 3558        }
 3559    }
 3560
 3561    fn is_completion_trigger(
 3562        &self,
 3563        text: &str,
 3564        trigger_in_words: bool,
 3565        cx: &mut Context<Self>,
 3566    ) -> bool {
 3567        let position = self.selections.newest_anchor().head();
 3568        let multibuffer = self.buffer.read(cx);
 3569        let Some(buffer) = position
 3570            .buffer_id
 3571            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3572        else {
 3573            return false;
 3574        };
 3575
 3576        if let Some(completion_provider) = &self.completion_provider {
 3577            completion_provider.is_completion_trigger(
 3578                &buffer,
 3579                position.text_anchor,
 3580                text,
 3581                trigger_in_words,
 3582                cx,
 3583            )
 3584        } else {
 3585            false
 3586        }
 3587    }
 3588
 3589    /// If any empty selections is touching the start of its innermost containing autoclose
 3590    /// region, expand it to select the brackets.
 3591    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3592        let selections = self.selections.all::<usize>(cx);
 3593        let buffer = self.buffer.read(cx).read(cx);
 3594        let new_selections = self
 3595            .selections_with_autoclose_regions(selections, &buffer)
 3596            .map(|(mut selection, region)| {
 3597                if !selection.is_empty() {
 3598                    return selection;
 3599                }
 3600
 3601                if let Some(region) = region {
 3602                    let mut range = region.range.to_offset(&buffer);
 3603                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3604                        range.start -= region.pair.start.len();
 3605                        if buffer.contains_str_at(range.start, &region.pair.start)
 3606                            && buffer.contains_str_at(range.end, &region.pair.end)
 3607                        {
 3608                            range.end += region.pair.end.len();
 3609                            selection.start = range.start;
 3610                            selection.end = range.end;
 3611
 3612                            return selection;
 3613                        }
 3614                    }
 3615                }
 3616
 3617                let always_treat_brackets_as_autoclosed = buffer
 3618                    .language_settings_at(selection.start, cx)
 3619                    .always_treat_brackets_as_autoclosed;
 3620
 3621                if !always_treat_brackets_as_autoclosed {
 3622                    return selection;
 3623                }
 3624
 3625                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3626                    for (pair, enabled) in scope.brackets() {
 3627                        if !enabled || !pair.close {
 3628                            continue;
 3629                        }
 3630
 3631                        if buffer.contains_str_at(selection.start, &pair.end) {
 3632                            let pair_start_len = pair.start.len();
 3633                            if buffer.contains_str_at(
 3634                                selection.start.saturating_sub(pair_start_len),
 3635                                &pair.start,
 3636                            ) {
 3637                                selection.start -= pair_start_len;
 3638                                selection.end += pair.end.len();
 3639
 3640                                return selection;
 3641                            }
 3642                        }
 3643                    }
 3644                }
 3645
 3646                selection
 3647            })
 3648            .collect();
 3649
 3650        drop(buffer);
 3651        self.change_selections(None, window, cx, |selections| {
 3652            selections.select(new_selections)
 3653        });
 3654    }
 3655
 3656    /// Iterate the given selections, and for each one, find the smallest surrounding
 3657    /// autoclose region. This uses the ordering of the selections and the autoclose
 3658    /// regions to avoid repeated comparisons.
 3659    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3660        &'a self,
 3661        selections: impl IntoIterator<Item = Selection<D>>,
 3662        buffer: &'a MultiBufferSnapshot,
 3663    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3664        let mut i = 0;
 3665        let mut regions = self.autoclose_regions.as_slice();
 3666        selections.into_iter().map(move |selection| {
 3667            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3668
 3669            let mut enclosing = None;
 3670            while let Some(pair_state) = regions.get(i) {
 3671                if pair_state.range.end.to_offset(buffer) < range.start {
 3672                    regions = &regions[i + 1..];
 3673                    i = 0;
 3674                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3675                    break;
 3676                } else {
 3677                    if pair_state.selection_id == selection.id {
 3678                        enclosing = Some(pair_state);
 3679                    }
 3680                    i += 1;
 3681                }
 3682            }
 3683
 3684            (selection, enclosing)
 3685        })
 3686    }
 3687
 3688    /// Remove any autoclose regions that no longer contain their selection.
 3689    fn invalidate_autoclose_regions(
 3690        &mut self,
 3691        mut selections: &[Selection<Anchor>],
 3692        buffer: &MultiBufferSnapshot,
 3693    ) {
 3694        self.autoclose_regions.retain(|state| {
 3695            let mut i = 0;
 3696            while let Some(selection) = selections.get(i) {
 3697                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3698                    selections = &selections[1..];
 3699                    continue;
 3700                }
 3701                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3702                    break;
 3703                }
 3704                if selection.id == state.selection_id {
 3705                    return true;
 3706                } else {
 3707                    i += 1;
 3708                }
 3709            }
 3710            false
 3711        });
 3712    }
 3713
 3714    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3715        let offset = position.to_offset(buffer);
 3716        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3717        if offset > word_range.start && kind == Some(CharKind::Word) {
 3718            Some(
 3719                buffer
 3720                    .text_for_range(word_range.start..offset)
 3721                    .collect::<String>(),
 3722            )
 3723        } else {
 3724            None
 3725        }
 3726    }
 3727
 3728    pub fn toggle_inlay_hints(
 3729        &mut self,
 3730        _: &ToggleInlayHints,
 3731        _: &mut Window,
 3732        cx: &mut Context<Self>,
 3733    ) {
 3734        self.refresh_inlay_hints(
 3735            InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
 3736            cx,
 3737        );
 3738    }
 3739
 3740    pub fn inlay_hints_enabled(&self) -> bool {
 3741        self.inlay_hint_cache.enabled
 3742    }
 3743
 3744    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3745        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3746            return;
 3747        }
 3748
 3749        let reason_description = reason.description();
 3750        let ignore_debounce = matches!(
 3751            reason,
 3752            InlayHintRefreshReason::SettingsChange(_)
 3753                | InlayHintRefreshReason::Toggle(_)
 3754                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3755                | InlayHintRefreshReason::ModifiersChanged(_)
 3756        );
 3757        let (invalidate_cache, required_languages) = match reason {
 3758            InlayHintRefreshReason::ModifiersChanged(enabled) => {
 3759                match self.inlay_hint_cache.modifiers_override(enabled) {
 3760                    Some(enabled) => {
 3761                        if enabled {
 3762                            (InvalidationStrategy::RefreshRequested, None)
 3763                        } else {
 3764                            self.splice_inlays(
 3765                                &self
 3766                                    .visible_inlay_hints(cx)
 3767                                    .iter()
 3768                                    .map(|inlay| inlay.id)
 3769                                    .collect::<Vec<InlayId>>(),
 3770                                Vec::new(),
 3771                                cx,
 3772                            );
 3773                            return;
 3774                        }
 3775                    }
 3776                    None => return,
 3777                }
 3778            }
 3779            InlayHintRefreshReason::Toggle(enabled) => {
 3780                if self.inlay_hint_cache.toggle(enabled) {
 3781                    if enabled {
 3782                        (InvalidationStrategy::RefreshRequested, None)
 3783                    } else {
 3784                        self.splice_inlays(
 3785                            &self
 3786                                .visible_inlay_hints(cx)
 3787                                .iter()
 3788                                .map(|inlay| inlay.id)
 3789                                .collect::<Vec<InlayId>>(),
 3790                            Vec::new(),
 3791                            cx,
 3792                        );
 3793                        return;
 3794                    }
 3795                } else {
 3796                    return;
 3797                }
 3798            }
 3799            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3800                match self.inlay_hint_cache.update_settings(
 3801                    &self.buffer,
 3802                    new_settings,
 3803                    self.visible_inlay_hints(cx),
 3804                    cx,
 3805                ) {
 3806                    ControlFlow::Break(Some(InlaySplice {
 3807                        to_remove,
 3808                        to_insert,
 3809                    })) => {
 3810                        self.splice_inlays(&to_remove, to_insert, cx);
 3811                        return;
 3812                    }
 3813                    ControlFlow::Break(None) => return,
 3814                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3815                }
 3816            }
 3817            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3818                if let Some(InlaySplice {
 3819                    to_remove,
 3820                    to_insert,
 3821                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3822                {
 3823                    self.splice_inlays(&to_remove, to_insert, cx);
 3824                }
 3825                return;
 3826            }
 3827            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3828            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3829                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3830            }
 3831            InlayHintRefreshReason::RefreshRequested => {
 3832                (InvalidationStrategy::RefreshRequested, None)
 3833            }
 3834        };
 3835
 3836        if let Some(InlaySplice {
 3837            to_remove,
 3838            to_insert,
 3839        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3840            reason_description,
 3841            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3842            invalidate_cache,
 3843            ignore_debounce,
 3844            cx,
 3845        ) {
 3846            self.splice_inlays(&to_remove, to_insert, cx);
 3847        }
 3848    }
 3849
 3850    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3851        self.display_map
 3852            .read(cx)
 3853            .current_inlays()
 3854            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3855            .cloned()
 3856            .collect()
 3857    }
 3858
 3859    pub fn excerpts_for_inlay_hints_query(
 3860        &self,
 3861        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3862        cx: &mut Context<Editor>,
 3863    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3864        let Some(project) = self.project.as_ref() else {
 3865            return HashMap::default();
 3866        };
 3867        let project = project.read(cx);
 3868        let multi_buffer = self.buffer().read(cx);
 3869        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3870        let multi_buffer_visible_start = self
 3871            .scroll_manager
 3872            .anchor()
 3873            .anchor
 3874            .to_point(&multi_buffer_snapshot);
 3875        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3876            multi_buffer_visible_start
 3877                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3878            Bias::Left,
 3879        );
 3880        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3881        multi_buffer_snapshot
 3882            .range_to_buffer_ranges(multi_buffer_visible_range)
 3883            .into_iter()
 3884            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3885            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3886                let buffer_file = project::File::from_dyn(buffer.file())?;
 3887                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3888                let worktree_entry = buffer_worktree
 3889                    .read(cx)
 3890                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3891                if worktree_entry.is_ignored {
 3892                    return None;
 3893                }
 3894
 3895                let language = buffer.language()?;
 3896                if let Some(restrict_to_languages) = restrict_to_languages {
 3897                    if !restrict_to_languages.contains(language) {
 3898                        return None;
 3899                    }
 3900                }
 3901                Some((
 3902                    excerpt_id,
 3903                    (
 3904                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3905                        buffer.version().clone(),
 3906                        excerpt_visible_range,
 3907                    ),
 3908                ))
 3909            })
 3910            .collect()
 3911    }
 3912
 3913    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3914        TextLayoutDetails {
 3915            text_system: window.text_system().clone(),
 3916            editor_style: self.style.clone().unwrap(),
 3917            rem_size: window.rem_size(),
 3918            scroll_anchor: self.scroll_manager.anchor(),
 3919            visible_rows: self.visible_line_count(),
 3920            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3921        }
 3922    }
 3923
 3924    pub fn splice_inlays(
 3925        &self,
 3926        to_remove: &[InlayId],
 3927        to_insert: Vec<Inlay>,
 3928        cx: &mut Context<Self>,
 3929    ) {
 3930        self.display_map.update(cx, |display_map, cx| {
 3931            display_map.splice_inlays(to_remove, to_insert, cx)
 3932        });
 3933        cx.notify();
 3934    }
 3935
 3936    fn trigger_on_type_formatting(
 3937        &self,
 3938        input: String,
 3939        window: &mut Window,
 3940        cx: &mut Context<Self>,
 3941    ) -> Option<Task<Result<()>>> {
 3942        if input.len() != 1 {
 3943            return None;
 3944        }
 3945
 3946        let project = self.project.as_ref()?;
 3947        let position = self.selections.newest_anchor().head();
 3948        let (buffer, buffer_position) = self
 3949            .buffer
 3950            .read(cx)
 3951            .text_anchor_for_position(position, cx)?;
 3952
 3953        let settings = language_settings::language_settings(
 3954            buffer
 3955                .read(cx)
 3956                .language_at(buffer_position)
 3957                .map(|l| l.name()),
 3958            buffer.read(cx).file(),
 3959            cx,
 3960        );
 3961        if !settings.use_on_type_format {
 3962            return None;
 3963        }
 3964
 3965        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3966        // hence we do LSP request & edit on host side only — add formats to host's history.
 3967        let push_to_lsp_host_history = true;
 3968        // If this is not the host, append its history with new edits.
 3969        let push_to_client_history = project.read(cx).is_via_collab();
 3970
 3971        let on_type_formatting = project.update(cx, |project, cx| {
 3972            project.on_type_format(
 3973                buffer.clone(),
 3974                buffer_position,
 3975                input,
 3976                push_to_lsp_host_history,
 3977                cx,
 3978            )
 3979        });
 3980        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3981            if let Some(transaction) = on_type_formatting.await? {
 3982                if push_to_client_history {
 3983                    buffer
 3984                        .update(&mut cx, |buffer, _| {
 3985                            buffer.push_transaction(transaction, Instant::now());
 3986                        })
 3987                        .ok();
 3988                }
 3989                editor.update(&mut cx, |editor, cx| {
 3990                    editor.refresh_document_highlights(cx);
 3991                })?;
 3992            }
 3993            Ok(())
 3994        }))
 3995    }
 3996
 3997    pub fn show_word_completions(
 3998        &mut self,
 3999        _: &ShowWordCompletions,
 4000        window: &mut Window,
 4001        cx: &mut Context<Self>,
 4002    ) {
 4003        self.open_completions_menu(true, None, window, cx);
 4004    }
 4005
 4006    pub fn show_completions(
 4007        &mut self,
 4008        options: &ShowCompletions,
 4009        window: &mut Window,
 4010        cx: &mut Context<Self>,
 4011    ) {
 4012        self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
 4013    }
 4014
 4015    fn open_completions_menu(
 4016        &mut self,
 4017        ignore_completion_provider: bool,
 4018        trigger: Option<&str>,
 4019        window: &mut Window,
 4020        cx: &mut Context<Self>,
 4021    ) {
 4022        if self.pending_rename.is_some() {
 4023            return;
 4024        }
 4025        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 4026            return;
 4027        }
 4028
 4029        let position = self.selections.newest_anchor().head();
 4030        if position.diff_base_anchor.is_some() {
 4031            return;
 4032        }
 4033        let (buffer, buffer_position) =
 4034            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4035                output
 4036            } else {
 4037                return;
 4038            };
 4039        let buffer_snapshot = buffer.read(cx).snapshot();
 4040        let show_completion_documentation = buffer_snapshot
 4041            .settings_at(buffer_position, cx)
 4042            .show_completion_documentation;
 4043
 4044        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4045
 4046        let trigger_kind = match trigger {
 4047            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4048                CompletionTriggerKind::TRIGGER_CHARACTER
 4049            }
 4050            _ => CompletionTriggerKind::INVOKED,
 4051        };
 4052        let completion_context = CompletionContext {
 4053            trigger_character: trigger.and_then(|trigger| {
 4054                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4055                    Some(String::from(trigger))
 4056                } else {
 4057                    None
 4058                }
 4059            }),
 4060            trigger_kind,
 4061        };
 4062
 4063        let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
 4064        let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
 4065            let word_to_exclude = buffer_snapshot
 4066                .text_for_range(old_range.clone())
 4067                .collect::<String>();
 4068            (
 4069                buffer_snapshot.anchor_before(old_range.start)
 4070                    ..buffer_snapshot.anchor_after(old_range.end),
 4071                Some(word_to_exclude),
 4072            )
 4073        } else {
 4074            (buffer_position..buffer_position, None)
 4075        };
 4076
 4077        let completion_settings = language_settings(
 4078            buffer_snapshot
 4079                .language_at(buffer_position)
 4080                .map(|language| language.name()),
 4081            buffer_snapshot.file(),
 4082            cx,
 4083        )
 4084        .completions;
 4085
 4086        // The document can be large, so stay in reasonable bounds when searching for words,
 4087        // otherwise completion pop-up might be slow to appear.
 4088        const WORD_LOOKUP_ROWS: u32 = 5_000;
 4089        let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
 4090        let min_word_search = buffer_snapshot.clip_point(
 4091            Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
 4092            Bias::Left,
 4093        );
 4094        let max_word_search = buffer_snapshot.clip_point(
 4095            Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
 4096            Bias::Right,
 4097        );
 4098        let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
 4099            ..buffer_snapshot.point_to_offset(max_word_search);
 4100
 4101        let provider = self
 4102            .completion_provider
 4103            .as_ref()
 4104            .filter(|_| !ignore_completion_provider);
 4105        let skip_digits = query
 4106            .as_ref()
 4107            .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
 4108
 4109        let (mut words, provided_completions) = match provider {
 4110            Some(provider) => {
 4111                let completions =
 4112                    provider.completions(&buffer, buffer_position, completion_context, window, cx);
 4113
 4114                let words = match completion_settings.words {
 4115                    WordsCompletionMode::Disabled => Task::ready(HashMap::default()),
 4116                    WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
 4117                        .background_spawn(async move {
 4118                            buffer_snapshot.words_in_range(WordsQuery {
 4119                                fuzzy_contents: None,
 4120                                range: word_search_range,
 4121                                skip_digits,
 4122                            })
 4123                        }),
 4124                };
 4125
 4126                (words, completions)
 4127            }
 4128            None => (
 4129                cx.background_spawn(async move {
 4130                    buffer_snapshot.words_in_range(WordsQuery {
 4131                        fuzzy_contents: None,
 4132                        range: word_search_range,
 4133                        skip_digits,
 4134                    })
 4135                }),
 4136                Task::ready(Ok(None)),
 4137            ),
 4138        };
 4139
 4140        let sort_completions = provider
 4141            .as_ref()
 4142            .map_or(true, |provider| provider.sort_completions());
 4143
 4144        let id = post_inc(&mut self.next_completion_id);
 4145        let task = cx.spawn_in(window, |editor, mut cx| {
 4146            async move {
 4147                editor.update(&mut cx, |this, _| {
 4148                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4149                })?;
 4150
 4151                let mut completions = Vec::new();
 4152                if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
 4153                    completions.extend(provided_completions);
 4154                    if completion_settings.words == WordsCompletionMode::Fallback {
 4155                        words = Task::ready(HashMap::default());
 4156                    }
 4157                }
 4158
 4159                let mut words = words.await;
 4160                if let Some(word_to_exclude) = &word_to_exclude {
 4161                    words.remove(word_to_exclude);
 4162                }
 4163                for lsp_completion in &completions {
 4164                    words.remove(&lsp_completion.new_text);
 4165                }
 4166                completions.extend(words.into_iter().map(|(word, word_range)| Completion {
 4167                    old_range: old_range.clone(),
 4168                    new_text: word.clone(),
 4169                    label: CodeLabel::plain(word, None),
 4170                    documentation: None,
 4171                    source: CompletionSource::BufferWord {
 4172                        word_range,
 4173                        resolved: false,
 4174                    },
 4175                    confirm: None,
 4176                }));
 4177
 4178                let menu = if completions.is_empty() {
 4179                    None
 4180                } else {
 4181                    let mut menu = CompletionsMenu::new(
 4182                        id,
 4183                        sort_completions,
 4184                        show_completion_documentation,
 4185                        position,
 4186                        buffer.clone(),
 4187                        completions.into(),
 4188                    );
 4189
 4190                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4191                        .await;
 4192
 4193                    menu.visible().then_some(menu)
 4194                };
 4195
 4196                editor.update_in(&mut cx, |editor, window, cx| {
 4197                    match editor.context_menu.borrow().as_ref() {
 4198                        None => {}
 4199                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4200                            if prev_menu.id > id {
 4201                                return;
 4202                            }
 4203                        }
 4204                        _ => return,
 4205                    }
 4206
 4207                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4208                        let mut menu = menu.unwrap();
 4209                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4210
 4211                        *editor.context_menu.borrow_mut() =
 4212                            Some(CodeContextMenu::Completions(menu));
 4213
 4214                        if editor.show_edit_predictions_in_menu() {
 4215                            editor.update_visible_inline_completion(window, cx);
 4216                        } else {
 4217                            editor.discard_inline_completion(false, cx);
 4218                        }
 4219
 4220                        cx.notify();
 4221                    } else if editor.completion_tasks.len() <= 1 {
 4222                        // If there are no more completion tasks and the last menu was
 4223                        // empty, we should hide it.
 4224                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4225                        // If it was already hidden and we don't show inline
 4226                        // completions in the menu, we should also show the
 4227                        // inline-completion when available.
 4228                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4229                            editor.update_visible_inline_completion(window, cx);
 4230                        }
 4231                    }
 4232                })?;
 4233
 4234                anyhow::Ok(())
 4235            }
 4236            .log_err()
 4237        });
 4238
 4239        self.completion_tasks.push((id, task));
 4240    }
 4241
 4242    pub fn confirm_completion(
 4243        &mut self,
 4244        action: &ConfirmCompletion,
 4245        window: &mut Window,
 4246        cx: &mut Context<Self>,
 4247    ) -> Option<Task<Result<()>>> {
 4248        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4249    }
 4250
 4251    pub fn compose_completion(
 4252        &mut self,
 4253        action: &ComposeCompletion,
 4254        window: &mut Window,
 4255        cx: &mut Context<Self>,
 4256    ) -> Option<Task<Result<()>>> {
 4257        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4258    }
 4259
 4260    fn do_completion(
 4261        &mut self,
 4262        item_ix: Option<usize>,
 4263        intent: CompletionIntent,
 4264        window: &mut Window,
 4265        cx: &mut Context<Editor>,
 4266    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4267        use language::ToOffset as _;
 4268
 4269        let completions_menu =
 4270            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4271                menu
 4272            } else {
 4273                return None;
 4274            };
 4275
 4276        let entries = completions_menu.entries.borrow();
 4277        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4278        if self.show_edit_predictions_in_menu() {
 4279            self.discard_inline_completion(true, cx);
 4280        }
 4281        let candidate_id = mat.candidate_id;
 4282        drop(entries);
 4283
 4284        let buffer_handle = completions_menu.buffer;
 4285        let completion = completions_menu
 4286            .completions
 4287            .borrow()
 4288            .get(candidate_id)?
 4289            .clone();
 4290        cx.stop_propagation();
 4291
 4292        let snippet;
 4293        let text;
 4294
 4295        if completion.is_snippet() {
 4296            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4297            text = snippet.as_ref().unwrap().text.clone();
 4298        } else {
 4299            snippet = None;
 4300            text = completion.new_text.clone();
 4301        };
 4302        let selections = self.selections.all::<usize>(cx);
 4303        let buffer = buffer_handle.read(cx);
 4304        let old_range = completion.old_range.to_offset(buffer);
 4305        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4306
 4307        let newest_selection = self.selections.newest_anchor();
 4308        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4309            return None;
 4310        }
 4311
 4312        let lookbehind = newest_selection
 4313            .start
 4314            .text_anchor
 4315            .to_offset(buffer)
 4316            .saturating_sub(old_range.start);
 4317        let lookahead = old_range
 4318            .end
 4319            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4320        let mut common_prefix_len = old_text
 4321            .bytes()
 4322            .zip(text.bytes())
 4323            .take_while(|(a, b)| a == b)
 4324            .count();
 4325
 4326        let snapshot = self.buffer.read(cx).snapshot(cx);
 4327        let mut range_to_replace: Option<Range<isize>> = None;
 4328        let mut ranges = Vec::new();
 4329        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4330        for selection in &selections {
 4331            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4332                let start = selection.start.saturating_sub(lookbehind);
 4333                let end = selection.end + lookahead;
 4334                if selection.id == newest_selection.id {
 4335                    range_to_replace = Some(
 4336                        ((start + common_prefix_len) as isize - selection.start as isize)
 4337                            ..(end as isize - selection.start as isize),
 4338                    );
 4339                }
 4340                ranges.push(start + common_prefix_len..end);
 4341            } else {
 4342                common_prefix_len = 0;
 4343                ranges.clear();
 4344                ranges.extend(selections.iter().map(|s| {
 4345                    if s.id == newest_selection.id {
 4346                        range_to_replace = Some(
 4347                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4348                                - selection.start as isize
 4349                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4350                                    - selection.start as isize,
 4351                        );
 4352                        old_range.clone()
 4353                    } else {
 4354                        s.start..s.end
 4355                    }
 4356                }));
 4357                break;
 4358            }
 4359            if !self.linked_edit_ranges.is_empty() {
 4360                let start_anchor = snapshot.anchor_before(selection.head());
 4361                let end_anchor = snapshot.anchor_after(selection.tail());
 4362                if let Some(ranges) = self
 4363                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4364                {
 4365                    for (buffer, edits) in ranges {
 4366                        linked_edits.entry(buffer.clone()).or_default().extend(
 4367                            edits
 4368                                .into_iter()
 4369                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4370                        );
 4371                    }
 4372                }
 4373            }
 4374        }
 4375        let text = &text[common_prefix_len..];
 4376
 4377        cx.emit(EditorEvent::InputHandled {
 4378            utf16_range_to_replace: range_to_replace,
 4379            text: text.into(),
 4380        });
 4381
 4382        self.transact(window, cx, |this, window, cx| {
 4383            if let Some(mut snippet) = snippet {
 4384                snippet.text = text.to_string();
 4385                for tabstop in snippet
 4386                    .tabstops
 4387                    .iter_mut()
 4388                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4389                {
 4390                    tabstop.start -= common_prefix_len as isize;
 4391                    tabstop.end -= common_prefix_len as isize;
 4392                }
 4393
 4394                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4395            } else {
 4396                this.buffer.update(cx, |buffer, cx| {
 4397                    buffer.edit(
 4398                        ranges.iter().map(|range| (range.clone(), text)),
 4399                        this.autoindent_mode.clone(),
 4400                        cx,
 4401                    );
 4402                });
 4403            }
 4404            for (buffer, edits) in linked_edits {
 4405                buffer.update(cx, |buffer, cx| {
 4406                    let snapshot = buffer.snapshot();
 4407                    let edits = edits
 4408                        .into_iter()
 4409                        .map(|(range, text)| {
 4410                            use text::ToPoint as TP;
 4411                            let end_point = TP::to_point(&range.end, &snapshot);
 4412                            let start_point = TP::to_point(&range.start, &snapshot);
 4413                            (start_point..end_point, text)
 4414                        })
 4415                        .sorted_by_key(|(range, _)| range.start)
 4416                        .collect::<Vec<_>>();
 4417                    buffer.edit(edits, None, cx);
 4418                })
 4419            }
 4420
 4421            this.refresh_inline_completion(true, false, window, cx);
 4422        });
 4423
 4424        let show_new_completions_on_confirm = completion
 4425            .confirm
 4426            .as_ref()
 4427            .map_or(false, |confirm| confirm(intent, window, cx));
 4428        if show_new_completions_on_confirm {
 4429            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4430        }
 4431
 4432        let provider = self.completion_provider.as_ref()?;
 4433        drop(completion);
 4434        let apply_edits = provider.apply_additional_edits_for_completion(
 4435            buffer_handle,
 4436            completions_menu.completions.clone(),
 4437            candidate_id,
 4438            true,
 4439            cx,
 4440        );
 4441
 4442        let editor_settings = EditorSettings::get_global(cx);
 4443        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4444            // After the code completion is finished, users often want to know what signatures are needed.
 4445            // so we should automatically call signature_help
 4446            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4447        }
 4448
 4449        Some(cx.foreground_executor().spawn(async move {
 4450            apply_edits.await?;
 4451            Ok(())
 4452        }))
 4453    }
 4454
 4455    pub fn toggle_code_actions(
 4456        &mut self,
 4457        action: &ToggleCodeActions,
 4458        window: &mut Window,
 4459        cx: &mut Context<Self>,
 4460    ) {
 4461        let mut context_menu = self.context_menu.borrow_mut();
 4462        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4463            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4464                // Toggle if we're selecting the same one
 4465                *context_menu = None;
 4466                cx.notify();
 4467                return;
 4468            } else {
 4469                // Otherwise, clear it and start a new one
 4470                *context_menu = None;
 4471                cx.notify();
 4472            }
 4473        }
 4474        drop(context_menu);
 4475        let snapshot = self.snapshot(window, cx);
 4476        let deployed_from_indicator = action.deployed_from_indicator;
 4477        let mut task = self.code_actions_task.take();
 4478        let action = action.clone();
 4479        cx.spawn_in(window, |editor, mut cx| async move {
 4480            while let Some(prev_task) = task {
 4481                prev_task.await.log_err();
 4482                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4483            }
 4484
 4485            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4486                if editor.focus_handle.is_focused(window) {
 4487                    let multibuffer_point = action
 4488                        .deployed_from_indicator
 4489                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4490                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4491                    let (buffer, buffer_row) = snapshot
 4492                        .buffer_snapshot
 4493                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4494                        .and_then(|(buffer_snapshot, range)| {
 4495                            editor
 4496                                .buffer
 4497                                .read(cx)
 4498                                .buffer(buffer_snapshot.remote_id())
 4499                                .map(|buffer| (buffer, range.start.row))
 4500                        })?;
 4501                    let (_, code_actions) = editor
 4502                        .available_code_actions
 4503                        .clone()
 4504                        .and_then(|(location, code_actions)| {
 4505                            let snapshot = location.buffer.read(cx).snapshot();
 4506                            let point_range = location.range.to_point(&snapshot);
 4507                            let point_range = point_range.start.row..=point_range.end.row;
 4508                            if point_range.contains(&buffer_row) {
 4509                                Some((location, code_actions))
 4510                            } else {
 4511                                None
 4512                            }
 4513                        })
 4514                        .unzip();
 4515                    let buffer_id = buffer.read(cx).remote_id();
 4516                    let tasks = editor
 4517                        .tasks
 4518                        .get(&(buffer_id, buffer_row))
 4519                        .map(|t| Arc::new(t.to_owned()));
 4520                    if tasks.is_none() && code_actions.is_none() {
 4521                        return None;
 4522                    }
 4523
 4524                    editor.completion_tasks.clear();
 4525                    editor.discard_inline_completion(false, cx);
 4526                    let task_context =
 4527                        tasks
 4528                            .as_ref()
 4529                            .zip(editor.project.clone())
 4530                            .map(|(tasks, project)| {
 4531                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4532                            });
 4533
 4534                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4535                        let task_context = match task_context {
 4536                            Some(task_context) => task_context.await,
 4537                            None => None,
 4538                        };
 4539                        let resolved_tasks =
 4540                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4541                                Rc::new(ResolvedTasks {
 4542                                    templates: tasks.resolve(&task_context).collect(),
 4543                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4544                                        multibuffer_point.row,
 4545                                        tasks.column,
 4546                                    )),
 4547                                })
 4548                            });
 4549                        let spawn_straight_away = resolved_tasks
 4550                            .as_ref()
 4551                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4552                            && code_actions
 4553                                .as_ref()
 4554                                .map_or(true, |actions| actions.is_empty());
 4555                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4556                            *editor.context_menu.borrow_mut() =
 4557                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4558                                    buffer,
 4559                                    actions: CodeActionContents {
 4560                                        tasks: resolved_tasks,
 4561                                        actions: code_actions,
 4562                                    },
 4563                                    selected_item: Default::default(),
 4564                                    scroll_handle: UniformListScrollHandle::default(),
 4565                                    deployed_from_indicator,
 4566                                }));
 4567                            if spawn_straight_away {
 4568                                if let Some(task) = editor.confirm_code_action(
 4569                                    &ConfirmCodeAction { item_ix: Some(0) },
 4570                                    window,
 4571                                    cx,
 4572                                ) {
 4573                                    cx.notify();
 4574                                    return task;
 4575                                }
 4576                            }
 4577                            cx.notify();
 4578                            Task::ready(Ok(()))
 4579                        }) {
 4580                            task.await
 4581                        } else {
 4582                            Ok(())
 4583                        }
 4584                    }))
 4585                } else {
 4586                    Some(Task::ready(Ok(())))
 4587                }
 4588            })?;
 4589            if let Some(task) = spawned_test_task {
 4590                task.await?;
 4591            }
 4592
 4593            Ok::<_, anyhow::Error>(())
 4594        })
 4595        .detach_and_log_err(cx);
 4596    }
 4597
 4598    pub fn confirm_code_action(
 4599        &mut self,
 4600        action: &ConfirmCodeAction,
 4601        window: &mut Window,
 4602        cx: &mut Context<Self>,
 4603    ) -> Option<Task<Result<()>>> {
 4604        let actions_menu =
 4605            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4606                menu
 4607            } else {
 4608                return None;
 4609            };
 4610        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4611        let action = actions_menu.actions.get(action_ix)?;
 4612        let title = action.label();
 4613        let buffer = actions_menu.buffer;
 4614        let workspace = self.workspace()?;
 4615
 4616        match action {
 4617            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4618                workspace.update(cx, |workspace, cx| {
 4619                    workspace::tasks::schedule_resolved_task(
 4620                        workspace,
 4621                        task_source_kind,
 4622                        resolved_task,
 4623                        false,
 4624                        cx,
 4625                    );
 4626
 4627                    Some(Task::ready(Ok(())))
 4628                })
 4629            }
 4630            CodeActionsItem::CodeAction {
 4631                excerpt_id,
 4632                action,
 4633                provider,
 4634            } => {
 4635                let apply_code_action =
 4636                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4637                let workspace = workspace.downgrade();
 4638                Some(cx.spawn_in(window, |editor, cx| async move {
 4639                    let project_transaction = apply_code_action.await?;
 4640                    Self::open_project_transaction(
 4641                        &editor,
 4642                        workspace,
 4643                        project_transaction,
 4644                        title,
 4645                        cx,
 4646                    )
 4647                    .await
 4648                }))
 4649            }
 4650        }
 4651    }
 4652
 4653    pub async fn open_project_transaction(
 4654        this: &WeakEntity<Editor>,
 4655        workspace: WeakEntity<Workspace>,
 4656        transaction: ProjectTransaction,
 4657        title: String,
 4658        mut cx: AsyncWindowContext,
 4659    ) -> Result<()> {
 4660        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4661        cx.update(|_, cx| {
 4662            entries.sort_unstable_by_key(|(buffer, _)| {
 4663                buffer.read(cx).file().map(|f| f.path().clone())
 4664            });
 4665        })?;
 4666
 4667        // If the project transaction's edits are all contained within this editor, then
 4668        // avoid opening a new editor to display them.
 4669
 4670        if let Some((buffer, transaction)) = entries.first() {
 4671            if entries.len() == 1 {
 4672                let excerpt = this.update(&mut cx, |editor, cx| {
 4673                    editor
 4674                        .buffer()
 4675                        .read(cx)
 4676                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4677                })?;
 4678                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4679                    if excerpted_buffer == *buffer {
 4680                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4681                            let excerpt_range = excerpt_range.to_offset(buffer);
 4682                            buffer
 4683                                .edited_ranges_for_transaction::<usize>(transaction)
 4684                                .all(|range| {
 4685                                    excerpt_range.start <= range.start
 4686                                        && excerpt_range.end >= range.end
 4687                                })
 4688                        })?;
 4689
 4690                        if all_edits_within_excerpt {
 4691                            return Ok(());
 4692                        }
 4693                    }
 4694                }
 4695            }
 4696        } else {
 4697            return Ok(());
 4698        }
 4699
 4700        let mut ranges_to_highlight = Vec::new();
 4701        let excerpt_buffer = cx.new(|cx| {
 4702            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4703            for (buffer_handle, transaction) in &entries {
 4704                let buffer = buffer_handle.read(cx);
 4705                ranges_to_highlight.extend(
 4706                    multibuffer.push_excerpts_with_context_lines(
 4707                        buffer_handle.clone(),
 4708                        buffer
 4709                            .edited_ranges_for_transaction::<usize>(transaction)
 4710                            .collect(),
 4711                        DEFAULT_MULTIBUFFER_CONTEXT,
 4712                        cx,
 4713                    ),
 4714                );
 4715            }
 4716            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4717            multibuffer
 4718        })?;
 4719
 4720        workspace.update_in(&mut cx, |workspace, window, cx| {
 4721            let project = workspace.project().clone();
 4722            let editor =
 4723                cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
 4724            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4725            editor.update(cx, |editor, cx| {
 4726                editor.highlight_background::<Self>(
 4727                    &ranges_to_highlight,
 4728                    |theme| theme.editor_highlighted_line_background,
 4729                    cx,
 4730                );
 4731            });
 4732        })?;
 4733
 4734        Ok(())
 4735    }
 4736
 4737    pub fn clear_code_action_providers(&mut self) {
 4738        self.code_action_providers.clear();
 4739        self.available_code_actions.take();
 4740    }
 4741
 4742    pub fn add_code_action_provider(
 4743        &mut self,
 4744        provider: Rc<dyn CodeActionProvider>,
 4745        window: &mut Window,
 4746        cx: &mut Context<Self>,
 4747    ) {
 4748        if self
 4749            .code_action_providers
 4750            .iter()
 4751            .any(|existing_provider| existing_provider.id() == provider.id())
 4752        {
 4753            return;
 4754        }
 4755
 4756        self.code_action_providers.push(provider);
 4757        self.refresh_code_actions(window, cx);
 4758    }
 4759
 4760    pub fn remove_code_action_provider(
 4761        &mut self,
 4762        id: Arc<str>,
 4763        window: &mut Window,
 4764        cx: &mut Context<Self>,
 4765    ) {
 4766        self.code_action_providers
 4767            .retain(|provider| provider.id() != id);
 4768        self.refresh_code_actions(window, cx);
 4769    }
 4770
 4771    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4772        let buffer = self.buffer.read(cx);
 4773        let newest_selection = self.selections.newest_anchor().clone();
 4774        if newest_selection.head().diff_base_anchor.is_some() {
 4775            return None;
 4776        }
 4777        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4778        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4779        if start_buffer != end_buffer {
 4780            return None;
 4781        }
 4782
 4783        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4784            cx.background_executor()
 4785                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4786                .await;
 4787
 4788            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4789                let providers = this.code_action_providers.clone();
 4790                let tasks = this
 4791                    .code_action_providers
 4792                    .iter()
 4793                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4794                    .collect::<Vec<_>>();
 4795                (providers, tasks)
 4796            })?;
 4797
 4798            let mut actions = Vec::new();
 4799            for (provider, provider_actions) in
 4800                providers.into_iter().zip(future::join_all(tasks).await)
 4801            {
 4802                if let Some(provider_actions) = provider_actions.log_err() {
 4803                    actions.extend(provider_actions.into_iter().map(|action| {
 4804                        AvailableCodeAction {
 4805                            excerpt_id: newest_selection.start.excerpt_id,
 4806                            action,
 4807                            provider: provider.clone(),
 4808                        }
 4809                    }));
 4810                }
 4811            }
 4812
 4813            this.update(&mut cx, |this, cx| {
 4814                this.available_code_actions = if actions.is_empty() {
 4815                    None
 4816                } else {
 4817                    Some((
 4818                        Location {
 4819                            buffer: start_buffer,
 4820                            range: start..end,
 4821                        },
 4822                        actions.into(),
 4823                    ))
 4824                };
 4825                cx.notify();
 4826            })
 4827        }));
 4828        None
 4829    }
 4830
 4831    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4832        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4833            self.show_git_blame_inline = false;
 4834
 4835            self.show_git_blame_inline_delay_task =
 4836                Some(cx.spawn_in(window, |this, mut cx| async move {
 4837                    cx.background_executor().timer(delay).await;
 4838
 4839                    this.update(&mut cx, |this, cx| {
 4840                        this.show_git_blame_inline = true;
 4841                        cx.notify();
 4842                    })
 4843                    .log_err();
 4844                }));
 4845        }
 4846    }
 4847
 4848    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4849        if self.pending_rename.is_some() {
 4850            return None;
 4851        }
 4852
 4853        let provider = self.semantics_provider.clone()?;
 4854        let buffer = self.buffer.read(cx);
 4855        let newest_selection = self.selections.newest_anchor().clone();
 4856        let cursor_position = newest_selection.head();
 4857        let (cursor_buffer, cursor_buffer_position) =
 4858            buffer.text_anchor_for_position(cursor_position, cx)?;
 4859        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4860        if cursor_buffer != tail_buffer {
 4861            return None;
 4862        }
 4863        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4864        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4865            cx.background_executor()
 4866                .timer(Duration::from_millis(debounce))
 4867                .await;
 4868
 4869            let highlights = if let Some(highlights) = cx
 4870                .update(|cx| {
 4871                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4872                })
 4873                .ok()
 4874                .flatten()
 4875            {
 4876                highlights.await.log_err()
 4877            } else {
 4878                None
 4879            };
 4880
 4881            if let Some(highlights) = highlights {
 4882                this.update(&mut cx, |this, cx| {
 4883                    if this.pending_rename.is_some() {
 4884                        return;
 4885                    }
 4886
 4887                    let buffer_id = cursor_position.buffer_id;
 4888                    let buffer = this.buffer.read(cx);
 4889                    if !buffer
 4890                        .text_anchor_for_position(cursor_position, cx)
 4891                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4892                    {
 4893                        return;
 4894                    }
 4895
 4896                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4897                    let mut write_ranges = Vec::new();
 4898                    let mut read_ranges = Vec::new();
 4899                    for highlight in highlights {
 4900                        for (excerpt_id, excerpt_range) in
 4901                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4902                        {
 4903                            let start = highlight
 4904                                .range
 4905                                .start
 4906                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4907                            let end = highlight
 4908                                .range
 4909                                .end
 4910                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4911                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4912                                continue;
 4913                            }
 4914
 4915                            let range = Anchor {
 4916                                buffer_id,
 4917                                excerpt_id,
 4918                                text_anchor: start,
 4919                                diff_base_anchor: None,
 4920                            }..Anchor {
 4921                                buffer_id,
 4922                                excerpt_id,
 4923                                text_anchor: end,
 4924                                diff_base_anchor: None,
 4925                            };
 4926                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4927                                write_ranges.push(range);
 4928                            } else {
 4929                                read_ranges.push(range);
 4930                            }
 4931                        }
 4932                    }
 4933
 4934                    this.highlight_background::<DocumentHighlightRead>(
 4935                        &read_ranges,
 4936                        |theme| theme.editor_document_highlight_read_background,
 4937                        cx,
 4938                    );
 4939                    this.highlight_background::<DocumentHighlightWrite>(
 4940                        &write_ranges,
 4941                        |theme| theme.editor_document_highlight_write_background,
 4942                        cx,
 4943                    );
 4944                    cx.notify();
 4945                })
 4946                .log_err();
 4947            }
 4948        }));
 4949        None
 4950    }
 4951
 4952    pub fn refresh_selected_text_highlights(
 4953        &mut self,
 4954        window: &mut Window,
 4955        cx: &mut Context<Editor>,
 4956    ) {
 4957        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 4958            return;
 4959        }
 4960        self.selection_highlight_task.take();
 4961        if !EditorSettings::get_global(cx).selection_highlight {
 4962            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4963            return;
 4964        }
 4965        if self.selections.count() != 1 || self.selections.line_mode {
 4966            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4967            return;
 4968        }
 4969        let selection = self.selections.newest::<Point>(cx);
 4970        if selection.is_empty() || selection.start.row != selection.end.row {
 4971            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4972            return;
 4973        }
 4974        let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
 4975        self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
 4976            cx.background_executor()
 4977                .timer(Duration::from_millis(debounce))
 4978                .await;
 4979            let Some(Some(matches_task)) = editor
 4980                .update_in(&mut cx, |editor, _, cx| {
 4981                    if editor.selections.count() != 1 || editor.selections.line_mode {
 4982                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4983                        return None;
 4984                    }
 4985                    let selection = editor.selections.newest::<Point>(cx);
 4986                    if selection.is_empty() || selection.start.row != selection.end.row {
 4987                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4988                        return None;
 4989                    }
 4990                    let buffer = editor.buffer().read(cx).snapshot(cx);
 4991                    let query = buffer.text_for_range(selection.range()).collect::<String>();
 4992                    if query.trim().is_empty() {
 4993                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4994                        return None;
 4995                    }
 4996                    Some(cx.background_spawn(async move {
 4997                        let mut ranges = Vec::new();
 4998                        let selection_anchors = selection.range().to_anchors(&buffer);
 4999                        for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
 5000                            for (search_buffer, search_range, excerpt_id) in
 5001                                buffer.range_to_buffer_ranges(range)
 5002                            {
 5003                                ranges.extend(
 5004                                    project::search::SearchQuery::text(
 5005                                        query.clone(),
 5006                                        false,
 5007                                        false,
 5008                                        false,
 5009                                        Default::default(),
 5010                                        Default::default(),
 5011                                        None,
 5012                                    )
 5013                                    .unwrap()
 5014                                    .search(search_buffer, Some(search_range.clone()))
 5015                                    .await
 5016                                    .into_iter()
 5017                                    .filter_map(
 5018                                        |match_range| {
 5019                                            let start = search_buffer.anchor_after(
 5020                                                search_range.start + match_range.start,
 5021                                            );
 5022                                            let end = search_buffer.anchor_before(
 5023                                                search_range.start + match_range.end,
 5024                                            );
 5025                                            let range = Anchor::range_in_buffer(
 5026                                                excerpt_id,
 5027                                                search_buffer.remote_id(),
 5028                                                start..end,
 5029                                            );
 5030                                            (range != selection_anchors).then_some(range)
 5031                                        },
 5032                                    ),
 5033                                );
 5034                            }
 5035                        }
 5036                        ranges
 5037                    }))
 5038                })
 5039                .log_err()
 5040            else {
 5041                return;
 5042            };
 5043            let matches = matches_task.await;
 5044            editor
 5045                .update_in(&mut cx, |editor, _, cx| {
 5046                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5047                    if !matches.is_empty() {
 5048                        editor.highlight_background::<SelectedTextHighlight>(
 5049                            &matches,
 5050                            |theme| theme.editor_document_highlight_bracket_background,
 5051                            cx,
 5052                        )
 5053                    }
 5054                })
 5055                .log_err();
 5056        }));
 5057    }
 5058
 5059    pub fn refresh_inline_completion(
 5060        &mut self,
 5061        debounce: bool,
 5062        user_requested: bool,
 5063        window: &mut Window,
 5064        cx: &mut Context<Self>,
 5065    ) -> Option<()> {
 5066        let provider = self.edit_prediction_provider()?;
 5067        let cursor = self.selections.newest_anchor().head();
 5068        let (buffer, cursor_buffer_position) =
 5069            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5070
 5071        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 5072            self.discard_inline_completion(false, cx);
 5073            return None;
 5074        }
 5075
 5076        if !user_requested
 5077            && (!self.should_show_edit_predictions()
 5078                || !self.is_focused(window)
 5079                || buffer.read(cx).is_empty())
 5080        {
 5081            self.discard_inline_completion(false, cx);
 5082            return None;
 5083        }
 5084
 5085        self.update_visible_inline_completion(window, cx);
 5086        provider.refresh(
 5087            self.project.clone(),
 5088            buffer,
 5089            cursor_buffer_position,
 5090            debounce,
 5091            cx,
 5092        );
 5093        Some(())
 5094    }
 5095
 5096    fn show_edit_predictions_in_menu(&self) -> bool {
 5097        match self.edit_prediction_settings {
 5098            EditPredictionSettings::Disabled => false,
 5099            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 5100        }
 5101    }
 5102
 5103    pub fn edit_predictions_enabled(&self) -> bool {
 5104        match self.edit_prediction_settings {
 5105            EditPredictionSettings::Disabled => false,
 5106            EditPredictionSettings::Enabled { .. } => true,
 5107        }
 5108    }
 5109
 5110    fn edit_prediction_requires_modifier(&self) -> bool {
 5111        match self.edit_prediction_settings {
 5112            EditPredictionSettings::Disabled => false,
 5113            EditPredictionSettings::Enabled {
 5114                preview_requires_modifier,
 5115                ..
 5116            } => preview_requires_modifier,
 5117        }
 5118    }
 5119
 5120    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 5121        if self.edit_prediction_provider.is_none() {
 5122            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5123        } else {
 5124            let selection = self.selections.newest_anchor();
 5125            let cursor = selection.head();
 5126
 5127            if let Some((buffer, cursor_buffer_position)) =
 5128                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5129            {
 5130                self.edit_prediction_settings =
 5131                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5132            }
 5133        }
 5134    }
 5135
 5136    fn edit_prediction_settings_at_position(
 5137        &self,
 5138        buffer: &Entity<Buffer>,
 5139        buffer_position: language::Anchor,
 5140        cx: &App,
 5141    ) -> EditPredictionSettings {
 5142        if self.mode != EditorMode::Full
 5143            || !self.show_inline_completions_override.unwrap_or(true)
 5144            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 5145        {
 5146            return EditPredictionSettings::Disabled;
 5147        }
 5148
 5149        let buffer = buffer.read(cx);
 5150
 5151        let file = buffer.file();
 5152
 5153        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 5154            return EditPredictionSettings::Disabled;
 5155        };
 5156
 5157        let by_provider = matches!(
 5158            self.menu_inline_completions_policy,
 5159            MenuInlineCompletionsPolicy::ByProvider
 5160        );
 5161
 5162        let show_in_menu = by_provider
 5163            && self
 5164                .edit_prediction_provider
 5165                .as_ref()
 5166                .map_or(false, |provider| {
 5167                    provider.provider.show_completions_in_menu()
 5168                });
 5169
 5170        let preview_requires_modifier =
 5171            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 5172
 5173        EditPredictionSettings::Enabled {
 5174            show_in_menu,
 5175            preview_requires_modifier,
 5176        }
 5177    }
 5178
 5179    fn should_show_edit_predictions(&self) -> bool {
 5180        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 5181    }
 5182
 5183    pub fn edit_prediction_preview_is_active(&self) -> bool {
 5184        matches!(
 5185            self.edit_prediction_preview,
 5186            EditPredictionPreview::Active { .. }
 5187        )
 5188    }
 5189
 5190    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 5191        let cursor = self.selections.newest_anchor().head();
 5192        if let Some((buffer, cursor_position)) =
 5193            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5194        {
 5195            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 5196        } else {
 5197            false
 5198        }
 5199    }
 5200
 5201    fn edit_predictions_enabled_in_buffer(
 5202        &self,
 5203        buffer: &Entity<Buffer>,
 5204        buffer_position: language::Anchor,
 5205        cx: &App,
 5206    ) -> bool {
 5207        maybe!({
 5208            if self.read_only(cx) {
 5209                return Some(false);
 5210            }
 5211            let provider = self.edit_prediction_provider()?;
 5212            if !provider.is_enabled(&buffer, buffer_position, cx) {
 5213                return Some(false);
 5214            }
 5215            let buffer = buffer.read(cx);
 5216            let Some(file) = buffer.file() else {
 5217                return Some(true);
 5218            };
 5219            let settings = all_language_settings(Some(file), cx);
 5220            Some(settings.edit_predictions_enabled_for_file(file, cx))
 5221        })
 5222        .unwrap_or(false)
 5223    }
 5224
 5225    fn cycle_inline_completion(
 5226        &mut self,
 5227        direction: Direction,
 5228        window: &mut Window,
 5229        cx: &mut Context<Self>,
 5230    ) -> Option<()> {
 5231        let provider = self.edit_prediction_provider()?;
 5232        let cursor = self.selections.newest_anchor().head();
 5233        let (buffer, cursor_buffer_position) =
 5234            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5235        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 5236            return None;
 5237        }
 5238
 5239        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5240        self.update_visible_inline_completion(window, cx);
 5241
 5242        Some(())
 5243    }
 5244
 5245    pub fn show_inline_completion(
 5246        &mut self,
 5247        _: &ShowEditPrediction,
 5248        window: &mut Window,
 5249        cx: &mut Context<Self>,
 5250    ) {
 5251        if !self.has_active_inline_completion() {
 5252            self.refresh_inline_completion(false, true, window, cx);
 5253            return;
 5254        }
 5255
 5256        self.update_visible_inline_completion(window, cx);
 5257    }
 5258
 5259    pub fn display_cursor_names(
 5260        &mut self,
 5261        _: &DisplayCursorNames,
 5262        window: &mut Window,
 5263        cx: &mut Context<Self>,
 5264    ) {
 5265        self.show_cursor_names(window, cx);
 5266    }
 5267
 5268    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5269        self.show_cursor_names = true;
 5270        cx.notify();
 5271        cx.spawn_in(window, |this, mut cx| async move {
 5272            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5273            this.update(&mut cx, |this, cx| {
 5274                this.show_cursor_names = false;
 5275                cx.notify()
 5276            })
 5277            .ok()
 5278        })
 5279        .detach();
 5280    }
 5281
 5282    pub fn next_edit_prediction(
 5283        &mut self,
 5284        _: &NextEditPrediction,
 5285        window: &mut Window,
 5286        cx: &mut Context<Self>,
 5287    ) {
 5288        if self.has_active_inline_completion() {
 5289            self.cycle_inline_completion(Direction::Next, window, cx);
 5290        } else {
 5291            let is_copilot_disabled = self
 5292                .refresh_inline_completion(false, true, window, cx)
 5293                .is_none();
 5294            if is_copilot_disabled {
 5295                cx.propagate();
 5296            }
 5297        }
 5298    }
 5299
 5300    pub fn previous_edit_prediction(
 5301        &mut self,
 5302        _: &PreviousEditPrediction,
 5303        window: &mut Window,
 5304        cx: &mut Context<Self>,
 5305    ) {
 5306        if self.has_active_inline_completion() {
 5307            self.cycle_inline_completion(Direction::Prev, window, cx);
 5308        } else {
 5309            let is_copilot_disabled = self
 5310                .refresh_inline_completion(false, true, window, cx)
 5311                .is_none();
 5312            if is_copilot_disabled {
 5313                cx.propagate();
 5314            }
 5315        }
 5316    }
 5317
 5318    pub fn accept_edit_prediction(
 5319        &mut self,
 5320        _: &AcceptEditPrediction,
 5321        window: &mut Window,
 5322        cx: &mut Context<Self>,
 5323    ) {
 5324        if self.show_edit_predictions_in_menu() {
 5325            self.hide_context_menu(window, cx);
 5326        }
 5327
 5328        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5329            return;
 5330        };
 5331
 5332        self.report_inline_completion_event(
 5333            active_inline_completion.completion_id.clone(),
 5334            true,
 5335            cx,
 5336        );
 5337
 5338        match &active_inline_completion.completion {
 5339            InlineCompletion::Move { target, .. } => {
 5340                let target = *target;
 5341
 5342                if let Some(position_map) = &self.last_position_map {
 5343                    if position_map
 5344                        .visible_row_range
 5345                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5346                        || !self.edit_prediction_requires_modifier()
 5347                    {
 5348                        self.unfold_ranges(&[target..target], true, false, cx);
 5349                        // Note that this is also done in vim's handler of the Tab action.
 5350                        self.change_selections(
 5351                            Some(Autoscroll::newest()),
 5352                            window,
 5353                            cx,
 5354                            |selections| {
 5355                                selections.select_anchor_ranges([target..target]);
 5356                            },
 5357                        );
 5358                        self.clear_row_highlights::<EditPredictionPreview>();
 5359
 5360                        self.edit_prediction_preview
 5361                            .set_previous_scroll_position(None);
 5362                    } else {
 5363                        self.edit_prediction_preview
 5364                            .set_previous_scroll_position(Some(
 5365                                position_map.snapshot.scroll_anchor,
 5366                            ));
 5367
 5368                        self.highlight_rows::<EditPredictionPreview>(
 5369                            target..target,
 5370                            cx.theme().colors().editor_highlighted_line_background,
 5371                            true,
 5372                            cx,
 5373                        );
 5374                        self.request_autoscroll(Autoscroll::fit(), cx);
 5375                    }
 5376                }
 5377            }
 5378            InlineCompletion::Edit { edits, .. } => {
 5379                if let Some(provider) = self.edit_prediction_provider() {
 5380                    provider.accept(cx);
 5381                }
 5382
 5383                let snapshot = self.buffer.read(cx).snapshot(cx);
 5384                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5385
 5386                self.buffer.update(cx, |buffer, cx| {
 5387                    buffer.edit(edits.iter().cloned(), None, cx)
 5388                });
 5389
 5390                self.change_selections(None, window, cx, |s| {
 5391                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5392                });
 5393
 5394                self.update_visible_inline_completion(window, cx);
 5395                if self.active_inline_completion.is_none() {
 5396                    self.refresh_inline_completion(true, true, window, cx);
 5397                }
 5398
 5399                cx.notify();
 5400            }
 5401        }
 5402
 5403        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 5404    }
 5405
 5406    pub fn accept_partial_inline_completion(
 5407        &mut self,
 5408        _: &AcceptPartialEditPrediction,
 5409        window: &mut Window,
 5410        cx: &mut Context<Self>,
 5411    ) {
 5412        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5413            return;
 5414        };
 5415        if self.selections.count() != 1 {
 5416            return;
 5417        }
 5418
 5419        self.report_inline_completion_event(
 5420            active_inline_completion.completion_id.clone(),
 5421            true,
 5422            cx,
 5423        );
 5424
 5425        match &active_inline_completion.completion {
 5426            InlineCompletion::Move { target, .. } => {
 5427                let target = *target;
 5428                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5429                    selections.select_anchor_ranges([target..target]);
 5430                });
 5431            }
 5432            InlineCompletion::Edit { edits, .. } => {
 5433                // Find an insertion that starts at the cursor position.
 5434                let snapshot = self.buffer.read(cx).snapshot(cx);
 5435                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5436                let insertion = edits.iter().find_map(|(range, text)| {
 5437                    let range = range.to_offset(&snapshot);
 5438                    if range.is_empty() && range.start == cursor_offset {
 5439                        Some(text)
 5440                    } else {
 5441                        None
 5442                    }
 5443                });
 5444
 5445                if let Some(text) = insertion {
 5446                    let mut partial_completion = text
 5447                        .chars()
 5448                        .by_ref()
 5449                        .take_while(|c| c.is_alphabetic())
 5450                        .collect::<String>();
 5451                    if partial_completion.is_empty() {
 5452                        partial_completion = text
 5453                            .chars()
 5454                            .by_ref()
 5455                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5456                            .collect::<String>();
 5457                    }
 5458
 5459                    cx.emit(EditorEvent::InputHandled {
 5460                        utf16_range_to_replace: None,
 5461                        text: partial_completion.clone().into(),
 5462                    });
 5463
 5464                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5465
 5466                    self.refresh_inline_completion(true, true, window, cx);
 5467                    cx.notify();
 5468                } else {
 5469                    self.accept_edit_prediction(&Default::default(), window, cx);
 5470                }
 5471            }
 5472        }
 5473    }
 5474
 5475    fn discard_inline_completion(
 5476        &mut self,
 5477        should_report_inline_completion_event: bool,
 5478        cx: &mut Context<Self>,
 5479    ) -> bool {
 5480        if should_report_inline_completion_event {
 5481            let completion_id = self
 5482                .active_inline_completion
 5483                .as_ref()
 5484                .and_then(|active_completion| active_completion.completion_id.clone());
 5485
 5486            self.report_inline_completion_event(completion_id, false, cx);
 5487        }
 5488
 5489        if let Some(provider) = self.edit_prediction_provider() {
 5490            provider.discard(cx);
 5491        }
 5492
 5493        self.take_active_inline_completion(cx)
 5494    }
 5495
 5496    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5497        let Some(provider) = self.edit_prediction_provider() else {
 5498            return;
 5499        };
 5500
 5501        let Some((_, buffer, _)) = self
 5502            .buffer
 5503            .read(cx)
 5504            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5505        else {
 5506            return;
 5507        };
 5508
 5509        let extension = buffer
 5510            .read(cx)
 5511            .file()
 5512            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5513
 5514        let event_type = match accepted {
 5515            true => "Edit Prediction Accepted",
 5516            false => "Edit Prediction Discarded",
 5517        };
 5518        telemetry::event!(
 5519            event_type,
 5520            provider = provider.name(),
 5521            prediction_id = id,
 5522            suggestion_accepted = accepted,
 5523            file_extension = extension,
 5524        );
 5525    }
 5526
 5527    pub fn has_active_inline_completion(&self) -> bool {
 5528        self.active_inline_completion.is_some()
 5529    }
 5530
 5531    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5532        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5533            return false;
 5534        };
 5535
 5536        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5537        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5538        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5539        true
 5540    }
 5541
 5542    /// Returns true when we're displaying the edit prediction popover below the cursor
 5543    /// like we are not previewing and the LSP autocomplete menu is visible
 5544    /// or we are in `when_holding_modifier` mode.
 5545    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5546        if self.edit_prediction_preview_is_active()
 5547            || !self.show_edit_predictions_in_menu()
 5548            || !self.edit_predictions_enabled()
 5549        {
 5550            return false;
 5551        }
 5552
 5553        if self.has_visible_completions_menu() {
 5554            return true;
 5555        }
 5556
 5557        has_completion && self.edit_prediction_requires_modifier()
 5558    }
 5559
 5560    fn handle_modifiers_changed(
 5561        &mut self,
 5562        modifiers: Modifiers,
 5563        position_map: &PositionMap,
 5564        window: &mut Window,
 5565        cx: &mut Context<Self>,
 5566    ) {
 5567        if self.show_edit_predictions_in_menu() {
 5568            self.update_edit_prediction_preview(&modifiers, window, cx);
 5569        }
 5570
 5571        self.update_selection_mode(&modifiers, position_map, window, cx);
 5572
 5573        let mouse_position = window.mouse_position();
 5574        if !position_map.text_hitbox.is_hovered(window) {
 5575            return;
 5576        }
 5577
 5578        self.update_hovered_link(
 5579            position_map.point_for_position(mouse_position),
 5580            &position_map.snapshot,
 5581            modifiers,
 5582            window,
 5583            cx,
 5584        )
 5585    }
 5586
 5587    fn update_selection_mode(
 5588        &mut self,
 5589        modifiers: &Modifiers,
 5590        position_map: &PositionMap,
 5591        window: &mut Window,
 5592        cx: &mut Context<Self>,
 5593    ) {
 5594        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 5595            return;
 5596        }
 5597
 5598        let mouse_position = window.mouse_position();
 5599        let point_for_position = position_map.point_for_position(mouse_position);
 5600        let position = point_for_position.previous_valid;
 5601
 5602        self.select(
 5603            SelectPhase::BeginColumnar {
 5604                position,
 5605                reset: false,
 5606                goal_column: point_for_position.exact_unclipped.column(),
 5607            },
 5608            window,
 5609            cx,
 5610        );
 5611    }
 5612
 5613    fn update_edit_prediction_preview(
 5614        &mut self,
 5615        modifiers: &Modifiers,
 5616        window: &mut Window,
 5617        cx: &mut Context<Self>,
 5618    ) {
 5619        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5620        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5621            return;
 5622        };
 5623
 5624        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5625            if matches!(
 5626                self.edit_prediction_preview,
 5627                EditPredictionPreview::Inactive { .. }
 5628            ) {
 5629                self.edit_prediction_preview = EditPredictionPreview::Active {
 5630                    previous_scroll_position: None,
 5631                    since: Instant::now(),
 5632                };
 5633
 5634                self.update_visible_inline_completion(window, cx);
 5635                cx.notify();
 5636            }
 5637        } else if let EditPredictionPreview::Active {
 5638            previous_scroll_position,
 5639            since,
 5640        } = self.edit_prediction_preview
 5641        {
 5642            if let (Some(previous_scroll_position), Some(position_map)) =
 5643                (previous_scroll_position, self.last_position_map.as_ref())
 5644            {
 5645                self.set_scroll_position(
 5646                    previous_scroll_position
 5647                        .scroll_position(&position_map.snapshot.display_snapshot),
 5648                    window,
 5649                    cx,
 5650                );
 5651            }
 5652
 5653            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 5654                released_too_fast: since.elapsed() < Duration::from_millis(200),
 5655            };
 5656            self.clear_row_highlights::<EditPredictionPreview>();
 5657            self.update_visible_inline_completion(window, cx);
 5658            cx.notify();
 5659        }
 5660    }
 5661
 5662    fn update_visible_inline_completion(
 5663        &mut self,
 5664        _window: &mut Window,
 5665        cx: &mut Context<Self>,
 5666    ) -> Option<()> {
 5667        let selection = self.selections.newest_anchor();
 5668        let cursor = selection.head();
 5669        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5670        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5671        let excerpt_id = cursor.excerpt_id;
 5672
 5673        let show_in_menu = self.show_edit_predictions_in_menu();
 5674        let completions_menu_has_precedence = !show_in_menu
 5675            && (self.context_menu.borrow().is_some()
 5676                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5677
 5678        if completions_menu_has_precedence
 5679            || !offset_selection.is_empty()
 5680            || self
 5681                .active_inline_completion
 5682                .as_ref()
 5683                .map_or(false, |completion| {
 5684                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5685                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5686                    !invalidation_range.contains(&offset_selection.head())
 5687                })
 5688        {
 5689            self.discard_inline_completion(false, cx);
 5690            return None;
 5691        }
 5692
 5693        self.take_active_inline_completion(cx);
 5694        let Some(provider) = self.edit_prediction_provider() else {
 5695            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5696            return None;
 5697        };
 5698
 5699        let (buffer, cursor_buffer_position) =
 5700            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5701
 5702        self.edit_prediction_settings =
 5703            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5704
 5705        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 5706
 5707        if self.edit_prediction_indent_conflict {
 5708            let cursor_point = cursor.to_point(&multibuffer);
 5709
 5710            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 5711
 5712            if let Some((_, indent)) = indents.iter().next() {
 5713                if indent.len == cursor_point.column {
 5714                    self.edit_prediction_indent_conflict = false;
 5715                }
 5716            }
 5717        }
 5718
 5719        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5720        let edits = inline_completion
 5721            .edits
 5722            .into_iter()
 5723            .flat_map(|(range, new_text)| {
 5724                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5725                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5726                Some((start..end, new_text))
 5727            })
 5728            .collect::<Vec<_>>();
 5729        if edits.is_empty() {
 5730            return None;
 5731        }
 5732
 5733        let first_edit_start = edits.first().unwrap().0.start;
 5734        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5735        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5736
 5737        let last_edit_end = edits.last().unwrap().0.end;
 5738        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5739        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5740
 5741        let cursor_row = cursor.to_point(&multibuffer).row;
 5742
 5743        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5744
 5745        let mut inlay_ids = Vec::new();
 5746        let invalidation_row_range;
 5747        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5748            Some(cursor_row..edit_end_row)
 5749        } else if cursor_row > edit_end_row {
 5750            Some(edit_start_row..cursor_row)
 5751        } else {
 5752            None
 5753        };
 5754        let is_move =
 5755            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5756        let completion = if is_move {
 5757            invalidation_row_range =
 5758                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5759            let target = first_edit_start;
 5760            InlineCompletion::Move { target, snapshot }
 5761        } else {
 5762            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 5763                && !self.inline_completions_hidden_for_vim_mode;
 5764
 5765            if show_completions_in_buffer {
 5766                if edits
 5767                    .iter()
 5768                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5769                {
 5770                    let mut inlays = Vec::new();
 5771                    for (range, new_text) in &edits {
 5772                        let inlay = Inlay::inline_completion(
 5773                            post_inc(&mut self.next_inlay_id),
 5774                            range.start,
 5775                            new_text.as_str(),
 5776                        );
 5777                        inlay_ids.push(inlay.id);
 5778                        inlays.push(inlay);
 5779                    }
 5780
 5781                    self.splice_inlays(&[], inlays, cx);
 5782                } else {
 5783                    let background_color = cx.theme().status().deleted_background;
 5784                    self.highlight_text::<InlineCompletionHighlight>(
 5785                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5786                        HighlightStyle {
 5787                            background_color: Some(background_color),
 5788                            ..Default::default()
 5789                        },
 5790                        cx,
 5791                    );
 5792                }
 5793            }
 5794
 5795            invalidation_row_range = edit_start_row..edit_end_row;
 5796
 5797            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5798                if provider.show_tab_accept_marker() {
 5799                    EditDisplayMode::TabAccept
 5800                } else {
 5801                    EditDisplayMode::Inline
 5802                }
 5803            } else {
 5804                EditDisplayMode::DiffPopover
 5805            };
 5806
 5807            InlineCompletion::Edit {
 5808                edits,
 5809                edit_preview: inline_completion.edit_preview,
 5810                display_mode,
 5811                snapshot,
 5812            }
 5813        };
 5814
 5815        let invalidation_range = multibuffer
 5816            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5817            ..multibuffer.anchor_after(Point::new(
 5818                invalidation_row_range.end,
 5819                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5820            ));
 5821
 5822        self.stale_inline_completion_in_menu = None;
 5823        self.active_inline_completion = Some(InlineCompletionState {
 5824            inlay_ids,
 5825            completion,
 5826            completion_id: inline_completion.id,
 5827            invalidation_range,
 5828        });
 5829
 5830        cx.notify();
 5831
 5832        Some(())
 5833    }
 5834
 5835    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5836        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5837    }
 5838
 5839    fn render_code_actions_indicator(
 5840        &self,
 5841        _style: &EditorStyle,
 5842        row: DisplayRow,
 5843        is_active: bool,
 5844        cx: &mut Context<Self>,
 5845    ) -> Option<IconButton> {
 5846        if self.available_code_actions.is_some() {
 5847            Some(
 5848                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5849                    .shape(ui::IconButtonShape::Square)
 5850                    .icon_size(IconSize::XSmall)
 5851                    .icon_color(Color::Muted)
 5852                    .toggle_state(is_active)
 5853                    .tooltip({
 5854                        let focus_handle = self.focus_handle.clone();
 5855                        move |window, cx| {
 5856                            Tooltip::for_action_in(
 5857                                "Toggle Code Actions",
 5858                                &ToggleCodeActions {
 5859                                    deployed_from_indicator: None,
 5860                                },
 5861                                &focus_handle,
 5862                                window,
 5863                                cx,
 5864                            )
 5865                        }
 5866                    })
 5867                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5868                        window.focus(&editor.focus_handle(cx));
 5869                        editor.toggle_code_actions(
 5870                            &ToggleCodeActions {
 5871                                deployed_from_indicator: Some(row),
 5872                            },
 5873                            window,
 5874                            cx,
 5875                        );
 5876                    })),
 5877            )
 5878        } else {
 5879            None
 5880        }
 5881    }
 5882
 5883    fn clear_tasks(&mut self) {
 5884        self.tasks.clear()
 5885    }
 5886
 5887    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5888        if self.tasks.insert(key, value).is_some() {
 5889            // This case should hopefully be rare, but just in case...
 5890            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5891        }
 5892    }
 5893
 5894    fn build_tasks_context(
 5895        project: &Entity<Project>,
 5896        buffer: &Entity<Buffer>,
 5897        buffer_row: u32,
 5898        tasks: &Arc<RunnableTasks>,
 5899        cx: &mut Context<Self>,
 5900    ) -> Task<Option<task::TaskContext>> {
 5901        let position = Point::new(buffer_row, tasks.column);
 5902        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5903        let location = Location {
 5904            buffer: buffer.clone(),
 5905            range: range_start..range_start,
 5906        };
 5907        // Fill in the environmental variables from the tree-sitter captures
 5908        let mut captured_task_variables = TaskVariables::default();
 5909        for (capture_name, value) in tasks.extra_variables.clone() {
 5910            captured_task_variables.insert(
 5911                task::VariableName::Custom(capture_name.into()),
 5912                value.clone(),
 5913            );
 5914        }
 5915        project.update(cx, |project, cx| {
 5916            project.task_store().update(cx, |task_store, cx| {
 5917                task_store.task_context_for_location(captured_task_variables, location, cx)
 5918            })
 5919        })
 5920    }
 5921
 5922    pub fn spawn_nearest_task(
 5923        &mut self,
 5924        action: &SpawnNearestTask,
 5925        window: &mut Window,
 5926        cx: &mut Context<Self>,
 5927    ) {
 5928        let Some((workspace, _)) = self.workspace.clone() else {
 5929            return;
 5930        };
 5931        let Some(project) = self.project.clone() else {
 5932            return;
 5933        };
 5934
 5935        // Try to find a closest, enclosing node using tree-sitter that has a
 5936        // task
 5937        let Some((buffer, buffer_row, tasks)) = self
 5938            .find_enclosing_node_task(cx)
 5939            // Or find the task that's closest in row-distance.
 5940            .or_else(|| self.find_closest_task(cx))
 5941        else {
 5942            return;
 5943        };
 5944
 5945        let reveal_strategy = action.reveal;
 5946        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5947        cx.spawn_in(window, |_, mut cx| async move {
 5948            let context = task_context.await?;
 5949            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5950
 5951            let resolved = resolved_task.resolved.as_mut()?;
 5952            resolved.reveal = reveal_strategy;
 5953
 5954            workspace
 5955                .update(&mut cx, |workspace, cx| {
 5956                    workspace::tasks::schedule_resolved_task(
 5957                        workspace,
 5958                        task_source_kind,
 5959                        resolved_task,
 5960                        false,
 5961                        cx,
 5962                    );
 5963                })
 5964                .ok()
 5965        })
 5966        .detach();
 5967    }
 5968
 5969    fn find_closest_task(
 5970        &mut self,
 5971        cx: &mut Context<Self>,
 5972    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5973        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5974
 5975        let ((buffer_id, row), tasks) = self
 5976            .tasks
 5977            .iter()
 5978            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5979
 5980        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5981        let tasks = Arc::new(tasks.to_owned());
 5982        Some((buffer, *row, tasks))
 5983    }
 5984
 5985    fn find_enclosing_node_task(
 5986        &mut self,
 5987        cx: &mut Context<Self>,
 5988    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5989        let snapshot = self.buffer.read(cx).snapshot(cx);
 5990        let offset = self.selections.newest::<usize>(cx).head();
 5991        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5992        let buffer_id = excerpt.buffer().remote_id();
 5993
 5994        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5995        let mut cursor = layer.node().walk();
 5996
 5997        while cursor.goto_first_child_for_byte(offset).is_some() {
 5998            if cursor.node().end_byte() == offset {
 5999                cursor.goto_next_sibling();
 6000            }
 6001        }
 6002
 6003        // Ascend to the smallest ancestor that contains the range and has a task.
 6004        loop {
 6005            let node = cursor.node();
 6006            let node_range = node.byte_range();
 6007            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 6008
 6009            // Check if this node contains our offset
 6010            if node_range.start <= offset && node_range.end >= offset {
 6011                // If it contains offset, check for task
 6012                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 6013                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 6014                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 6015                }
 6016            }
 6017
 6018            if !cursor.goto_parent() {
 6019                break;
 6020            }
 6021        }
 6022        None
 6023    }
 6024
 6025    fn render_run_indicator(
 6026        &self,
 6027        _style: &EditorStyle,
 6028        is_active: bool,
 6029        row: DisplayRow,
 6030        cx: &mut Context<Self>,
 6031    ) -> IconButton {
 6032        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 6033            .shape(ui::IconButtonShape::Square)
 6034            .icon_size(IconSize::XSmall)
 6035            .icon_color(Color::Muted)
 6036            .toggle_state(is_active)
 6037            .on_click(cx.listener(move |editor, _e, window, cx| {
 6038                window.focus(&editor.focus_handle(cx));
 6039                editor.toggle_code_actions(
 6040                    &ToggleCodeActions {
 6041                        deployed_from_indicator: Some(row),
 6042                    },
 6043                    window,
 6044                    cx,
 6045                );
 6046            }))
 6047    }
 6048
 6049    pub fn context_menu_visible(&self) -> bool {
 6050        !self.edit_prediction_preview_is_active()
 6051            && self
 6052                .context_menu
 6053                .borrow()
 6054                .as_ref()
 6055                .map_or(false, |menu| menu.visible())
 6056    }
 6057
 6058    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 6059        self.context_menu
 6060            .borrow()
 6061            .as_ref()
 6062            .map(|menu| menu.origin())
 6063    }
 6064
 6065    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 6066    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 6067
 6068    fn render_edit_prediction_popover(
 6069        &mut self,
 6070        text_bounds: &Bounds<Pixels>,
 6071        content_origin: gpui::Point<Pixels>,
 6072        editor_snapshot: &EditorSnapshot,
 6073        visible_row_range: Range<DisplayRow>,
 6074        scroll_top: f32,
 6075        scroll_bottom: f32,
 6076        line_layouts: &[LineWithInvisibles],
 6077        line_height: Pixels,
 6078        scroll_pixel_position: gpui::Point<Pixels>,
 6079        newest_selection_head: Option<DisplayPoint>,
 6080        editor_width: Pixels,
 6081        style: &EditorStyle,
 6082        window: &mut Window,
 6083        cx: &mut App,
 6084    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6085        let active_inline_completion = self.active_inline_completion.as_ref()?;
 6086
 6087        if self.edit_prediction_visible_in_cursor_popover(true) {
 6088            return None;
 6089        }
 6090
 6091        match &active_inline_completion.completion {
 6092            InlineCompletion::Move { target, .. } => {
 6093                let target_display_point = target.to_display_point(editor_snapshot);
 6094
 6095                if self.edit_prediction_requires_modifier() {
 6096                    if !self.edit_prediction_preview_is_active() {
 6097                        return None;
 6098                    }
 6099
 6100                    self.render_edit_prediction_modifier_jump_popover(
 6101                        text_bounds,
 6102                        content_origin,
 6103                        visible_row_range,
 6104                        line_layouts,
 6105                        line_height,
 6106                        scroll_pixel_position,
 6107                        newest_selection_head,
 6108                        target_display_point,
 6109                        window,
 6110                        cx,
 6111                    )
 6112                } else {
 6113                    self.render_edit_prediction_eager_jump_popover(
 6114                        text_bounds,
 6115                        content_origin,
 6116                        editor_snapshot,
 6117                        visible_row_range,
 6118                        scroll_top,
 6119                        scroll_bottom,
 6120                        line_height,
 6121                        scroll_pixel_position,
 6122                        target_display_point,
 6123                        editor_width,
 6124                        window,
 6125                        cx,
 6126                    )
 6127                }
 6128            }
 6129            InlineCompletion::Edit {
 6130                display_mode: EditDisplayMode::Inline,
 6131                ..
 6132            } => None,
 6133            InlineCompletion::Edit {
 6134                display_mode: EditDisplayMode::TabAccept,
 6135                edits,
 6136                ..
 6137            } => {
 6138                let range = &edits.first()?.0;
 6139                let target_display_point = range.end.to_display_point(editor_snapshot);
 6140
 6141                self.render_edit_prediction_end_of_line_popover(
 6142                    "Accept",
 6143                    editor_snapshot,
 6144                    visible_row_range,
 6145                    target_display_point,
 6146                    line_height,
 6147                    scroll_pixel_position,
 6148                    content_origin,
 6149                    editor_width,
 6150                    window,
 6151                    cx,
 6152                )
 6153            }
 6154            InlineCompletion::Edit {
 6155                edits,
 6156                edit_preview,
 6157                display_mode: EditDisplayMode::DiffPopover,
 6158                snapshot,
 6159            } => self.render_edit_prediction_diff_popover(
 6160                text_bounds,
 6161                content_origin,
 6162                editor_snapshot,
 6163                visible_row_range,
 6164                line_layouts,
 6165                line_height,
 6166                scroll_pixel_position,
 6167                newest_selection_head,
 6168                editor_width,
 6169                style,
 6170                edits,
 6171                edit_preview,
 6172                snapshot,
 6173                window,
 6174                cx,
 6175            ),
 6176        }
 6177    }
 6178
 6179    fn render_edit_prediction_modifier_jump_popover(
 6180        &mut self,
 6181        text_bounds: &Bounds<Pixels>,
 6182        content_origin: gpui::Point<Pixels>,
 6183        visible_row_range: Range<DisplayRow>,
 6184        line_layouts: &[LineWithInvisibles],
 6185        line_height: Pixels,
 6186        scroll_pixel_position: gpui::Point<Pixels>,
 6187        newest_selection_head: Option<DisplayPoint>,
 6188        target_display_point: DisplayPoint,
 6189        window: &mut Window,
 6190        cx: &mut App,
 6191    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6192        let scrolled_content_origin =
 6193            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 6194
 6195        const SCROLL_PADDING_Y: Pixels = px(12.);
 6196
 6197        if target_display_point.row() < visible_row_range.start {
 6198            return self.render_edit_prediction_scroll_popover(
 6199                |_| SCROLL_PADDING_Y,
 6200                IconName::ArrowUp,
 6201                visible_row_range,
 6202                line_layouts,
 6203                newest_selection_head,
 6204                scrolled_content_origin,
 6205                window,
 6206                cx,
 6207            );
 6208        } else if target_display_point.row() >= visible_row_range.end {
 6209            return self.render_edit_prediction_scroll_popover(
 6210                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 6211                IconName::ArrowDown,
 6212                visible_row_range,
 6213                line_layouts,
 6214                newest_selection_head,
 6215                scrolled_content_origin,
 6216                window,
 6217                cx,
 6218            );
 6219        }
 6220
 6221        const POLE_WIDTH: Pixels = px(2.);
 6222
 6223        let line_layout =
 6224            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 6225        let target_column = target_display_point.column() as usize;
 6226
 6227        let target_x = line_layout.x_for_index(target_column);
 6228        let target_y =
 6229            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 6230
 6231        let flag_on_right = target_x < text_bounds.size.width / 2.;
 6232
 6233        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 6234        border_color.l += 0.001;
 6235
 6236        let mut element = v_flex()
 6237            .items_end()
 6238            .when(flag_on_right, |el| el.items_start())
 6239            .child(if flag_on_right {
 6240                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6241                    .rounded_bl(px(0.))
 6242                    .rounded_tl(px(0.))
 6243                    .border_l_2()
 6244                    .border_color(border_color)
 6245            } else {
 6246                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6247                    .rounded_br(px(0.))
 6248                    .rounded_tr(px(0.))
 6249                    .border_r_2()
 6250                    .border_color(border_color)
 6251            })
 6252            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 6253            .into_any();
 6254
 6255        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6256
 6257        let mut origin = scrolled_content_origin + point(target_x, target_y)
 6258            - point(
 6259                if flag_on_right {
 6260                    POLE_WIDTH
 6261                } else {
 6262                    size.width - POLE_WIDTH
 6263                },
 6264                size.height - line_height,
 6265            );
 6266
 6267        origin.x = origin.x.max(content_origin.x);
 6268
 6269        element.prepaint_at(origin, window, cx);
 6270
 6271        Some((element, origin))
 6272    }
 6273
 6274    fn render_edit_prediction_scroll_popover(
 6275        &mut self,
 6276        to_y: impl Fn(Size<Pixels>) -> Pixels,
 6277        scroll_icon: IconName,
 6278        visible_row_range: Range<DisplayRow>,
 6279        line_layouts: &[LineWithInvisibles],
 6280        newest_selection_head: Option<DisplayPoint>,
 6281        scrolled_content_origin: gpui::Point<Pixels>,
 6282        window: &mut Window,
 6283        cx: &mut App,
 6284    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6285        let mut element = self
 6286            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 6287            .into_any();
 6288
 6289        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6290
 6291        let cursor = newest_selection_head?;
 6292        let cursor_row_layout =
 6293            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 6294        let cursor_column = cursor.column() as usize;
 6295
 6296        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 6297
 6298        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 6299
 6300        element.prepaint_at(origin, window, cx);
 6301        Some((element, origin))
 6302    }
 6303
 6304    fn render_edit_prediction_eager_jump_popover(
 6305        &mut self,
 6306        text_bounds: &Bounds<Pixels>,
 6307        content_origin: gpui::Point<Pixels>,
 6308        editor_snapshot: &EditorSnapshot,
 6309        visible_row_range: Range<DisplayRow>,
 6310        scroll_top: f32,
 6311        scroll_bottom: f32,
 6312        line_height: Pixels,
 6313        scroll_pixel_position: gpui::Point<Pixels>,
 6314        target_display_point: DisplayPoint,
 6315        editor_width: Pixels,
 6316        window: &mut Window,
 6317        cx: &mut App,
 6318    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6319        if target_display_point.row().as_f32() < scroll_top {
 6320            let mut element = self
 6321                .render_edit_prediction_line_popover(
 6322                    "Jump to Edit",
 6323                    Some(IconName::ArrowUp),
 6324                    window,
 6325                    cx,
 6326                )?
 6327                .into_any();
 6328
 6329            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6330            let offset = point(
 6331                (text_bounds.size.width - size.width) / 2.,
 6332                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6333            );
 6334
 6335            let origin = text_bounds.origin + offset;
 6336            element.prepaint_at(origin, window, cx);
 6337            Some((element, origin))
 6338        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 6339            let mut element = self
 6340                .render_edit_prediction_line_popover(
 6341                    "Jump to Edit",
 6342                    Some(IconName::ArrowDown),
 6343                    window,
 6344                    cx,
 6345                )?
 6346                .into_any();
 6347
 6348            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6349            let offset = point(
 6350                (text_bounds.size.width - size.width) / 2.,
 6351                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6352            );
 6353
 6354            let origin = text_bounds.origin + offset;
 6355            element.prepaint_at(origin, window, cx);
 6356            Some((element, origin))
 6357        } else {
 6358            self.render_edit_prediction_end_of_line_popover(
 6359                "Jump to Edit",
 6360                editor_snapshot,
 6361                visible_row_range,
 6362                target_display_point,
 6363                line_height,
 6364                scroll_pixel_position,
 6365                content_origin,
 6366                editor_width,
 6367                window,
 6368                cx,
 6369            )
 6370        }
 6371    }
 6372
 6373    fn render_edit_prediction_end_of_line_popover(
 6374        self: &mut Editor,
 6375        label: &'static str,
 6376        editor_snapshot: &EditorSnapshot,
 6377        visible_row_range: Range<DisplayRow>,
 6378        target_display_point: DisplayPoint,
 6379        line_height: Pixels,
 6380        scroll_pixel_position: gpui::Point<Pixels>,
 6381        content_origin: gpui::Point<Pixels>,
 6382        editor_width: Pixels,
 6383        window: &mut Window,
 6384        cx: &mut App,
 6385    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6386        let target_line_end = DisplayPoint::new(
 6387            target_display_point.row(),
 6388            editor_snapshot.line_len(target_display_point.row()),
 6389        );
 6390
 6391        let mut element = self
 6392            .render_edit_prediction_line_popover(label, None, window, cx)?
 6393            .into_any();
 6394
 6395        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6396
 6397        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 6398
 6399        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 6400        let mut origin = start_point
 6401            + line_origin
 6402            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 6403        origin.x = origin.x.max(content_origin.x);
 6404
 6405        let max_x = content_origin.x + editor_width - size.width;
 6406
 6407        if origin.x > max_x {
 6408            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 6409
 6410            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 6411                origin.y += offset;
 6412                IconName::ArrowUp
 6413            } else {
 6414                origin.y -= offset;
 6415                IconName::ArrowDown
 6416            };
 6417
 6418            element = self
 6419                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 6420                .into_any();
 6421
 6422            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6423
 6424            origin.x = content_origin.x + editor_width - size.width - px(2.);
 6425        }
 6426
 6427        element.prepaint_at(origin, window, cx);
 6428        Some((element, origin))
 6429    }
 6430
 6431    fn render_edit_prediction_diff_popover(
 6432        self: &Editor,
 6433        text_bounds: &Bounds<Pixels>,
 6434        content_origin: gpui::Point<Pixels>,
 6435        editor_snapshot: &EditorSnapshot,
 6436        visible_row_range: Range<DisplayRow>,
 6437        line_layouts: &[LineWithInvisibles],
 6438        line_height: Pixels,
 6439        scroll_pixel_position: gpui::Point<Pixels>,
 6440        newest_selection_head: Option<DisplayPoint>,
 6441        editor_width: Pixels,
 6442        style: &EditorStyle,
 6443        edits: &Vec<(Range<Anchor>, String)>,
 6444        edit_preview: &Option<language::EditPreview>,
 6445        snapshot: &language::BufferSnapshot,
 6446        window: &mut Window,
 6447        cx: &mut App,
 6448    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6449        let edit_start = edits
 6450            .first()
 6451            .unwrap()
 6452            .0
 6453            .start
 6454            .to_display_point(editor_snapshot);
 6455        let edit_end = edits
 6456            .last()
 6457            .unwrap()
 6458            .0
 6459            .end
 6460            .to_display_point(editor_snapshot);
 6461
 6462        let is_visible = visible_row_range.contains(&edit_start.row())
 6463            || visible_row_range.contains(&edit_end.row());
 6464        if !is_visible {
 6465            return None;
 6466        }
 6467
 6468        let highlighted_edits =
 6469            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 6470
 6471        let styled_text = highlighted_edits.to_styled_text(&style.text);
 6472        let line_count = highlighted_edits.text.lines().count();
 6473
 6474        const BORDER_WIDTH: Pixels = px(1.);
 6475
 6476        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 6477        let has_keybind = keybind.is_some();
 6478
 6479        let mut element = h_flex()
 6480            .items_start()
 6481            .child(
 6482                h_flex()
 6483                    .bg(cx.theme().colors().editor_background)
 6484                    .border(BORDER_WIDTH)
 6485                    .shadow_sm()
 6486                    .border_color(cx.theme().colors().border)
 6487                    .rounded_l_lg()
 6488                    .when(line_count > 1, |el| el.rounded_br_lg())
 6489                    .pr_1()
 6490                    .child(styled_text),
 6491            )
 6492            .child(
 6493                h_flex()
 6494                    .h(line_height + BORDER_WIDTH * px(2.))
 6495                    .px_1p5()
 6496                    .gap_1()
 6497                    // Workaround: For some reason, there's a gap if we don't do this
 6498                    .ml(-BORDER_WIDTH)
 6499                    .shadow(smallvec![gpui::BoxShadow {
 6500                        color: gpui::black().opacity(0.05),
 6501                        offset: point(px(1.), px(1.)),
 6502                        blur_radius: px(2.),
 6503                        spread_radius: px(0.),
 6504                    }])
 6505                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 6506                    .border(BORDER_WIDTH)
 6507                    .border_color(cx.theme().colors().border)
 6508                    .rounded_r_lg()
 6509                    .id("edit_prediction_diff_popover_keybind")
 6510                    .when(!has_keybind, |el| {
 6511                        let status_colors = cx.theme().status();
 6512
 6513                        el.bg(status_colors.error_background)
 6514                            .border_color(status_colors.error.opacity(0.6))
 6515                            .child(Icon::new(IconName::Info).color(Color::Error))
 6516                            .cursor_default()
 6517                            .hoverable_tooltip(move |_window, cx| {
 6518                                cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 6519                            })
 6520                    })
 6521                    .children(keybind),
 6522            )
 6523            .into_any();
 6524
 6525        let longest_row =
 6526            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 6527        let longest_line_width = if visible_row_range.contains(&longest_row) {
 6528            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 6529        } else {
 6530            layout_line(
 6531                longest_row,
 6532                editor_snapshot,
 6533                style,
 6534                editor_width,
 6535                |_| false,
 6536                window,
 6537                cx,
 6538            )
 6539            .width
 6540        };
 6541
 6542        let viewport_bounds =
 6543            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 6544                right: -EditorElement::SCROLLBAR_WIDTH,
 6545                ..Default::default()
 6546            });
 6547
 6548        let x_after_longest =
 6549            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 6550                - scroll_pixel_position.x;
 6551
 6552        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6553
 6554        // Fully visible if it can be displayed within the window (allow overlapping other
 6555        // panes). However, this is only allowed if the popover starts within text_bounds.
 6556        let can_position_to_the_right = x_after_longest < text_bounds.right()
 6557            && x_after_longest + element_bounds.width < viewport_bounds.right();
 6558
 6559        let mut origin = if can_position_to_the_right {
 6560            point(
 6561                x_after_longest,
 6562                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 6563                    - scroll_pixel_position.y,
 6564            )
 6565        } else {
 6566            let cursor_row = newest_selection_head.map(|head| head.row());
 6567            let above_edit = edit_start
 6568                .row()
 6569                .0
 6570                .checked_sub(line_count as u32)
 6571                .map(DisplayRow);
 6572            let below_edit = Some(edit_end.row() + 1);
 6573            let above_cursor =
 6574                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 6575            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 6576
 6577            // Place the edit popover adjacent to the edit if there is a location
 6578            // available that is onscreen and does not obscure the cursor. Otherwise,
 6579            // place it adjacent to the cursor.
 6580            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 6581                .into_iter()
 6582                .flatten()
 6583                .find(|&start_row| {
 6584                    let end_row = start_row + line_count as u32;
 6585                    visible_row_range.contains(&start_row)
 6586                        && visible_row_range.contains(&end_row)
 6587                        && cursor_row.map_or(true, |cursor_row| {
 6588                            !((start_row..end_row).contains(&cursor_row))
 6589                        })
 6590                })?;
 6591
 6592            content_origin
 6593                + point(
 6594                    -scroll_pixel_position.x,
 6595                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 6596                )
 6597        };
 6598
 6599        origin.x -= BORDER_WIDTH;
 6600
 6601        window.defer_draw(element, origin, 1);
 6602
 6603        // Do not return an element, since it will already be drawn due to defer_draw.
 6604        None
 6605    }
 6606
 6607    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 6608        px(30.)
 6609    }
 6610
 6611    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 6612        if self.read_only(cx) {
 6613            cx.theme().players().read_only()
 6614        } else {
 6615            self.style.as_ref().unwrap().local_player
 6616        }
 6617    }
 6618
 6619    fn render_edit_prediction_accept_keybind(
 6620        &self,
 6621        window: &mut Window,
 6622        cx: &App,
 6623    ) -> Option<AnyElement> {
 6624        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 6625        let accept_keystroke = accept_binding.keystroke()?;
 6626
 6627        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6628
 6629        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 6630            Color::Accent
 6631        } else {
 6632            Color::Muted
 6633        };
 6634
 6635        h_flex()
 6636            .px_0p5()
 6637            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 6638            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6639            .text_size(TextSize::XSmall.rems(cx))
 6640            .child(h_flex().children(ui::render_modifiers(
 6641                &accept_keystroke.modifiers,
 6642                PlatformStyle::platform(),
 6643                Some(modifiers_color),
 6644                Some(IconSize::XSmall.rems().into()),
 6645                true,
 6646            )))
 6647            .when(is_platform_style_mac, |parent| {
 6648                parent.child(accept_keystroke.key.clone())
 6649            })
 6650            .when(!is_platform_style_mac, |parent| {
 6651                parent.child(
 6652                    Key::new(
 6653                        util::capitalize(&accept_keystroke.key),
 6654                        Some(Color::Default),
 6655                    )
 6656                    .size(Some(IconSize::XSmall.rems().into())),
 6657                )
 6658            })
 6659            .into_any()
 6660            .into()
 6661    }
 6662
 6663    fn render_edit_prediction_line_popover(
 6664        &self,
 6665        label: impl Into<SharedString>,
 6666        icon: Option<IconName>,
 6667        window: &mut Window,
 6668        cx: &App,
 6669    ) -> Option<Stateful<Div>> {
 6670        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 6671
 6672        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 6673        let has_keybind = keybind.is_some();
 6674
 6675        let result = h_flex()
 6676            .id("ep-line-popover")
 6677            .py_0p5()
 6678            .pl_1()
 6679            .pr(padding_right)
 6680            .gap_1()
 6681            .rounded_md()
 6682            .border_1()
 6683            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6684            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 6685            .shadow_sm()
 6686            .when(!has_keybind, |el| {
 6687                let status_colors = cx.theme().status();
 6688
 6689                el.bg(status_colors.error_background)
 6690                    .border_color(status_colors.error.opacity(0.6))
 6691                    .pl_2()
 6692                    .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
 6693                    .cursor_default()
 6694                    .hoverable_tooltip(move |_window, cx| {
 6695                        cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 6696                    })
 6697            })
 6698            .children(keybind)
 6699            .child(
 6700                Label::new(label)
 6701                    .size(LabelSize::Small)
 6702                    .when(!has_keybind, |el| {
 6703                        el.color(cx.theme().status().error.into()).strikethrough()
 6704                    }),
 6705            )
 6706            .when(!has_keybind, |el| {
 6707                el.child(
 6708                    h_flex().ml_1().child(
 6709                        Icon::new(IconName::Info)
 6710                            .size(IconSize::Small)
 6711                            .color(cx.theme().status().error.into()),
 6712                    ),
 6713                )
 6714            })
 6715            .when_some(icon, |element, icon| {
 6716                element.child(
 6717                    div()
 6718                        .mt(px(1.5))
 6719                        .child(Icon::new(icon).size(IconSize::Small)),
 6720                )
 6721            });
 6722
 6723        Some(result)
 6724    }
 6725
 6726    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 6727        let accent_color = cx.theme().colors().text_accent;
 6728        let editor_bg_color = cx.theme().colors().editor_background;
 6729        editor_bg_color.blend(accent_color.opacity(0.1))
 6730    }
 6731
 6732    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 6733        let accent_color = cx.theme().colors().text_accent;
 6734        let editor_bg_color = cx.theme().colors().editor_background;
 6735        editor_bg_color.blend(accent_color.opacity(0.6))
 6736    }
 6737
 6738    fn render_edit_prediction_cursor_popover(
 6739        &self,
 6740        min_width: Pixels,
 6741        max_width: Pixels,
 6742        cursor_point: Point,
 6743        style: &EditorStyle,
 6744        accept_keystroke: Option<&gpui::Keystroke>,
 6745        _window: &Window,
 6746        cx: &mut Context<Editor>,
 6747    ) -> Option<AnyElement> {
 6748        let provider = self.edit_prediction_provider.as_ref()?;
 6749
 6750        if provider.provider.needs_terms_acceptance(cx) {
 6751            return Some(
 6752                h_flex()
 6753                    .min_w(min_width)
 6754                    .flex_1()
 6755                    .px_2()
 6756                    .py_1()
 6757                    .gap_3()
 6758                    .elevation_2(cx)
 6759                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 6760                    .id("accept-terms")
 6761                    .cursor_pointer()
 6762                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 6763                    .on_click(cx.listener(|this, _event, window, cx| {
 6764                        cx.stop_propagation();
 6765                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 6766                        window.dispatch_action(
 6767                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 6768                            cx,
 6769                        );
 6770                    }))
 6771                    .child(
 6772                        h_flex()
 6773                            .flex_1()
 6774                            .gap_2()
 6775                            .child(Icon::new(IconName::ZedPredict))
 6776                            .child(Label::new("Accept Terms of Service"))
 6777                            .child(div().w_full())
 6778                            .child(
 6779                                Icon::new(IconName::ArrowUpRight)
 6780                                    .color(Color::Muted)
 6781                                    .size(IconSize::Small),
 6782                            )
 6783                            .into_any_element(),
 6784                    )
 6785                    .into_any(),
 6786            );
 6787        }
 6788
 6789        let is_refreshing = provider.provider.is_refreshing(cx);
 6790
 6791        fn pending_completion_container() -> Div {
 6792            h_flex()
 6793                .h_full()
 6794                .flex_1()
 6795                .gap_2()
 6796                .child(Icon::new(IconName::ZedPredict))
 6797        }
 6798
 6799        let completion = match &self.active_inline_completion {
 6800            Some(prediction) => {
 6801                if !self.has_visible_completions_menu() {
 6802                    const RADIUS: Pixels = px(6.);
 6803                    const BORDER_WIDTH: Pixels = px(1.);
 6804
 6805                    return Some(
 6806                        h_flex()
 6807                            .elevation_2(cx)
 6808                            .border(BORDER_WIDTH)
 6809                            .border_color(cx.theme().colors().border)
 6810                            .when(accept_keystroke.is_none(), |el| {
 6811                                el.border_color(cx.theme().status().error)
 6812                            })
 6813                            .rounded(RADIUS)
 6814                            .rounded_tl(px(0.))
 6815                            .overflow_hidden()
 6816                            .child(div().px_1p5().child(match &prediction.completion {
 6817                                InlineCompletion::Move { target, snapshot } => {
 6818                                    use text::ToPoint as _;
 6819                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 6820                                    {
 6821                                        Icon::new(IconName::ZedPredictDown)
 6822                                    } else {
 6823                                        Icon::new(IconName::ZedPredictUp)
 6824                                    }
 6825                                }
 6826                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 6827                            }))
 6828                            .child(
 6829                                h_flex()
 6830                                    .gap_1()
 6831                                    .py_1()
 6832                                    .px_2()
 6833                                    .rounded_r(RADIUS - BORDER_WIDTH)
 6834                                    .border_l_1()
 6835                                    .border_color(cx.theme().colors().border)
 6836                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6837                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 6838                                        el.child(
 6839                                            Label::new("Hold")
 6840                                                .size(LabelSize::Small)
 6841                                                .when(accept_keystroke.is_none(), |el| {
 6842                                                    el.strikethrough()
 6843                                                })
 6844                                                .line_height_style(LineHeightStyle::UiLabel),
 6845                                        )
 6846                                    })
 6847                                    .id("edit_prediction_cursor_popover_keybind")
 6848                                    .when(accept_keystroke.is_none(), |el| {
 6849                                        let status_colors = cx.theme().status();
 6850
 6851                                        el.bg(status_colors.error_background)
 6852                                            .border_color(status_colors.error.opacity(0.6))
 6853                                            .child(Icon::new(IconName::Info).color(Color::Error))
 6854                                            .cursor_default()
 6855                                            .hoverable_tooltip(move |_window, cx| {
 6856                                                cx.new(|_| MissingEditPredictionKeybindingTooltip)
 6857                                                    .into()
 6858                                            })
 6859                                    })
 6860                                    .when_some(
 6861                                        accept_keystroke.as_ref(),
 6862                                        |el, accept_keystroke| {
 6863                                            el.child(h_flex().children(ui::render_modifiers(
 6864                                                &accept_keystroke.modifiers,
 6865                                                PlatformStyle::platform(),
 6866                                                Some(Color::Default),
 6867                                                Some(IconSize::XSmall.rems().into()),
 6868                                                false,
 6869                                            )))
 6870                                        },
 6871                                    ),
 6872                            )
 6873                            .into_any(),
 6874                    );
 6875                }
 6876
 6877                self.render_edit_prediction_cursor_popover_preview(
 6878                    prediction,
 6879                    cursor_point,
 6880                    style,
 6881                    cx,
 6882                )?
 6883            }
 6884
 6885            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 6886                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 6887                    stale_completion,
 6888                    cursor_point,
 6889                    style,
 6890                    cx,
 6891                )?,
 6892
 6893                None => {
 6894                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 6895                }
 6896            },
 6897
 6898            None => pending_completion_container().child(Label::new("No Prediction")),
 6899        };
 6900
 6901        let completion = if is_refreshing {
 6902            completion
 6903                .with_animation(
 6904                    "loading-completion",
 6905                    Animation::new(Duration::from_secs(2))
 6906                        .repeat()
 6907                        .with_easing(pulsating_between(0.4, 0.8)),
 6908                    |label, delta| label.opacity(delta),
 6909                )
 6910                .into_any_element()
 6911        } else {
 6912            completion.into_any_element()
 6913        };
 6914
 6915        let has_completion = self.active_inline_completion.is_some();
 6916
 6917        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6918        Some(
 6919            h_flex()
 6920                .min_w(min_width)
 6921                .max_w(max_width)
 6922                .flex_1()
 6923                .elevation_2(cx)
 6924                .border_color(cx.theme().colors().border)
 6925                .child(
 6926                    div()
 6927                        .flex_1()
 6928                        .py_1()
 6929                        .px_2()
 6930                        .overflow_hidden()
 6931                        .child(completion),
 6932                )
 6933                .when_some(accept_keystroke, |el, accept_keystroke| {
 6934                    if !accept_keystroke.modifiers.modified() {
 6935                        return el;
 6936                    }
 6937
 6938                    el.child(
 6939                        h_flex()
 6940                            .h_full()
 6941                            .border_l_1()
 6942                            .rounded_r_lg()
 6943                            .border_color(cx.theme().colors().border)
 6944                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6945                            .gap_1()
 6946                            .py_1()
 6947                            .px_2()
 6948                            .child(
 6949                                h_flex()
 6950                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6951                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 6952                                    .child(h_flex().children(ui::render_modifiers(
 6953                                        &accept_keystroke.modifiers,
 6954                                        PlatformStyle::platform(),
 6955                                        Some(if !has_completion {
 6956                                            Color::Muted
 6957                                        } else {
 6958                                            Color::Default
 6959                                        }),
 6960                                        None,
 6961                                        false,
 6962                                    ))),
 6963                            )
 6964                            .child(Label::new("Preview").into_any_element())
 6965                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 6966                    )
 6967                })
 6968                .into_any(),
 6969        )
 6970    }
 6971
 6972    fn render_edit_prediction_cursor_popover_preview(
 6973        &self,
 6974        completion: &InlineCompletionState,
 6975        cursor_point: Point,
 6976        style: &EditorStyle,
 6977        cx: &mut Context<Editor>,
 6978    ) -> Option<Div> {
 6979        use text::ToPoint as _;
 6980
 6981        fn render_relative_row_jump(
 6982            prefix: impl Into<String>,
 6983            current_row: u32,
 6984            target_row: u32,
 6985        ) -> Div {
 6986            let (row_diff, arrow) = if target_row < current_row {
 6987                (current_row - target_row, IconName::ArrowUp)
 6988            } else {
 6989                (target_row - current_row, IconName::ArrowDown)
 6990            };
 6991
 6992            h_flex()
 6993                .child(
 6994                    Label::new(format!("{}{}", prefix.into(), row_diff))
 6995                        .color(Color::Muted)
 6996                        .size(LabelSize::Small),
 6997                )
 6998                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 6999        }
 7000
 7001        match &completion.completion {
 7002            InlineCompletion::Move {
 7003                target, snapshot, ..
 7004            } => Some(
 7005                h_flex()
 7006                    .px_2()
 7007                    .gap_2()
 7008                    .flex_1()
 7009                    .child(
 7010                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 7011                            Icon::new(IconName::ZedPredictDown)
 7012                        } else {
 7013                            Icon::new(IconName::ZedPredictUp)
 7014                        },
 7015                    )
 7016                    .child(Label::new("Jump to Edit")),
 7017            ),
 7018
 7019            InlineCompletion::Edit {
 7020                edits,
 7021                edit_preview,
 7022                snapshot,
 7023                display_mode: _,
 7024            } => {
 7025                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 7026
 7027                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 7028                    &snapshot,
 7029                    &edits,
 7030                    edit_preview.as_ref()?,
 7031                    true,
 7032                    cx,
 7033                )
 7034                .first_line_preview();
 7035
 7036                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 7037                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 7038
 7039                let preview = h_flex()
 7040                    .gap_1()
 7041                    .min_w_16()
 7042                    .child(styled_text)
 7043                    .when(has_more_lines, |parent| parent.child(""));
 7044
 7045                let left = if first_edit_row != cursor_point.row {
 7046                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 7047                        .into_any_element()
 7048                } else {
 7049                    Icon::new(IconName::ZedPredict).into_any_element()
 7050                };
 7051
 7052                Some(
 7053                    h_flex()
 7054                        .h_full()
 7055                        .flex_1()
 7056                        .gap_2()
 7057                        .pr_1()
 7058                        .overflow_x_hidden()
 7059                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7060                        .child(left)
 7061                        .child(preview),
 7062                )
 7063            }
 7064        }
 7065    }
 7066
 7067    fn render_context_menu(
 7068        &self,
 7069        style: &EditorStyle,
 7070        max_height_in_lines: u32,
 7071        y_flipped: bool,
 7072        window: &mut Window,
 7073        cx: &mut Context<Editor>,
 7074    ) -> Option<AnyElement> {
 7075        let menu = self.context_menu.borrow();
 7076        let menu = menu.as_ref()?;
 7077        if !menu.visible() {
 7078            return None;
 7079        };
 7080        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 7081    }
 7082
 7083    fn render_context_menu_aside(
 7084        &mut self,
 7085        max_size: Size<Pixels>,
 7086        window: &mut Window,
 7087        cx: &mut Context<Editor>,
 7088    ) -> Option<AnyElement> {
 7089        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 7090            if menu.visible() {
 7091                menu.render_aside(self, max_size, window, cx)
 7092            } else {
 7093                None
 7094            }
 7095        })
 7096    }
 7097
 7098    fn hide_context_menu(
 7099        &mut self,
 7100        window: &mut Window,
 7101        cx: &mut Context<Self>,
 7102    ) -> Option<CodeContextMenu> {
 7103        cx.notify();
 7104        self.completion_tasks.clear();
 7105        let context_menu = self.context_menu.borrow_mut().take();
 7106        self.stale_inline_completion_in_menu.take();
 7107        self.update_visible_inline_completion(window, cx);
 7108        context_menu
 7109    }
 7110
 7111    fn show_snippet_choices(
 7112        &mut self,
 7113        choices: &Vec<String>,
 7114        selection: Range<Anchor>,
 7115        cx: &mut Context<Self>,
 7116    ) {
 7117        if selection.start.buffer_id.is_none() {
 7118            return;
 7119        }
 7120        let buffer_id = selection.start.buffer_id.unwrap();
 7121        let buffer = self.buffer().read(cx).buffer(buffer_id);
 7122        let id = post_inc(&mut self.next_completion_id);
 7123
 7124        if let Some(buffer) = buffer {
 7125            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 7126                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 7127            ));
 7128        }
 7129    }
 7130
 7131    pub fn insert_snippet(
 7132        &mut self,
 7133        insertion_ranges: &[Range<usize>],
 7134        snippet: Snippet,
 7135        window: &mut Window,
 7136        cx: &mut Context<Self>,
 7137    ) -> Result<()> {
 7138        struct Tabstop<T> {
 7139            is_end_tabstop: bool,
 7140            ranges: Vec<Range<T>>,
 7141            choices: Option<Vec<String>>,
 7142        }
 7143
 7144        let tabstops = self.buffer.update(cx, |buffer, cx| {
 7145            let snippet_text: Arc<str> = snippet.text.clone().into();
 7146            buffer.edit(
 7147                insertion_ranges
 7148                    .iter()
 7149                    .cloned()
 7150                    .map(|range| (range, snippet_text.clone())),
 7151                Some(AutoindentMode::EachLine),
 7152                cx,
 7153            );
 7154
 7155            let snapshot = &*buffer.read(cx);
 7156            let snippet = &snippet;
 7157            snippet
 7158                .tabstops
 7159                .iter()
 7160                .map(|tabstop| {
 7161                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 7162                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 7163                    });
 7164                    let mut tabstop_ranges = tabstop
 7165                        .ranges
 7166                        .iter()
 7167                        .flat_map(|tabstop_range| {
 7168                            let mut delta = 0_isize;
 7169                            insertion_ranges.iter().map(move |insertion_range| {
 7170                                let insertion_start = insertion_range.start as isize + delta;
 7171                                delta +=
 7172                                    snippet.text.len() as isize - insertion_range.len() as isize;
 7173
 7174                                let start = ((insertion_start + tabstop_range.start) as usize)
 7175                                    .min(snapshot.len());
 7176                                let end = ((insertion_start + tabstop_range.end) as usize)
 7177                                    .min(snapshot.len());
 7178                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 7179                            })
 7180                        })
 7181                        .collect::<Vec<_>>();
 7182                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 7183
 7184                    Tabstop {
 7185                        is_end_tabstop,
 7186                        ranges: tabstop_ranges,
 7187                        choices: tabstop.choices.clone(),
 7188                    }
 7189                })
 7190                .collect::<Vec<_>>()
 7191        });
 7192        if let Some(tabstop) = tabstops.first() {
 7193            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7194                s.select_ranges(tabstop.ranges.iter().cloned());
 7195            });
 7196
 7197            if let Some(choices) = &tabstop.choices {
 7198                if let Some(selection) = tabstop.ranges.first() {
 7199                    self.show_snippet_choices(choices, selection.clone(), cx)
 7200                }
 7201            }
 7202
 7203            // If we're already at the last tabstop and it's at the end of the snippet,
 7204            // we're done, we don't need to keep the state around.
 7205            if !tabstop.is_end_tabstop {
 7206                let choices = tabstops
 7207                    .iter()
 7208                    .map(|tabstop| tabstop.choices.clone())
 7209                    .collect();
 7210
 7211                let ranges = tabstops
 7212                    .into_iter()
 7213                    .map(|tabstop| tabstop.ranges)
 7214                    .collect::<Vec<_>>();
 7215
 7216                self.snippet_stack.push(SnippetState {
 7217                    active_index: 0,
 7218                    ranges,
 7219                    choices,
 7220                });
 7221            }
 7222
 7223            // Check whether the just-entered snippet ends with an auto-closable bracket.
 7224            if self.autoclose_regions.is_empty() {
 7225                let snapshot = self.buffer.read(cx).snapshot(cx);
 7226                for selection in &mut self.selections.all::<Point>(cx) {
 7227                    let selection_head = selection.head();
 7228                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 7229                        continue;
 7230                    };
 7231
 7232                    let mut bracket_pair = None;
 7233                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 7234                    let prev_chars = snapshot
 7235                        .reversed_chars_at(selection_head)
 7236                        .collect::<String>();
 7237                    for (pair, enabled) in scope.brackets() {
 7238                        if enabled
 7239                            && pair.close
 7240                            && prev_chars.starts_with(pair.start.as_str())
 7241                            && next_chars.starts_with(pair.end.as_str())
 7242                        {
 7243                            bracket_pair = Some(pair.clone());
 7244                            break;
 7245                        }
 7246                    }
 7247                    if let Some(pair) = bracket_pair {
 7248                        let start = snapshot.anchor_after(selection_head);
 7249                        let end = snapshot.anchor_after(selection_head);
 7250                        self.autoclose_regions.push(AutocloseRegion {
 7251                            selection_id: selection.id,
 7252                            range: start..end,
 7253                            pair,
 7254                        });
 7255                    }
 7256                }
 7257            }
 7258        }
 7259        Ok(())
 7260    }
 7261
 7262    pub fn move_to_next_snippet_tabstop(
 7263        &mut self,
 7264        window: &mut Window,
 7265        cx: &mut Context<Self>,
 7266    ) -> bool {
 7267        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 7268    }
 7269
 7270    pub fn move_to_prev_snippet_tabstop(
 7271        &mut self,
 7272        window: &mut Window,
 7273        cx: &mut Context<Self>,
 7274    ) -> bool {
 7275        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 7276    }
 7277
 7278    pub fn move_to_snippet_tabstop(
 7279        &mut self,
 7280        bias: Bias,
 7281        window: &mut Window,
 7282        cx: &mut Context<Self>,
 7283    ) -> bool {
 7284        if let Some(mut snippet) = self.snippet_stack.pop() {
 7285            match bias {
 7286                Bias::Left => {
 7287                    if snippet.active_index > 0 {
 7288                        snippet.active_index -= 1;
 7289                    } else {
 7290                        self.snippet_stack.push(snippet);
 7291                        return false;
 7292                    }
 7293                }
 7294                Bias::Right => {
 7295                    if snippet.active_index + 1 < snippet.ranges.len() {
 7296                        snippet.active_index += 1;
 7297                    } else {
 7298                        self.snippet_stack.push(snippet);
 7299                        return false;
 7300                    }
 7301                }
 7302            }
 7303            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 7304                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7305                    s.select_anchor_ranges(current_ranges.iter().cloned())
 7306                });
 7307
 7308                if let Some(choices) = &snippet.choices[snippet.active_index] {
 7309                    if let Some(selection) = current_ranges.first() {
 7310                        self.show_snippet_choices(&choices, selection.clone(), cx);
 7311                    }
 7312                }
 7313
 7314                // If snippet state is not at the last tabstop, push it back on the stack
 7315                if snippet.active_index + 1 < snippet.ranges.len() {
 7316                    self.snippet_stack.push(snippet);
 7317                }
 7318                return true;
 7319            }
 7320        }
 7321
 7322        false
 7323    }
 7324
 7325    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 7326        self.transact(window, cx, |this, window, cx| {
 7327            this.select_all(&SelectAll, window, cx);
 7328            this.insert("", window, cx);
 7329        });
 7330    }
 7331
 7332    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 7333        self.transact(window, cx, |this, window, cx| {
 7334            this.select_autoclose_pair(window, cx);
 7335            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 7336            if !this.linked_edit_ranges.is_empty() {
 7337                let selections = this.selections.all::<MultiBufferPoint>(cx);
 7338                let snapshot = this.buffer.read(cx).snapshot(cx);
 7339
 7340                for selection in selections.iter() {
 7341                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 7342                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 7343                    if selection_start.buffer_id != selection_end.buffer_id {
 7344                        continue;
 7345                    }
 7346                    if let Some(ranges) =
 7347                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 7348                    {
 7349                        for (buffer, entries) in ranges {
 7350                            linked_ranges.entry(buffer).or_default().extend(entries);
 7351                        }
 7352                    }
 7353                }
 7354            }
 7355
 7356            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 7357            if !this.selections.line_mode {
 7358                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 7359                for selection in &mut selections {
 7360                    if selection.is_empty() {
 7361                        let old_head = selection.head();
 7362                        let mut new_head =
 7363                            movement::left(&display_map, old_head.to_display_point(&display_map))
 7364                                .to_point(&display_map);
 7365                        if let Some((buffer, line_buffer_range)) = display_map
 7366                            .buffer_snapshot
 7367                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 7368                        {
 7369                            let indent_size =
 7370                                buffer.indent_size_for_line(line_buffer_range.start.row);
 7371                            let indent_len = match indent_size.kind {
 7372                                IndentKind::Space => {
 7373                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 7374                                }
 7375                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 7376                            };
 7377                            if old_head.column <= indent_size.len && old_head.column > 0 {
 7378                                let indent_len = indent_len.get();
 7379                                new_head = cmp::min(
 7380                                    new_head,
 7381                                    MultiBufferPoint::new(
 7382                                        old_head.row,
 7383                                        ((old_head.column - 1) / indent_len) * indent_len,
 7384                                    ),
 7385                                );
 7386                            }
 7387                        }
 7388
 7389                        selection.set_head(new_head, SelectionGoal::None);
 7390                    }
 7391                }
 7392            }
 7393
 7394            this.signature_help_state.set_backspace_pressed(true);
 7395            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7396                s.select(selections)
 7397            });
 7398            this.insert("", window, cx);
 7399            let empty_str: Arc<str> = Arc::from("");
 7400            for (buffer, edits) in linked_ranges {
 7401                let snapshot = buffer.read(cx).snapshot();
 7402                use text::ToPoint as TP;
 7403
 7404                let edits = edits
 7405                    .into_iter()
 7406                    .map(|range| {
 7407                        let end_point = TP::to_point(&range.end, &snapshot);
 7408                        let mut start_point = TP::to_point(&range.start, &snapshot);
 7409
 7410                        if end_point == start_point {
 7411                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 7412                                .saturating_sub(1);
 7413                            start_point =
 7414                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 7415                        };
 7416
 7417                        (start_point..end_point, empty_str.clone())
 7418                    })
 7419                    .sorted_by_key(|(range, _)| range.start)
 7420                    .collect::<Vec<_>>();
 7421                buffer.update(cx, |this, cx| {
 7422                    this.edit(edits, None, cx);
 7423                })
 7424            }
 7425            this.refresh_inline_completion(true, false, window, cx);
 7426            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 7427        });
 7428    }
 7429
 7430    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 7431        self.transact(window, cx, |this, window, cx| {
 7432            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7433                let line_mode = s.line_mode;
 7434                s.move_with(|map, selection| {
 7435                    if selection.is_empty() && !line_mode {
 7436                        let cursor = movement::right(map, selection.head());
 7437                        selection.end = cursor;
 7438                        selection.reversed = true;
 7439                        selection.goal = SelectionGoal::None;
 7440                    }
 7441                })
 7442            });
 7443            this.insert("", window, cx);
 7444            this.refresh_inline_completion(true, false, window, cx);
 7445        });
 7446    }
 7447
 7448    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 7449        if self.move_to_prev_snippet_tabstop(window, cx) {
 7450            return;
 7451        }
 7452
 7453        self.outdent(&Outdent, window, cx);
 7454    }
 7455
 7456    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 7457        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 7458            return;
 7459        }
 7460
 7461        let mut selections = self.selections.all_adjusted(cx);
 7462        let buffer = self.buffer.read(cx);
 7463        let snapshot = buffer.snapshot(cx);
 7464        let rows_iter = selections.iter().map(|s| s.head().row);
 7465        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 7466
 7467        let mut edits = Vec::new();
 7468        let mut prev_edited_row = 0;
 7469        let mut row_delta = 0;
 7470        for selection in &mut selections {
 7471            if selection.start.row != prev_edited_row {
 7472                row_delta = 0;
 7473            }
 7474            prev_edited_row = selection.end.row;
 7475
 7476            // If the selection is non-empty, then increase the indentation of the selected lines.
 7477            if !selection.is_empty() {
 7478                row_delta =
 7479                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7480                continue;
 7481            }
 7482
 7483            // If the selection is empty and the cursor is in the leading whitespace before the
 7484            // suggested indentation, then auto-indent the line.
 7485            let cursor = selection.head();
 7486            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 7487            if let Some(suggested_indent) =
 7488                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 7489            {
 7490                if cursor.column < suggested_indent.len
 7491                    && cursor.column <= current_indent.len
 7492                    && current_indent.len <= suggested_indent.len
 7493                {
 7494                    selection.start = Point::new(cursor.row, suggested_indent.len);
 7495                    selection.end = selection.start;
 7496                    if row_delta == 0 {
 7497                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 7498                            cursor.row,
 7499                            current_indent,
 7500                            suggested_indent,
 7501                        ));
 7502                        row_delta = suggested_indent.len - current_indent.len;
 7503                    }
 7504                    continue;
 7505                }
 7506            }
 7507
 7508            // Otherwise, insert a hard or soft tab.
 7509            let settings = buffer.language_settings_at(cursor, cx);
 7510            let tab_size = if settings.hard_tabs {
 7511                IndentSize::tab()
 7512            } else {
 7513                let tab_size = settings.tab_size.get();
 7514                let char_column = snapshot
 7515                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 7516                    .flat_map(str::chars)
 7517                    .count()
 7518                    + row_delta as usize;
 7519                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 7520                IndentSize::spaces(chars_to_next_tab_stop)
 7521            };
 7522            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 7523            selection.end = selection.start;
 7524            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 7525            row_delta += tab_size.len;
 7526        }
 7527
 7528        self.transact(window, cx, |this, window, cx| {
 7529            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7530            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7531                s.select(selections)
 7532            });
 7533            this.refresh_inline_completion(true, false, window, cx);
 7534        });
 7535    }
 7536
 7537    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 7538        if self.read_only(cx) {
 7539            return;
 7540        }
 7541        let mut selections = self.selections.all::<Point>(cx);
 7542        let mut prev_edited_row = 0;
 7543        let mut row_delta = 0;
 7544        let mut edits = Vec::new();
 7545        let buffer = self.buffer.read(cx);
 7546        let snapshot = buffer.snapshot(cx);
 7547        for selection in &mut selections {
 7548            if selection.start.row != prev_edited_row {
 7549                row_delta = 0;
 7550            }
 7551            prev_edited_row = selection.end.row;
 7552
 7553            row_delta =
 7554                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7555        }
 7556
 7557        self.transact(window, cx, |this, window, cx| {
 7558            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7559            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7560                s.select(selections)
 7561            });
 7562        });
 7563    }
 7564
 7565    fn indent_selection(
 7566        buffer: &MultiBuffer,
 7567        snapshot: &MultiBufferSnapshot,
 7568        selection: &mut Selection<Point>,
 7569        edits: &mut Vec<(Range<Point>, String)>,
 7570        delta_for_start_row: u32,
 7571        cx: &App,
 7572    ) -> u32 {
 7573        let settings = buffer.language_settings_at(selection.start, cx);
 7574        let tab_size = settings.tab_size.get();
 7575        let indent_kind = if settings.hard_tabs {
 7576            IndentKind::Tab
 7577        } else {
 7578            IndentKind::Space
 7579        };
 7580        let mut start_row = selection.start.row;
 7581        let mut end_row = selection.end.row + 1;
 7582
 7583        // If a selection ends at the beginning of a line, don't indent
 7584        // that last line.
 7585        if selection.end.column == 0 && selection.end.row > selection.start.row {
 7586            end_row -= 1;
 7587        }
 7588
 7589        // Avoid re-indenting a row that has already been indented by a
 7590        // previous selection, but still update this selection's column
 7591        // to reflect that indentation.
 7592        if delta_for_start_row > 0 {
 7593            start_row += 1;
 7594            selection.start.column += delta_for_start_row;
 7595            if selection.end.row == selection.start.row {
 7596                selection.end.column += delta_for_start_row;
 7597            }
 7598        }
 7599
 7600        let mut delta_for_end_row = 0;
 7601        let has_multiple_rows = start_row + 1 != end_row;
 7602        for row in start_row..end_row {
 7603            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 7604            let indent_delta = match (current_indent.kind, indent_kind) {
 7605                (IndentKind::Space, IndentKind::Space) => {
 7606                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 7607                    IndentSize::spaces(columns_to_next_tab_stop)
 7608                }
 7609                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 7610                (_, IndentKind::Tab) => IndentSize::tab(),
 7611            };
 7612
 7613            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 7614                0
 7615            } else {
 7616                selection.start.column
 7617            };
 7618            let row_start = Point::new(row, start);
 7619            edits.push((
 7620                row_start..row_start,
 7621                indent_delta.chars().collect::<String>(),
 7622            ));
 7623
 7624            // Update this selection's endpoints to reflect the indentation.
 7625            if row == selection.start.row {
 7626                selection.start.column += indent_delta.len;
 7627            }
 7628            if row == selection.end.row {
 7629                selection.end.column += indent_delta.len;
 7630                delta_for_end_row = indent_delta.len;
 7631            }
 7632        }
 7633
 7634        if selection.start.row == selection.end.row {
 7635            delta_for_start_row + delta_for_end_row
 7636        } else {
 7637            delta_for_end_row
 7638        }
 7639    }
 7640
 7641    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 7642        if self.read_only(cx) {
 7643            return;
 7644        }
 7645        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7646        let selections = self.selections.all::<Point>(cx);
 7647        let mut deletion_ranges = Vec::new();
 7648        let mut last_outdent = None;
 7649        {
 7650            let buffer = self.buffer.read(cx);
 7651            let snapshot = buffer.snapshot(cx);
 7652            for selection in &selections {
 7653                let settings = buffer.language_settings_at(selection.start, cx);
 7654                let tab_size = settings.tab_size.get();
 7655                let mut rows = selection.spanned_rows(false, &display_map);
 7656
 7657                // Avoid re-outdenting a row that has already been outdented by a
 7658                // previous selection.
 7659                if let Some(last_row) = last_outdent {
 7660                    if last_row == rows.start {
 7661                        rows.start = rows.start.next_row();
 7662                    }
 7663                }
 7664                let has_multiple_rows = rows.len() > 1;
 7665                for row in rows.iter_rows() {
 7666                    let indent_size = snapshot.indent_size_for_line(row);
 7667                    if indent_size.len > 0 {
 7668                        let deletion_len = match indent_size.kind {
 7669                            IndentKind::Space => {
 7670                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 7671                                if columns_to_prev_tab_stop == 0 {
 7672                                    tab_size
 7673                                } else {
 7674                                    columns_to_prev_tab_stop
 7675                                }
 7676                            }
 7677                            IndentKind::Tab => 1,
 7678                        };
 7679                        let start = if has_multiple_rows
 7680                            || deletion_len > selection.start.column
 7681                            || indent_size.len < selection.start.column
 7682                        {
 7683                            0
 7684                        } else {
 7685                            selection.start.column - deletion_len
 7686                        };
 7687                        deletion_ranges.push(
 7688                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 7689                        );
 7690                        last_outdent = Some(row);
 7691                    }
 7692                }
 7693            }
 7694        }
 7695
 7696        self.transact(window, cx, |this, window, cx| {
 7697            this.buffer.update(cx, |buffer, cx| {
 7698                let empty_str: Arc<str> = Arc::default();
 7699                buffer.edit(
 7700                    deletion_ranges
 7701                        .into_iter()
 7702                        .map(|range| (range, empty_str.clone())),
 7703                    None,
 7704                    cx,
 7705                );
 7706            });
 7707            let selections = this.selections.all::<usize>(cx);
 7708            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7709                s.select(selections)
 7710            });
 7711        });
 7712    }
 7713
 7714    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 7715        if self.read_only(cx) {
 7716            return;
 7717        }
 7718        let selections = self
 7719            .selections
 7720            .all::<usize>(cx)
 7721            .into_iter()
 7722            .map(|s| s.range());
 7723
 7724        self.transact(window, cx, |this, window, cx| {
 7725            this.buffer.update(cx, |buffer, cx| {
 7726                buffer.autoindent_ranges(selections, cx);
 7727            });
 7728            let selections = this.selections.all::<usize>(cx);
 7729            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7730                s.select(selections)
 7731            });
 7732        });
 7733    }
 7734
 7735    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 7736        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7737        let selections = self.selections.all::<Point>(cx);
 7738
 7739        let mut new_cursors = Vec::new();
 7740        let mut edit_ranges = Vec::new();
 7741        let mut selections = selections.iter().peekable();
 7742        while let Some(selection) = selections.next() {
 7743            let mut rows = selection.spanned_rows(false, &display_map);
 7744            let goal_display_column = selection.head().to_display_point(&display_map).column();
 7745
 7746            // Accumulate contiguous regions of rows that we want to delete.
 7747            while let Some(next_selection) = selections.peek() {
 7748                let next_rows = next_selection.spanned_rows(false, &display_map);
 7749                if next_rows.start <= rows.end {
 7750                    rows.end = next_rows.end;
 7751                    selections.next().unwrap();
 7752                } else {
 7753                    break;
 7754                }
 7755            }
 7756
 7757            let buffer = &display_map.buffer_snapshot;
 7758            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 7759            let edit_end;
 7760            let cursor_buffer_row;
 7761            if buffer.max_point().row >= rows.end.0 {
 7762                // If there's a line after the range, delete the \n from the end of the row range
 7763                // and position the cursor on the next line.
 7764                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 7765                cursor_buffer_row = rows.end;
 7766            } else {
 7767                // If there isn't a line after the range, delete the \n from the line before the
 7768                // start of the row range and position the cursor there.
 7769                edit_start = edit_start.saturating_sub(1);
 7770                edit_end = buffer.len();
 7771                cursor_buffer_row = rows.start.previous_row();
 7772            }
 7773
 7774            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 7775            *cursor.column_mut() =
 7776                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 7777
 7778            new_cursors.push((
 7779                selection.id,
 7780                buffer.anchor_after(cursor.to_point(&display_map)),
 7781            ));
 7782            edit_ranges.push(edit_start..edit_end);
 7783        }
 7784
 7785        self.transact(window, cx, |this, window, cx| {
 7786            let buffer = this.buffer.update(cx, |buffer, cx| {
 7787                let empty_str: Arc<str> = Arc::default();
 7788                buffer.edit(
 7789                    edit_ranges
 7790                        .into_iter()
 7791                        .map(|range| (range, empty_str.clone())),
 7792                    None,
 7793                    cx,
 7794                );
 7795                buffer.snapshot(cx)
 7796            });
 7797            let new_selections = new_cursors
 7798                .into_iter()
 7799                .map(|(id, cursor)| {
 7800                    let cursor = cursor.to_point(&buffer);
 7801                    Selection {
 7802                        id,
 7803                        start: cursor,
 7804                        end: cursor,
 7805                        reversed: false,
 7806                        goal: SelectionGoal::None,
 7807                    }
 7808                })
 7809                .collect();
 7810
 7811            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7812                s.select(new_selections);
 7813            });
 7814        });
 7815    }
 7816
 7817    pub fn join_lines_impl(
 7818        &mut self,
 7819        insert_whitespace: bool,
 7820        window: &mut Window,
 7821        cx: &mut Context<Self>,
 7822    ) {
 7823        if self.read_only(cx) {
 7824            return;
 7825        }
 7826        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 7827        for selection in self.selections.all::<Point>(cx) {
 7828            let start = MultiBufferRow(selection.start.row);
 7829            // Treat single line selections as if they include the next line. Otherwise this action
 7830            // would do nothing for single line selections individual cursors.
 7831            let end = if selection.start.row == selection.end.row {
 7832                MultiBufferRow(selection.start.row + 1)
 7833            } else {
 7834                MultiBufferRow(selection.end.row)
 7835            };
 7836
 7837            if let Some(last_row_range) = row_ranges.last_mut() {
 7838                if start <= last_row_range.end {
 7839                    last_row_range.end = end;
 7840                    continue;
 7841                }
 7842            }
 7843            row_ranges.push(start..end);
 7844        }
 7845
 7846        let snapshot = self.buffer.read(cx).snapshot(cx);
 7847        let mut cursor_positions = Vec::new();
 7848        for row_range in &row_ranges {
 7849            let anchor = snapshot.anchor_before(Point::new(
 7850                row_range.end.previous_row().0,
 7851                snapshot.line_len(row_range.end.previous_row()),
 7852            ));
 7853            cursor_positions.push(anchor..anchor);
 7854        }
 7855
 7856        self.transact(window, cx, |this, window, cx| {
 7857            for row_range in row_ranges.into_iter().rev() {
 7858                for row in row_range.iter_rows().rev() {
 7859                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 7860                    let next_line_row = row.next_row();
 7861                    let indent = snapshot.indent_size_for_line(next_line_row);
 7862                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 7863
 7864                    let replace =
 7865                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 7866                            " "
 7867                        } else {
 7868                            ""
 7869                        };
 7870
 7871                    this.buffer.update(cx, |buffer, cx| {
 7872                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 7873                    });
 7874                }
 7875            }
 7876
 7877            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7878                s.select_anchor_ranges(cursor_positions)
 7879            });
 7880        });
 7881    }
 7882
 7883    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 7884        self.join_lines_impl(true, window, cx);
 7885    }
 7886
 7887    pub fn sort_lines_case_sensitive(
 7888        &mut self,
 7889        _: &SortLinesCaseSensitive,
 7890        window: &mut Window,
 7891        cx: &mut Context<Self>,
 7892    ) {
 7893        self.manipulate_lines(window, cx, |lines| lines.sort())
 7894    }
 7895
 7896    pub fn sort_lines_case_insensitive(
 7897        &mut self,
 7898        _: &SortLinesCaseInsensitive,
 7899        window: &mut Window,
 7900        cx: &mut Context<Self>,
 7901    ) {
 7902        self.manipulate_lines(window, cx, |lines| {
 7903            lines.sort_by_key(|line| line.to_lowercase())
 7904        })
 7905    }
 7906
 7907    pub fn unique_lines_case_insensitive(
 7908        &mut self,
 7909        _: &UniqueLinesCaseInsensitive,
 7910        window: &mut Window,
 7911        cx: &mut Context<Self>,
 7912    ) {
 7913        self.manipulate_lines(window, cx, |lines| {
 7914            let mut seen = HashSet::default();
 7915            lines.retain(|line| seen.insert(line.to_lowercase()));
 7916        })
 7917    }
 7918
 7919    pub fn unique_lines_case_sensitive(
 7920        &mut self,
 7921        _: &UniqueLinesCaseSensitive,
 7922        window: &mut Window,
 7923        cx: &mut Context<Self>,
 7924    ) {
 7925        self.manipulate_lines(window, cx, |lines| {
 7926            let mut seen = HashSet::default();
 7927            lines.retain(|line| seen.insert(*line));
 7928        })
 7929    }
 7930
 7931    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 7932        let Some(project) = self.project.clone() else {
 7933            return;
 7934        };
 7935        self.reload(project, window, cx)
 7936            .detach_and_notify_err(window, cx);
 7937    }
 7938
 7939    pub fn restore_file(
 7940        &mut self,
 7941        _: &::git::RestoreFile,
 7942        window: &mut Window,
 7943        cx: &mut Context<Self>,
 7944    ) {
 7945        let mut buffer_ids = HashSet::default();
 7946        let snapshot = self.buffer().read(cx).snapshot(cx);
 7947        for selection in self.selections.all::<usize>(cx) {
 7948            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 7949        }
 7950
 7951        let buffer = self.buffer().read(cx);
 7952        let ranges = buffer_ids
 7953            .into_iter()
 7954            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 7955            .collect::<Vec<_>>();
 7956
 7957        self.restore_hunks_in_ranges(ranges, window, cx);
 7958    }
 7959
 7960    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 7961        let selections = self
 7962            .selections
 7963            .all(cx)
 7964            .into_iter()
 7965            .map(|s| s.range())
 7966            .collect();
 7967        self.restore_hunks_in_ranges(selections, window, cx);
 7968    }
 7969
 7970    fn restore_hunks_in_ranges(
 7971        &mut self,
 7972        ranges: Vec<Range<Point>>,
 7973        window: &mut Window,
 7974        cx: &mut Context<Editor>,
 7975    ) {
 7976        let mut revert_changes = HashMap::default();
 7977        let chunk_by = self
 7978            .snapshot(window, cx)
 7979            .hunks_for_ranges(ranges)
 7980            .into_iter()
 7981            .chunk_by(|hunk| hunk.buffer_id);
 7982        for (buffer_id, hunks) in &chunk_by {
 7983            let hunks = hunks.collect::<Vec<_>>();
 7984            for hunk in &hunks {
 7985                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 7986            }
 7987            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
 7988        }
 7989        drop(chunk_by);
 7990        if !revert_changes.is_empty() {
 7991            self.transact(window, cx, |editor, window, cx| {
 7992                editor.restore(revert_changes, window, cx);
 7993            });
 7994        }
 7995    }
 7996
 7997    pub fn open_active_item_in_terminal(
 7998        &mut self,
 7999        _: &OpenInTerminal,
 8000        window: &mut Window,
 8001        cx: &mut Context<Self>,
 8002    ) {
 8003        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 8004            let project_path = buffer.read(cx).project_path(cx)?;
 8005            let project = self.project.as_ref()?.read(cx);
 8006            let entry = project.entry_for_path(&project_path, cx)?;
 8007            let parent = match &entry.canonical_path {
 8008                Some(canonical_path) => canonical_path.to_path_buf(),
 8009                None => project.absolute_path(&project_path, cx)?,
 8010            }
 8011            .parent()?
 8012            .to_path_buf();
 8013            Some(parent)
 8014        }) {
 8015            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 8016        }
 8017    }
 8018
 8019    pub fn prepare_restore_change(
 8020        &self,
 8021        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 8022        hunk: &MultiBufferDiffHunk,
 8023        cx: &mut App,
 8024    ) -> Option<()> {
 8025        if hunk.is_created_file() {
 8026            return None;
 8027        }
 8028        let buffer = self.buffer.read(cx);
 8029        let diff = buffer.diff_for(hunk.buffer_id)?;
 8030        let buffer = buffer.buffer(hunk.buffer_id)?;
 8031        let buffer = buffer.read(cx);
 8032        let original_text = diff
 8033            .read(cx)
 8034            .base_text()
 8035            .as_rope()
 8036            .slice(hunk.diff_base_byte_range.clone());
 8037        let buffer_snapshot = buffer.snapshot();
 8038        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 8039        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 8040            probe
 8041                .0
 8042                .start
 8043                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 8044                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 8045        }) {
 8046            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 8047            Some(())
 8048        } else {
 8049            None
 8050        }
 8051    }
 8052
 8053    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 8054        self.manipulate_lines(window, cx, |lines| lines.reverse())
 8055    }
 8056
 8057    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 8058        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 8059    }
 8060
 8061    fn manipulate_lines<Fn>(
 8062        &mut self,
 8063        window: &mut Window,
 8064        cx: &mut Context<Self>,
 8065        mut callback: Fn,
 8066    ) where
 8067        Fn: FnMut(&mut Vec<&str>),
 8068    {
 8069        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8070        let buffer = self.buffer.read(cx).snapshot(cx);
 8071
 8072        let mut edits = Vec::new();
 8073
 8074        let selections = self.selections.all::<Point>(cx);
 8075        let mut selections = selections.iter().peekable();
 8076        let mut contiguous_row_selections = Vec::new();
 8077        let mut new_selections = Vec::new();
 8078        let mut added_lines = 0;
 8079        let mut removed_lines = 0;
 8080
 8081        while let Some(selection) = selections.next() {
 8082            let (start_row, end_row) = consume_contiguous_rows(
 8083                &mut contiguous_row_selections,
 8084                selection,
 8085                &display_map,
 8086                &mut selections,
 8087            );
 8088
 8089            let start_point = Point::new(start_row.0, 0);
 8090            let end_point = Point::new(
 8091                end_row.previous_row().0,
 8092                buffer.line_len(end_row.previous_row()),
 8093            );
 8094            let text = buffer
 8095                .text_for_range(start_point..end_point)
 8096                .collect::<String>();
 8097
 8098            let mut lines = text.split('\n').collect_vec();
 8099
 8100            let lines_before = lines.len();
 8101            callback(&mut lines);
 8102            let lines_after = lines.len();
 8103
 8104            edits.push((start_point..end_point, lines.join("\n")));
 8105
 8106            // Selections must change based on added and removed line count
 8107            let start_row =
 8108                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 8109            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 8110            new_selections.push(Selection {
 8111                id: selection.id,
 8112                start: start_row,
 8113                end: end_row,
 8114                goal: SelectionGoal::None,
 8115                reversed: selection.reversed,
 8116            });
 8117
 8118            if lines_after > lines_before {
 8119                added_lines += lines_after - lines_before;
 8120            } else if lines_before > lines_after {
 8121                removed_lines += lines_before - lines_after;
 8122            }
 8123        }
 8124
 8125        self.transact(window, cx, |this, window, cx| {
 8126            let buffer = this.buffer.update(cx, |buffer, cx| {
 8127                buffer.edit(edits, None, cx);
 8128                buffer.snapshot(cx)
 8129            });
 8130
 8131            // Recalculate offsets on newly edited buffer
 8132            let new_selections = new_selections
 8133                .iter()
 8134                .map(|s| {
 8135                    let start_point = Point::new(s.start.0, 0);
 8136                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 8137                    Selection {
 8138                        id: s.id,
 8139                        start: buffer.point_to_offset(start_point),
 8140                        end: buffer.point_to_offset(end_point),
 8141                        goal: s.goal,
 8142                        reversed: s.reversed,
 8143                    }
 8144                })
 8145                .collect();
 8146
 8147            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8148                s.select(new_selections);
 8149            });
 8150
 8151            this.request_autoscroll(Autoscroll::fit(), cx);
 8152        });
 8153    }
 8154
 8155    pub fn convert_to_upper_case(
 8156        &mut self,
 8157        _: &ConvertToUpperCase,
 8158        window: &mut Window,
 8159        cx: &mut Context<Self>,
 8160    ) {
 8161        self.manipulate_text(window, cx, |text| text.to_uppercase())
 8162    }
 8163
 8164    pub fn convert_to_lower_case(
 8165        &mut self,
 8166        _: &ConvertToLowerCase,
 8167        window: &mut Window,
 8168        cx: &mut Context<Self>,
 8169    ) {
 8170        self.manipulate_text(window, cx, |text| text.to_lowercase())
 8171    }
 8172
 8173    pub fn convert_to_title_case(
 8174        &mut self,
 8175        _: &ConvertToTitleCase,
 8176        window: &mut Window,
 8177        cx: &mut Context<Self>,
 8178    ) {
 8179        self.manipulate_text(window, cx, |text| {
 8180            text.split('\n')
 8181                .map(|line| line.to_case(Case::Title))
 8182                .join("\n")
 8183        })
 8184    }
 8185
 8186    pub fn convert_to_snake_case(
 8187        &mut self,
 8188        _: &ConvertToSnakeCase,
 8189        window: &mut Window,
 8190        cx: &mut Context<Self>,
 8191    ) {
 8192        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 8193    }
 8194
 8195    pub fn convert_to_kebab_case(
 8196        &mut self,
 8197        _: &ConvertToKebabCase,
 8198        window: &mut Window,
 8199        cx: &mut Context<Self>,
 8200    ) {
 8201        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 8202    }
 8203
 8204    pub fn convert_to_upper_camel_case(
 8205        &mut self,
 8206        _: &ConvertToUpperCamelCase,
 8207        window: &mut Window,
 8208        cx: &mut Context<Self>,
 8209    ) {
 8210        self.manipulate_text(window, cx, |text| {
 8211            text.split('\n')
 8212                .map(|line| line.to_case(Case::UpperCamel))
 8213                .join("\n")
 8214        })
 8215    }
 8216
 8217    pub fn convert_to_lower_camel_case(
 8218        &mut self,
 8219        _: &ConvertToLowerCamelCase,
 8220        window: &mut Window,
 8221        cx: &mut Context<Self>,
 8222    ) {
 8223        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 8224    }
 8225
 8226    pub fn convert_to_opposite_case(
 8227        &mut self,
 8228        _: &ConvertToOppositeCase,
 8229        window: &mut Window,
 8230        cx: &mut Context<Self>,
 8231    ) {
 8232        self.manipulate_text(window, cx, |text| {
 8233            text.chars()
 8234                .fold(String::with_capacity(text.len()), |mut t, c| {
 8235                    if c.is_uppercase() {
 8236                        t.extend(c.to_lowercase());
 8237                    } else {
 8238                        t.extend(c.to_uppercase());
 8239                    }
 8240                    t
 8241                })
 8242        })
 8243    }
 8244
 8245    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 8246    where
 8247        Fn: FnMut(&str) -> String,
 8248    {
 8249        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8250        let buffer = self.buffer.read(cx).snapshot(cx);
 8251
 8252        let mut new_selections = Vec::new();
 8253        let mut edits = Vec::new();
 8254        let mut selection_adjustment = 0i32;
 8255
 8256        for selection in self.selections.all::<usize>(cx) {
 8257            let selection_is_empty = selection.is_empty();
 8258
 8259            let (start, end) = if selection_is_empty {
 8260                let word_range = movement::surrounding_word(
 8261                    &display_map,
 8262                    selection.start.to_display_point(&display_map),
 8263                );
 8264                let start = word_range.start.to_offset(&display_map, Bias::Left);
 8265                let end = word_range.end.to_offset(&display_map, Bias::Left);
 8266                (start, end)
 8267            } else {
 8268                (selection.start, selection.end)
 8269            };
 8270
 8271            let text = buffer.text_for_range(start..end).collect::<String>();
 8272            let old_length = text.len() as i32;
 8273            let text = callback(&text);
 8274
 8275            new_selections.push(Selection {
 8276                start: (start as i32 - selection_adjustment) as usize,
 8277                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 8278                goal: SelectionGoal::None,
 8279                ..selection
 8280            });
 8281
 8282            selection_adjustment += old_length - text.len() as i32;
 8283
 8284            edits.push((start..end, text));
 8285        }
 8286
 8287        self.transact(window, cx, |this, window, cx| {
 8288            this.buffer.update(cx, |buffer, cx| {
 8289                buffer.edit(edits, None, cx);
 8290            });
 8291
 8292            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8293                s.select(new_selections);
 8294            });
 8295
 8296            this.request_autoscroll(Autoscroll::fit(), cx);
 8297        });
 8298    }
 8299
 8300    pub fn duplicate(
 8301        &mut self,
 8302        upwards: bool,
 8303        whole_lines: bool,
 8304        window: &mut Window,
 8305        cx: &mut Context<Self>,
 8306    ) {
 8307        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8308        let buffer = &display_map.buffer_snapshot;
 8309        let selections = self.selections.all::<Point>(cx);
 8310
 8311        let mut edits = Vec::new();
 8312        let mut selections_iter = selections.iter().peekable();
 8313        while let Some(selection) = selections_iter.next() {
 8314            let mut rows = selection.spanned_rows(false, &display_map);
 8315            // duplicate line-wise
 8316            if whole_lines || selection.start == selection.end {
 8317                // Avoid duplicating the same lines twice.
 8318                while let Some(next_selection) = selections_iter.peek() {
 8319                    let next_rows = next_selection.spanned_rows(false, &display_map);
 8320                    if next_rows.start < rows.end {
 8321                        rows.end = next_rows.end;
 8322                        selections_iter.next().unwrap();
 8323                    } else {
 8324                        break;
 8325                    }
 8326                }
 8327
 8328                // Copy the text from the selected row region and splice it either at the start
 8329                // or end of the region.
 8330                let start = Point::new(rows.start.0, 0);
 8331                let end = Point::new(
 8332                    rows.end.previous_row().0,
 8333                    buffer.line_len(rows.end.previous_row()),
 8334                );
 8335                let text = buffer
 8336                    .text_for_range(start..end)
 8337                    .chain(Some("\n"))
 8338                    .collect::<String>();
 8339                let insert_location = if upwards {
 8340                    Point::new(rows.end.0, 0)
 8341                } else {
 8342                    start
 8343                };
 8344                edits.push((insert_location..insert_location, text));
 8345            } else {
 8346                // duplicate character-wise
 8347                let start = selection.start;
 8348                let end = selection.end;
 8349                let text = buffer.text_for_range(start..end).collect::<String>();
 8350                edits.push((selection.end..selection.end, text));
 8351            }
 8352        }
 8353
 8354        self.transact(window, cx, |this, _, cx| {
 8355            this.buffer.update(cx, |buffer, cx| {
 8356                buffer.edit(edits, None, cx);
 8357            });
 8358
 8359            this.request_autoscroll(Autoscroll::fit(), cx);
 8360        });
 8361    }
 8362
 8363    pub fn duplicate_line_up(
 8364        &mut self,
 8365        _: &DuplicateLineUp,
 8366        window: &mut Window,
 8367        cx: &mut Context<Self>,
 8368    ) {
 8369        self.duplicate(true, true, window, cx);
 8370    }
 8371
 8372    pub fn duplicate_line_down(
 8373        &mut self,
 8374        _: &DuplicateLineDown,
 8375        window: &mut Window,
 8376        cx: &mut Context<Self>,
 8377    ) {
 8378        self.duplicate(false, true, window, cx);
 8379    }
 8380
 8381    pub fn duplicate_selection(
 8382        &mut self,
 8383        _: &DuplicateSelection,
 8384        window: &mut Window,
 8385        cx: &mut Context<Self>,
 8386    ) {
 8387        self.duplicate(false, false, window, cx);
 8388    }
 8389
 8390    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 8391        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8392        let buffer = self.buffer.read(cx).snapshot(cx);
 8393
 8394        let mut edits = Vec::new();
 8395        let mut unfold_ranges = Vec::new();
 8396        let mut refold_creases = Vec::new();
 8397
 8398        let selections = self.selections.all::<Point>(cx);
 8399        let mut selections = selections.iter().peekable();
 8400        let mut contiguous_row_selections = Vec::new();
 8401        let mut new_selections = Vec::new();
 8402
 8403        while let Some(selection) = selections.next() {
 8404            // Find all the selections that span a contiguous row range
 8405            let (start_row, end_row) = consume_contiguous_rows(
 8406                &mut contiguous_row_selections,
 8407                selection,
 8408                &display_map,
 8409                &mut selections,
 8410            );
 8411
 8412            // Move the text spanned by the row range to be before the line preceding the row range
 8413            if start_row.0 > 0 {
 8414                let range_to_move = Point::new(
 8415                    start_row.previous_row().0,
 8416                    buffer.line_len(start_row.previous_row()),
 8417                )
 8418                    ..Point::new(
 8419                        end_row.previous_row().0,
 8420                        buffer.line_len(end_row.previous_row()),
 8421                    );
 8422                let insertion_point = display_map
 8423                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 8424                    .0;
 8425
 8426                // Don't move lines across excerpts
 8427                if buffer
 8428                    .excerpt_containing(insertion_point..range_to_move.end)
 8429                    .is_some()
 8430                {
 8431                    let text = buffer
 8432                        .text_for_range(range_to_move.clone())
 8433                        .flat_map(|s| s.chars())
 8434                        .skip(1)
 8435                        .chain(['\n'])
 8436                        .collect::<String>();
 8437
 8438                    edits.push((
 8439                        buffer.anchor_after(range_to_move.start)
 8440                            ..buffer.anchor_before(range_to_move.end),
 8441                        String::new(),
 8442                    ));
 8443                    let insertion_anchor = buffer.anchor_after(insertion_point);
 8444                    edits.push((insertion_anchor..insertion_anchor, text));
 8445
 8446                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 8447
 8448                    // Move selections up
 8449                    new_selections.extend(contiguous_row_selections.drain(..).map(
 8450                        |mut selection| {
 8451                            selection.start.row -= row_delta;
 8452                            selection.end.row -= row_delta;
 8453                            selection
 8454                        },
 8455                    ));
 8456
 8457                    // Move folds up
 8458                    unfold_ranges.push(range_to_move.clone());
 8459                    for fold in display_map.folds_in_range(
 8460                        buffer.anchor_before(range_to_move.start)
 8461                            ..buffer.anchor_after(range_to_move.end),
 8462                    ) {
 8463                        let mut start = fold.range.start.to_point(&buffer);
 8464                        let mut end = fold.range.end.to_point(&buffer);
 8465                        start.row -= row_delta;
 8466                        end.row -= row_delta;
 8467                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 8468                    }
 8469                }
 8470            }
 8471
 8472            // If we didn't move line(s), preserve the existing selections
 8473            new_selections.append(&mut contiguous_row_selections);
 8474        }
 8475
 8476        self.transact(window, cx, |this, window, cx| {
 8477            this.unfold_ranges(&unfold_ranges, true, true, cx);
 8478            this.buffer.update(cx, |buffer, cx| {
 8479                for (range, text) in edits {
 8480                    buffer.edit([(range, text)], None, cx);
 8481                }
 8482            });
 8483            this.fold_creases(refold_creases, true, window, cx);
 8484            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8485                s.select(new_selections);
 8486            })
 8487        });
 8488    }
 8489
 8490    pub fn move_line_down(
 8491        &mut self,
 8492        _: &MoveLineDown,
 8493        window: &mut Window,
 8494        cx: &mut Context<Self>,
 8495    ) {
 8496        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8497        let buffer = self.buffer.read(cx).snapshot(cx);
 8498
 8499        let mut edits = Vec::new();
 8500        let mut unfold_ranges = Vec::new();
 8501        let mut refold_creases = Vec::new();
 8502
 8503        let selections = self.selections.all::<Point>(cx);
 8504        let mut selections = selections.iter().peekable();
 8505        let mut contiguous_row_selections = Vec::new();
 8506        let mut new_selections = Vec::new();
 8507
 8508        while let Some(selection) = selections.next() {
 8509            // Find all the selections that span a contiguous row range
 8510            let (start_row, end_row) = consume_contiguous_rows(
 8511                &mut contiguous_row_selections,
 8512                selection,
 8513                &display_map,
 8514                &mut selections,
 8515            );
 8516
 8517            // Move the text spanned by the row range to be after the last line of the row range
 8518            if end_row.0 <= buffer.max_point().row {
 8519                let range_to_move =
 8520                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 8521                let insertion_point = display_map
 8522                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 8523                    .0;
 8524
 8525                // Don't move lines across excerpt boundaries
 8526                if buffer
 8527                    .excerpt_containing(range_to_move.start..insertion_point)
 8528                    .is_some()
 8529                {
 8530                    let mut text = String::from("\n");
 8531                    text.extend(buffer.text_for_range(range_to_move.clone()));
 8532                    text.pop(); // Drop trailing newline
 8533                    edits.push((
 8534                        buffer.anchor_after(range_to_move.start)
 8535                            ..buffer.anchor_before(range_to_move.end),
 8536                        String::new(),
 8537                    ));
 8538                    let insertion_anchor = buffer.anchor_after(insertion_point);
 8539                    edits.push((insertion_anchor..insertion_anchor, text));
 8540
 8541                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 8542
 8543                    // Move selections down
 8544                    new_selections.extend(contiguous_row_selections.drain(..).map(
 8545                        |mut selection| {
 8546                            selection.start.row += row_delta;
 8547                            selection.end.row += row_delta;
 8548                            selection
 8549                        },
 8550                    ));
 8551
 8552                    // Move folds down
 8553                    unfold_ranges.push(range_to_move.clone());
 8554                    for fold in display_map.folds_in_range(
 8555                        buffer.anchor_before(range_to_move.start)
 8556                            ..buffer.anchor_after(range_to_move.end),
 8557                    ) {
 8558                        let mut start = fold.range.start.to_point(&buffer);
 8559                        let mut end = fold.range.end.to_point(&buffer);
 8560                        start.row += row_delta;
 8561                        end.row += row_delta;
 8562                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 8563                    }
 8564                }
 8565            }
 8566
 8567            // If we didn't move line(s), preserve the existing selections
 8568            new_selections.append(&mut contiguous_row_selections);
 8569        }
 8570
 8571        self.transact(window, cx, |this, window, cx| {
 8572            this.unfold_ranges(&unfold_ranges, true, true, cx);
 8573            this.buffer.update(cx, |buffer, cx| {
 8574                for (range, text) in edits {
 8575                    buffer.edit([(range, text)], None, cx);
 8576                }
 8577            });
 8578            this.fold_creases(refold_creases, true, window, cx);
 8579            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8580                s.select(new_selections)
 8581            });
 8582        });
 8583    }
 8584
 8585    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 8586        let text_layout_details = &self.text_layout_details(window);
 8587        self.transact(window, cx, |this, window, cx| {
 8588            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8589                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 8590                let line_mode = s.line_mode;
 8591                s.move_with(|display_map, selection| {
 8592                    if !selection.is_empty() || line_mode {
 8593                        return;
 8594                    }
 8595
 8596                    let mut head = selection.head();
 8597                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 8598                    if head.column() == display_map.line_len(head.row()) {
 8599                        transpose_offset = display_map
 8600                            .buffer_snapshot
 8601                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 8602                    }
 8603
 8604                    if transpose_offset == 0 {
 8605                        return;
 8606                    }
 8607
 8608                    *head.column_mut() += 1;
 8609                    head = display_map.clip_point(head, Bias::Right);
 8610                    let goal = SelectionGoal::HorizontalPosition(
 8611                        display_map
 8612                            .x_for_display_point(head, text_layout_details)
 8613                            .into(),
 8614                    );
 8615                    selection.collapse_to(head, goal);
 8616
 8617                    let transpose_start = display_map
 8618                        .buffer_snapshot
 8619                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 8620                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 8621                        let transpose_end = display_map
 8622                            .buffer_snapshot
 8623                            .clip_offset(transpose_offset + 1, Bias::Right);
 8624                        if let Some(ch) =
 8625                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 8626                        {
 8627                            edits.push((transpose_start..transpose_offset, String::new()));
 8628                            edits.push((transpose_end..transpose_end, ch.to_string()));
 8629                        }
 8630                    }
 8631                });
 8632                edits
 8633            });
 8634            this.buffer
 8635                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 8636            let selections = this.selections.all::<usize>(cx);
 8637            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8638                s.select(selections);
 8639            });
 8640        });
 8641    }
 8642
 8643    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 8644        self.rewrap_impl(false, cx)
 8645    }
 8646
 8647    pub fn rewrap_impl(&mut self, override_language_settings: bool, cx: &mut Context<Self>) {
 8648        let buffer = self.buffer.read(cx).snapshot(cx);
 8649        let selections = self.selections.all::<Point>(cx);
 8650        let mut selections = selections.iter().peekable();
 8651
 8652        let mut edits = Vec::new();
 8653        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 8654
 8655        while let Some(selection) = selections.next() {
 8656            let mut start_row = selection.start.row;
 8657            let mut end_row = selection.end.row;
 8658
 8659            // Skip selections that overlap with a range that has already been rewrapped.
 8660            let selection_range = start_row..end_row;
 8661            if rewrapped_row_ranges
 8662                .iter()
 8663                .any(|range| range.overlaps(&selection_range))
 8664            {
 8665                continue;
 8666            }
 8667
 8668            let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
 8669
 8670            // Since not all lines in the selection may be at the same indent
 8671            // level, choose the indent size that is the most common between all
 8672            // of the lines.
 8673            //
 8674            // If there is a tie, we use the deepest indent.
 8675            let (indent_size, indent_end) = {
 8676                let mut indent_size_occurrences = HashMap::default();
 8677                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 8678
 8679                for row in start_row..=end_row {
 8680                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 8681                    rows_by_indent_size.entry(indent).or_default().push(row);
 8682                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 8683                }
 8684
 8685                let indent_size = indent_size_occurrences
 8686                    .into_iter()
 8687                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 8688                    .map(|(indent, _)| indent)
 8689                    .unwrap_or_default();
 8690                let row = rows_by_indent_size[&indent_size][0];
 8691                let indent_end = Point::new(row, indent_size.len);
 8692
 8693                (indent_size, indent_end)
 8694            };
 8695
 8696            let mut line_prefix = indent_size.chars().collect::<String>();
 8697
 8698            let mut inside_comment = false;
 8699            if let Some(comment_prefix) =
 8700                buffer
 8701                    .language_scope_at(selection.head())
 8702                    .and_then(|language| {
 8703                        language
 8704                            .line_comment_prefixes()
 8705                            .iter()
 8706                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 8707                            .cloned()
 8708                    })
 8709            {
 8710                line_prefix.push_str(&comment_prefix);
 8711                inside_comment = true;
 8712            }
 8713
 8714            let language_settings = buffer.language_settings_at(selection.head(), cx);
 8715            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 8716                RewrapBehavior::InComments => inside_comment,
 8717                RewrapBehavior::InSelections => !selection.is_empty(),
 8718                RewrapBehavior::Anywhere => true,
 8719            };
 8720
 8721            let should_rewrap = override_language_settings
 8722                || allow_rewrap_based_on_language
 8723                || self.hard_wrap.is_some();
 8724            if !should_rewrap {
 8725                continue;
 8726            }
 8727
 8728            if selection.is_empty() {
 8729                'expand_upwards: while start_row > 0 {
 8730                    let prev_row = start_row - 1;
 8731                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 8732                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 8733                    {
 8734                        start_row = prev_row;
 8735                    } else {
 8736                        break 'expand_upwards;
 8737                    }
 8738                }
 8739
 8740                'expand_downwards: while end_row < buffer.max_point().row {
 8741                    let next_row = end_row + 1;
 8742                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 8743                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 8744                    {
 8745                        end_row = next_row;
 8746                    } else {
 8747                        break 'expand_downwards;
 8748                    }
 8749                }
 8750            }
 8751
 8752            let start = Point::new(start_row, 0);
 8753            let start_offset = start.to_offset(&buffer);
 8754            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 8755            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 8756            let Some(lines_without_prefixes) = selection_text
 8757                .lines()
 8758                .map(|line| {
 8759                    line.strip_prefix(&line_prefix)
 8760                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 8761                        .ok_or_else(|| {
 8762                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 8763                        })
 8764                })
 8765                .collect::<Result<Vec<_>, _>>()
 8766                .log_err()
 8767            else {
 8768                continue;
 8769            };
 8770
 8771            let wrap_column = self.hard_wrap.unwrap_or_else(|| {
 8772                buffer
 8773                    .language_settings_at(Point::new(start_row, 0), cx)
 8774                    .preferred_line_length as usize
 8775            });
 8776            let wrapped_text = wrap_with_prefix(
 8777                line_prefix,
 8778                lines_without_prefixes.join(" "),
 8779                wrap_column,
 8780                tab_size,
 8781            );
 8782
 8783            // TODO: should always use char-based diff while still supporting cursor behavior that
 8784            // matches vim.
 8785            let mut diff_options = DiffOptions::default();
 8786            if override_language_settings {
 8787                diff_options.max_word_diff_len = 0;
 8788                diff_options.max_word_diff_line_count = 0;
 8789            } else {
 8790                diff_options.max_word_diff_len = usize::MAX;
 8791                diff_options.max_word_diff_line_count = usize::MAX;
 8792            }
 8793
 8794            for (old_range, new_text) in
 8795                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
 8796            {
 8797                let edit_start = buffer.anchor_after(start_offset + old_range.start);
 8798                let edit_end = buffer.anchor_after(start_offset + old_range.end);
 8799                edits.push((edit_start..edit_end, new_text));
 8800            }
 8801
 8802            rewrapped_row_ranges.push(start_row..=end_row);
 8803        }
 8804
 8805        self.buffer
 8806            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 8807    }
 8808
 8809    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 8810        let mut text = String::new();
 8811        let buffer = self.buffer.read(cx).snapshot(cx);
 8812        let mut selections = self.selections.all::<Point>(cx);
 8813        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8814        {
 8815            let max_point = buffer.max_point();
 8816            let mut is_first = true;
 8817            for selection in &mut selections {
 8818                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8819                if is_entire_line {
 8820                    selection.start = Point::new(selection.start.row, 0);
 8821                    if !selection.is_empty() && selection.end.column == 0 {
 8822                        selection.end = cmp::min(max_point, selection.end);
 8823                    } else {
 8824                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 8825                    }
 8826                    selection.goal = SelectionGoal::None;
 8827                }
 8828                if is_first {
 8829                    is_first = false;
 8830                } else {
 8831                    text += "\n";
 8832                }
 8833                let mut len = 0;
 8834                for chunk in buffer.text_for_range(selection.start..selection.end) {
 8835                    text.push_str(chunk);
 8836                    len += chunk.len();
 8837                }
 8838                clipboard_selections.push(ClipboardSelection {
 8839                    len,
 8840                    is_entire_line,
 8841                    first_line_indent: buffer
 8842                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 8843                        .len,
 8844                });
 8845            }
 8846        }
 8847
 8848        self.transact(window, cx, |this, window, cx| {
 8849            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8850                s.select(selections);
 8851            });
 8852            this.insert("", window, cx);
 8853        });
 8854        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 8855    }
 8856
 8857    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 8858        let item = self.cut_common(window, cx);
 8859        cx.write_to_clipboard(item);
 8860    }
 8861
 8862    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 8863        self.change_selections(None, window, cx, |s| {
 8864            s.move_with(|snapshot, sel| {
 8865                if sel.is_empty() {
 8866                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 8867                }
 8868            });
 8869        });
 8870        let item = self.cut_common(window, cx);
 8871        cx.set_global(KillRing(item))
 8872    }
 8873
 8874    pub fn kill_ring_yank(
 8875        &mut self,
 8876        _: &KillRingYank,
 8877        window: &mut Window,
 8878        cx: &mut Context<Self>,
 8879    ) {
 8880        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 8881            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 8882                (kill_ring.text().to_string(), kill_ring.metadata_json())
 8883            } else {
 8884                return;
 8885            }
 8886        } else {
 8887            return;
 8888        };
 8889        self.do_paste(&text, metadata, false, window, cx);
 8890    }
 8891
 8892    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 8893        let selections = self.selections.all::<Point>(cx);
 8894        let buffer = self.buffer.read(cx).read(cx);
 8895        let mut text = String::new();
 8896
 8897        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8898        {
 8899            let max_point = buffer.max_point();
 8900            let mut is_first = true;
 8901            for selection in selections.iter() {
 8902                let mut start = selection.start;
 8903                let mut end = selection.end;
 8904                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8905                if is_entire_line {
 8906                    start = Point::new(start.row, 0);
 8907                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 8908                }
 8909                if is_first {
 8910                    is_first = false;
 8911                } else {
 8912                    text += "\n";
 8913                }
 8914                let mut len = 0;
 8915                for chunk in buffer.text_for_range(start..end) {
 8916                    text.push_str(chunk);
 8917                    len += chunk.len();
 8918                }
 8919                clipboard_selections.push(ClipboardSelection {
 8920                    len,
 8921                    is_entire_line,
 8922                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 8923                });
 8924            }
 8925        }
 8926
 8927        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 8928            text,
 8929            clipboard_selections,
 8930        ));
 8931    }
 8932
 8933    pub fn do_paste(
 8934        &mut self,
 8935        text: &String,
 8936        clipboard_selections: Option<Vec<ClipboardSelection>>,
 8937        handle_entire_lines: bool,
 8938        window: &mut Window,
 8939        cx: &mut Context<Self>,
 8940    ) {
 8941        if self.read_only(cx) {
 8942            return;
 8943        }
 8944
 8945        let clipboard_text = Cow::Borrowed(text);
 8946
 8947        self.transact(window, cx, |this, window, cx| {
 8948            if let Some(mut clipboard_selections) = clipboard_selections {
 8949                let old_selections = this.selections.all::<usize>(cx);
 8950                let all_selections_were_entire_line =
 8951                    clipboard_selections.iter().all(|s| s.is_entire_line);
 8952                let first_selection_indent_column =
 8953                    clipboard_selections.first().map(|s| s.first_line_indent);
 8954                if clipboard_selections.len() != old_selections.len() {
 8955                    clipboard_selections.drain(..);
 8956                }
 8957                let cursor_offset = this.selections.last::<usize>(cx).head();
 8958                let mut auto_indent_on_paste = true;
 8959
 8960                this.buffer.update(cx, |buffer, cx| {
 8961                    let snapshot = buffer.read(cx);
 8962                    auto_indent_on_paste = snapshot
 8963                        .language_settings_at(cursor_offset, cx)
 8964                        .auto_indent_on_paste;
 8965
 8966                    let mut start_offset = 0;
 8967                    let mut edits = Vec::new();
 8968                    let mut original_indent_columns = Vec::new();
 8969                    for (ix, selection) in old_selections.iter().enumerate() {
 8970                        let to_insert;
 8971                        let entire_line;
 8972                        let original_indent_column;
 8973                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 8974                            let end_offset = start_offset + clipboard_selection.len;
 8975                            to_insert = &clipboard_text[start_offset..end_offset];
 8976                            entire_line = clipboard_selection.is_entire_line;
 8977                            start_offset = end_offset + 1;
 8978                            original_indent_column = Some(clipboard_selection.first_line_indent);
 8979                        } else {
 8980                            to_insert = clipboard_text.as_str();
 8981                            entire_line = all_selections_were_entire_line;
 8982                            original_indent_column = first_selection_indent_column
 8983                        }
 8984
 8985                        // If the corresponding selection was empty when this slice of the
 8986                        // clipboard text was written, then the entire line containing the
 8987                        // selection was copied. If this selection is also currently empty,
 8988                        // then paste the line before the current line of the buffer.
 8989                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 8990                            let column = selection.start.to_point(&snapshot).column as usize;
 8991                            let line_start = selection.start - column;
 8992                            line_start..line_start
 8993                        } else {
 8994                            selection.range()
 8995                        };
 8996
 8997                        edits.push((range, to_insert));
 8998                        original_indent_columns.push(original_indent_column);
 8999                    }
 9000                    drop(snapshot);
 9001
 9002                    buffer.edit(
 9003                        edits,
 9004                        if auto_indent_on_paste {
 9005                            Some(AutoindentMode::Block {
 9006                                original_indent_columns,
 9007                            })
 9008                        } else {
 9009                            None
 9010                        },
 9011                        cx,
 9012                    );
 9013                });
 9014
 9015                let selections = this.selections.all::<usize>(cx);
 9016                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9017                    s.select(selections)
 9018                });
 9019            } else {
 9020                this.insert(&clipboard_text, window, cx);
 9021            }
 9022        });
 9023    }
 9024
 9025    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 9026        if let Some(item) = cx.read_from_clipboard() {
 9027            let entries = item.entries();
 9028
 9029            match entries.first() {
 9030                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 9031                // of all the pasted entries.
 9032                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 9033                    .do_paste(
 9034                        clipboard_string.text(),
 9035                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 9036                        true,
 9037                        window,
 9038                        cx,
 9039                    ),
 9040                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 9041            }
 9042        }
 9043    }
 9044
 9045    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 9046        if self.read_only(cx) {
 9047            return;
 9048        }
 9049
 9050        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 9051            if let Some((selections, _)) =
 9052                self.selection_history.transaction(transaction_id).cloned()
 9053            {
 9054                self.change_selections(None, window, cx, |s| {
 9055                    s.select_anchors(selections.to_vec());
 9056                });
 9057            } else {
 9058                log::error!(
 9059                    "No entry in selection_history found for undo. \
 9060                     This may correspond to a bug where undo does not update the selection. \
 9061                     If this is occurring, please add details to \
 9062                     https://github.com/zed-industries/zed/issues/22692"
 9063                );
 9064            }
 9065            self.request_autoscroll(Autoscroll::fit(), cx);
 9066            self.unmark_text(window, cx);
 9067            self.refresh_inline_completion(true, false, window, cx);
 9068            cx.emit(EditorEvent::Edited { transaction_id });
 9069            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 9070        }
 9071    }
 9072
 9073    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 9074        if self.read_only(cx) {
 9075            return;
 9076        }
 9077
 9078        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 9079            if let Some((_, Some(selections))) =
 9080                self.selection_history.transaction(transaction_id).cloned()
 9081            {
 9082                self.change_selections(None, window, cx, |s| {
 9083                    s.select_anchors(selections.to_vec());
 9084                });
 9085            } else {
 9086                log::error!(
 9087                    "No entry in selection_history found for redo. \
 9088                     This may correspond to a bug where undo does not update the selection. \
 9089                     If this is occurring, please add details to \
 9090                     https://github.com/zed-industries/zed/issues/22692"
 9091                );
 9092            }
 9093            self.request_autoscroll(Autoscroll::fit(), cx);
 9094            self.unmark_text(window, cx);
 9095            self.refresh_inline_completion(true, false, window, cx);
 9096            cx.emit(EditorEvent::Edited { transaction_id });
 9097        }
 9098    }
 9099
 9100    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 9101        self.buffer
 9102            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 9103    }
 9104
 9105    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 9106        self.buffer
 9107            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 9108    }
 9109
 9110    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 9111        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9112            let line_mode = s.line_mode;
 9113            s.move_with(|map, selection| {
 9114                let cursor = if selection.is_empty() && !line_mode {
 9115                    movement::left(map, selection.start)
 9116                } else {
 9117                    selection.start
 9118                };
 9119                selection.collapse_to(cursor, SelectionGoal::None);
 9120            });
 9121        })
 9122    }
 9123
 9124    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 9125        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9126            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 9127        })
 9128    }
 9129
 9130    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 9131        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9132            let line_mode = s.line_mode;
 9133            s.move_with(|map, selection| {
 9134                let cursor = if selection.is_empty() && !line_mode {
 9135                    movement::right(map, selection.end)
 9136                } else {
 9137                    selection.end
 9138                };
 9139                selection.collapse_to(cursor, SelectionGoal::None)
 9140            });
 9141        })
 9142    }
 9143
 9144    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 9145        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9146            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 9147        })
 9148    }
 9149
 9150    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 9151        if self.take_rename(true, window, cx).is_some() {
 9152            return;
 9153        }
 9154
 9155        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9156            cx.propagate();
 9157            return;
 9158        }
 9159
 9160        let text_layout_details = &self.text_layout_details(window);
 9161        let selection_count = self.selections.count();
 9162        let first_selection = self.selections.first_anchor();
 9163
 9164        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9165            let line_mode = s.line_mode;
 9166            s.move_with(|map, selection| {
 9167                if !selection.is_empty() && !line_mode {
 9168                    selection.goal = SelectionGoal::None;
 9169                }
 9170                let (cursor, goal) = movement::up(
 9171                    map,
 9172                    selection.start,
 9173                    selection.goal,
 9174                    false,
 9175                    text_layout_details,
 9176                );
 9177                selection.collapse_to(cursor, goal);
 9178            });
 9179        });
 9180
 9181        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 9182        {
 9183            cx.propagate();
 9184        }
 9185    }
 9186
 9187    pub fn move_up_by_lines(
 9188        &mut self,
 9189        action: &MoveUpByLines,
 9190        window: &mut Window,
 9191        cx: &mut Context<Self>,
 9192    ) {
 9193        if self.take_rename(true, window, cx).is_some() {
 9194            return;
 9195        }
 9196
 9197        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9198            cx.propagate();
 9199            return;
 9200        }
 9201
 9202        let text_layout_details = &self.text_layout_details(window);
 9203
 9204        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9205            let line_mode = s.line_mode;
 9206            s.move_with(|map, selection| {
 9207                if !selection.is_empty() && !line_mode {
 9208                    selection.goal = SelectionGoal::None;
 9209                }
 9210                let (cursor, goal) = movement::up_by_rows(
 9211                    map,
 9212                    selection.start,
 9213                    action.lines,
 9214                    selection.goal,
 9215                    false,
 9216                    text_layout_details,
 9217                );
 9218                selection.collapse_to(cursor, goal);
 9219            });
 9220        })
 9221    }
 9222
 9223    pub fn move_down_by_lines(
 9224        &mut self,
 9225        action: &MoveDownByLines,
 9226        window: &mut Window,
 9227        cx: &mut Context<Self>,
 9228    ) {
 9229        if self.take_rename(true, window, cx).is_some() {
 9230            return;
 9231        }
 9232
 9233        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9234            cx.propagate();
 9235            return;
 9236        }
 9237
 9238        let text_layout_details = &self.text_layout_details(window);
 9239
 9240        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9241            let line_mode = s.line_mode;
 9242            s.move_with(|map, selection| {
 9243                if !selection.is_empty() && !line_mode {
 9244                    selection.goal = SelectionGoal::None;
 9245                }
 9246                let (cursor, goal) = movement::down_by_rows(
 9247                    map,
 9248                    selection.start,
 9249                    action.lines,
 9250                    selection.goal,
 9251                    false,
 9252                    text_layout_details,
 9253                );
 9254                selection.collapse_to(cursor, goal);
 9255            });
 9256        })
 9257    }
 9258
 9259    pub fn select_down_by_lines(
 9260        &mut self,
 9261        action: &SelectDownByLines,
 9262        window: &mut Window,
 9263        cx: &mut Context<Self>,
 9264    ) {
 9265        let text_layout_details = &self.text_layout_details(window);
 9266        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9267            s.move_heads_with(|map, head, goal| {
 9268                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 9269            })
 9270        })
 9271    }
 9272
 9273    pub fn select_up_by_lines(
 9274        &mut self,
 9275        action: &SelectUpByLines,
 9276        window: &mut Window,
 9277        cx: &mut Context<Self>,
 9278    ) {
 9279        let text_layout_details = &self.text_layout_details(window);
 9280        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9281            s.move_heads_with(|map, head, goal| {
 9282                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 9283            })
 9284        })
 9285    }
 9286
 9287    pub fn select_page_up(
 9288        &mut self,
 9289        _: &SelectPageUp,
 9290        window: &mut Window,
 9291        cx: &mut Context<Self>,
 9292    ) {
 9293        let Some(row_count) = self.visible_row_count() else {
 9294            return;
 9295        };
 9296
 9297        let text_layout_details = &self.text_layout_details(window);
 9298
 9299        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9300            s.move_heads_with(|map, head, goal| {
 9301                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 9302            })
 9303        })
 9304    }
 9305
 9306    pub fn move_page_up(
 9307        &mut self,
 9308        action: &MovePageUp,
 9309        window: &mut Window,
 9310        cx: &mut Context<Self>,
 9311    ) {
 9312        if self.take_rename(true, window, cx).is_some() {
 9313            return;
 9314        }
 9315
 9316        if self
 9317            .context_menu
 9318            .borrow_mut()
 9319            .as_mut()
 9320            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 9321            .unwrap_or(false)
 9322        {
 9323            return;
 9324        }
 9325
 9326        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9327            cx.propagate();
 9328            return;
 9329        }
 9330
 9331        let Some(row_count) = self.visible_row_count() else {
 9332            return;
 9333        };
 9334
 9335        let autoscroll = if action.center_cursor {
 9336            Autoscroll::center()
 9337        } else {
 9338            Autoscroll::fit()
 9339        };
 9340
 9341        let text_layout_details = &self.text_layout_details(window);
 9342
 9343        self.change_selections(Some(autoscroll), window, cx, |s| {
 9344            let line_mode = s.line_mode;
 9345            s.move_with(|map, selection| {
 9346                if !selection.is_empty() && !line_mode {
 9347                    selection.goal = SelectionGoal::None;
 9348                }
 9349                let (cursor, goal) = movement::up_by_rows(
 9350                    map,
 9351                    selection.end,
 9352                    row_count,
 9353                    selection.goal,
 9354                    false,
 9355                    text_layout_details,
 9356                );
 9357                selection.collapse_to(cursor, goal);
 9358            });
 9359        });
 9360    }
 9361
 9362    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 9363        let text_layout_details = &self.text_layout_details(window);
 9364        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9365            s.move_heads_with(|map, head, goal| {
 9366                movement::up(map, head, goal, false, text_layout_details)
 9367            })
 9368        })
 9369    }
 9370
 9371    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 9372        self.take_rename(true, window, cx);
 9373
 9374        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9375            cx.propagate();
 9376            return;
 9377        }
 9378
 9379        let text_layout_details = &self.text_layout_details(window);
 9380        let selection_count = self.selections.count();
 9381        let first_selection = self.selections.first_anchor();
 9382
 9383        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9384            let line_mode = s.line_mode;
 9385            s.move_with(|map, selection| {
 9386                if !selection.is_empty() && !line_mode {
 9387                    selection.goal = SelectionGoal::None;
 9388                }
 9389                let (cursor, goal) = movement::down(
 9390                    map,
 9391                    selection.end,
 9392                    selection.goal,
 9393                    false,
 9394                    text_layout_details,
 9395                );
 9396                selection.collapse_to(cursor, goal);
 9397            });
 9398        });
 9399
 9400        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 9401        {
 9402            cx.propagate();
 9403        }
 9404    }
 9405
 9406    pub fn select_page_down(
 9407        &mut self,
 9408        _: &SelectPageDown,
 9409        window: &mut Window,
 9410        cx: &mut Context<Self>,
 9411    ) {
 9412        let Some(row_count) = self.visible_row_count() else {
 9413            return;
 9414        };
 9415
 9416        let text_layout_details = &self.text_layout_details(window);
 9417
 9418        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9419            s.move_heads_with(|map, head, goal| {
 9420                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 9421            })
 9422        })
 9423    }
 9424
 9425    pub fn move_page_down(
 9426        &mut self,
 9427        action: &MovePageDown,
 9428        window: &mut Window,
 9429        cx: &mut Context<Self>,
 9430    ) {
 9431        if self.take_rename(true, window, cx).is_some() {
 9432            return;
 9433        }
 9434
 9435        if self
 9436            .context_menu
 9437            .borrow_mut()
 9438            .as_mut()
 9439            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 9440            .unwrap_or(false)
 9441        {
 9442            return;
 9443        }
 9444
 9445        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9446            cx.propagate();
 9447            return;
 9448        }
 9449
 9450        let Some(row_count) = self.visible_row_count() else {
 9451            return;
 9452        };
 9453
 9454        let autoscroll = if action.center_cursor {
 9455            Autoscroll::center()
 9456        } else {
 9457            Autoscroll::fit()
 9458        };
 9459
 9460        let text_layout_details = &self.text_layout_details(window);
 9461        self.change_selections(Some(autoscroll), window, cx, |s| {
 9462            let line_mode = s.line_mode;
 9463            s.move_with(|map, selection| {
 9464                if !selection.is_empty() && !line_mode {
 9465                    selection.goal = SelectionGoal::None;
 9466                }
 9467                let (cursor, goal) = movement::down_by_rows(
 9468                    map,
 9469                    selection.end,
 9470                    row_count,
 9471                    selection.goal,
 9472                    false,
 9473                    text_layout_details,
 9474                );
 9475                selection.collapse_to(cursor, goal);
 9476            });
 9477        });
 9478    }
 9479
 9480    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 9481        let text_layout_details = &self.text_layout_details(window);
 9482        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9483            s.move_heads_with(|map, head, goal| {
 9484                movement::down(map, head, goal, false, text_layout_details)
 9485            })
 9486        });
 9487    }
 9488
 9489    pub fn context_menu_first(
 9490        &mut self,
 9491        _: &ContextMenuFirst,
 9492        _window: &mut Window,
 9493        cx: &mut Context<Self>,
 9494    ) {
 9495        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9496            context_menu.select_first(self.completion_provider.as_deref(), cx);
 9497        }
 9498    }
 9499
 9500    pub fn context_menu_prev(
 9501        &mut self,
 9502        _: &ContextMenuPrevious,
 9503        _window: &mut Window,
 9504        cx: &mut Context<Self>,
 9505    ) {
 9506        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9507            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 9508        }
 9509    }
 9510
 9511    pub fn context_menu_next(
 9512        &mut self,
 9513        _: &ContextMenuNext,
 9514        _window: &mut Window,
 9515        cx: &mut Context<Self>,
 9516    ) {
 9517        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9518            context_menu.select_next(self.completion_provider.as_deref(), cx);
 9519        }
 9520    }
 9521
 9522    pub fn context_menu_last(
 9523        &mut self,
 9524        _: &ContextMenuLast,
 9525        _window: &mut Window,
 9526        cx: &mut Context<Self>,
 9527    ) {
 9528        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9529            context_menu.select_last(self.completion_provider.as_deref(), cx);
 9530        }
 9531    }
 9532
 9533    pub fn move_to_previous_word_start(
 9534        &mut self,
 9535        _: &MoveToPreviousWordStart,
 9536        window: &mut Window,
 9537        cx: &mut Context<Self>,
 9538    ) {
 9539        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9540            s.move_cursors_with(|map, head, _| {
 9541                (
 9542                    movement::previous_word_start(map, head),
 9543                    SelectionGoal::None,
 9544                )
 9545            });
 9546        })
 9547    }
 9548
 9549    pub fn move_to_previous_subword_start(
 9550        &mut self,
 9551        _: &MoveToPreviousSubwordStart,
 9552        window: &mut Window,
 9553        cx: &mut Context<Self>,
 9554    ) {
 9555        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9556            s.move_cursors_with(|map, head, _| {
 9557                (
 9558                    movement::previous_subword_start(map, head),
 9559                    SelectionGoal::None,
 9560                )
 9561            });
 9562        })
 9563    }
 9564
 9565    pub fn select_to_previous_word_start(
 9566        &mut self,
 9567        _: &SelectToPreviousWordStart,
 9568        window: &mut Window,
 9569        cx: &mut Context<Self>,
 9570    ) {
 9571        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9572            s.move_heads_with(|map, head, _| {
 9573                (
 9574                    movement::previous_word_start(map, head),
 9575                    SelectionGoal::None,
 9576                )
 9577            });
 9578        })
 9579    }
 9580
 9581    pub fn select_to_previous_subword_start(
 9582        &mut self,
 9583        _: &SelectToPreviousSubwordStart,
 9584        window: &mut Window,
 9585        cx: &mut Context<Self>,
 9586    ) {
 9587        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9588            s.move_heads_with(|map, head, _| {
 9589                (
 9590                    movement::previous_subword_start(map, head),
 9591                    SelectionGoal::None,
 9592                )
 9593            });
 9594        })
 9595    }
 9596
 9597    pub fn delete_to_previous_word_start(
 9598        &mut self,
 9599        action: &DeleteToPreviousWordStart,
 9600        window: &mut Window,
 9601        cx: &mut Context<Self>,
 9602    ) {
 9603        self.transact(window, cx, |this, window, cx| {
 9604            this.select_autoclose_pair(window, cx);
 9605            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9606                let line_mode = s.line_mode;
 9607                s.move_with(|map, selection| {
 9608                    if selection.is_empty() && !line_mode {
 9609                        let cursor = if action.ignore_newlines {
 9610                            movement::previous_word_start(map, selection.head())
 9611                        } else {
 9612                            movement::previous_word_start_or_newline(map, selection.head())
 9613                        };
 9614                        selection.set_head(cursor, SelectionGoal::None);
 9615                    }
 9616                });
 9617            });
 9618            this.insert("", window, cx);
 9619        });
 9620    }
 9621
 9622    pub fn delete_to_previous_subword_start(
 9623        &mut self,
 9624        _: &DeleteToPreviousSubwordStart,
 9625        window: &mut Window,
 9626        cx: &mut Context<Self>,
 9627    ) {
 9628        self.transact(window, cx, |this, window, cx| {
 9629            this.select_autoclose_pair(window, cx);
 9630            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9631                let line_mode = s.line_mode;
 9632                s.move_with(|map, selection| {
 9633                    if selection.is_empty() && !line_mode {
 9634                        let cursor = movement::previous_subword_start(map, selection.head());
 9635                        selection.set_head(cursor, SelectionGoal::None);
 9636                    }
 9637                });
 9638            });
 9639            this.insert("", window, cx);
 9640        });
 9641    }
 9642
 9643    pub fn move_to_next_word_end(
 9644        &mut self,
 9645        _: &MoveToNextWordEnd,
 9646        window: &mut Window,
 9647        cx: &mut Context<Self>,
 9648    ) {
 9649        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9650            s.move_cursors_with(|map, head, _| {
 9651                (movement::next_word_end(map, head), SelectionGoal::None)
 9652            });
 9653        })
 9654    }
 9655
 9656    pub fn move_to_next_subword_end(
 9657        &mut self,
 9658        _: &MoveToNextSubwordEnd,
 9659        window: &mut Window,
 9660        cx: &mut Context<Self>,
 9661    ) {
 9662        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9663            s.move_cursors_with(|map, head, _| {
 9664                (movement::next_subword_end(map, head), SelectionGoal::None)
 9665            });
 9666        })
 9667    }
 9668
 9669    pub fn select_to_next_word_end(
 9670        &mut self,
 9671        _: &SelectToNextWordEnd,
 9672        window: &mut Window,
 9673        cx: &mut Context<Self>,
 9674    ) {
 9675        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9676            s.move_heads_with(|map, head, _| {
 9677                (movement::next_word_end(map, head), SelectionGoal::None)
 9678            });
 9679        })
 9680    }
 9681
 9682    pub fn select_to_next_subword_end(
 9683        &mut self,
 9684        _: &SelectToNextSubwordEnd,
 9685        window: &mut Window,
 9686        cx: &mut Context<Self>,
 9687    ) {
 9688        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9689            s.move_heads_with(|map, head, _| {
 9690                (movement::next_subword_end(map, head), SelectionGoal::None)
 9691            });
 9692        })
 9693    }
 9694
 9695    pub fn delete_to_next_word_end(
 9696        &mut self,
 9697        action: &DeleteToNextWordEnd,
 9698        window: &mut Window,
 9699        cx: &mut Context<Self>,
 9700    ) {
 9701        self.transact(window, cx, |this, window, cx| {
 9702            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9703                let line_mode = s.line_mode;
 9704                s.move_with(|map, selection| {
 9705                    if selection.is_empty() && !line_mode {
 9706                        let cursor = if action.ignore_newlines {
 9707                            movement::next_word_end(map, selection.head())
 9708                        } else {
 9709                            movement::next_word_end_or_newline(map, selection.head())
 9710                        };
 9711                        selection.set_head(cursor, SelectionGoal::None);
 9712                    }
 9713                });
 9714            });
 9715            this.insert("", window, cx);
 9716        });
 9717    }
 9718
 9719    pub fn delete_to_next_subword_end(
 9720        &mut self,
 9721        _: &DeleteToNextSubwordEnd,
 9722        window: &mut Window,
 9723        cx: &mut Context<Self>,
 9724    ) {
 9725        self.transact(window, cx, |this, window, cx| {
 9726            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9727                s.move_with(|map, selection| {
 9728                    if selection.is_empty() {
 9729                        let cursor = movement::next_subword_end(map, selection.head());
 9730                        selection.set_head(cursor, SelectionGoal::None);
 9731                    }
 9732                });
 9733            });
 9734            this.insert("", window, cx);
 9735        });
 9736    }
 9737
 9738    pub fn move_to_beginning_of_line(
 9739        &mut self,
 9740        action: &MoveToBeginningOfLine,
 9741        window: &mut Window,
 9742        cx: &mut Context<Self>,
 9743    ) {
 9744        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9745            s.move_cursors_with(|map, head, _| {
 9746                (
 9747                    movement::indented_line_beginning(
 9748                        map,
 9749                        head,
 9750                        action.stop_at_soft_wraps,
 9751                        action.stop_at_indent,
 9752                    ),
 9753                    SelectionGoal::None,
 9754                )
 9755            });
 9756        })
 9757    }
 9758
 9759    pub fn select_to_beginning_of_line(
 9760        &mut self,
 9761        action: &SelectToBeginningOfLine,
 9762        window: &mut Window,
 9763        cx: &mut Context<Self>,
 9764    ) {
 9765        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9766            s.move_heads_with(|map, head, _| {
 9767                (
 9768                    movement::indented_line_beginning(
 9769                        map,
 9770                        head,
 9771                        action.stop_at_soft_wraps,
 9772                        action.stop_at_indent,
 9773                    ),
 9774                    SelectionGoal::None,
 9775                )
 9776            });
 9777        });
 9778    }
 9779
 9780    pub fn delete_to_beginning_of_line(
 9781        &mut self,
 9782        action: &DeleteToBeginningOfLine,
 9783        window: &mut Window,
 9784        cx: &mut Context<Self>,
 9785    ) {
 9786        self.transact(window, cx, |this, window, cx| {
 9787            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9788                s.move_with(|_, selection| {
 9789                    selection.reversed = true;
 9790                });
 9791            });
 9792
 9793            this.select_to_beginning_of_line(
 9794                &SelectToBeginningOfLine {
 9795                    stop_at_soft_wraps: false,
 9796                    stop_at_indent: action.stop_at_indent,
 9797                },
 9798                window,
 9799                cx,
 9800            );
 9801            this.backspace(&Backspace, window, cx);
 9802        });
 9803    }
 9804
 9805    pub fn move_to_end_of_line(
 9806        &mut self,
 9807        action: &MoveToEndOfLine,
 9808        window: &mut Window,
 9809        cx: &mut Context<Self>,
 9810    ) {
 9811        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9812            s.move_cursors_with(|map, head, _| {
 9813                (
 9814                    movement::line_end(map, head, action.stop_at_soft_wraps),
 9815                    SelectionGoal::None,
 9816                )
 9817            });
 9818        })
 9819    }
 9820
 9821    pub fn select_to_end_of_line(
 9822        &mut self,
 9823        action: &SelectToEndOfLine,
 9824        window: &mut Window,
 9825        cx: &mut Context<Self>,
 9826    ) {
 9827        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9828            s.move_heads_with(|map, head, _| {
 9829                (
 9830                    movement::line_end(map, head, action.stop_at_soft_wraps),
 9831                    SelectionGoal::None,
 9832                )
 9833            });
 9834        })
 9835    }
 9836
 9837    pub fn delete_to_end_of_line(
 9838        &mut self,
 9839        _: &DeleteToEndOfLine,
 9840        window: &mut Window,
 9841        cx: &mut Context<Self>,
 9842    ) {
 9843        self.transact(window, cx, |this, window, cx| {
 9844            this.select_to_end_of_line(
 9845                &SelectToEndOfLine {
 9846                    stop_at_soft_wraps: false,
 9847                },
 9848                window,
 9849                cx,
 9850            );
 9851            this.delete(&Delete, window, cx);
 9852        });
 9853    }
 9854
 9855    pub fn cut_to_end_of_line(
 9856        &mut self,
 9857        _: &CutToEndOfLine,
 9858        window: &mut Window,
 9859        cx: &mut Context<Self>,
 9860    ) {
 9861        self.transact(window, cx, |this, window, cx| {
 9862            this.select_to_end_of_line(
 9863                &SelectToEndOfLine {
 9864                    stop_at_soft_wraps: false,
 9865                },
 9866                window,
 9867                cx,
 9868            );
 9869            this.cut(&Cut, window, cx);
 9870        });
 9871    }
 9872
 9873    pub fn move_to_start_of_paragraph(
 9874        &mut self,
 9875        _: &MoveToStartOfParagraph,
 9876        window: &mut Window,
 9877        cx: &mut Context<Self>,
 9878    ) {
 9879        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9880            cx.propagate();
 9881            return;
 9882        }
 9883
 9884        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9885            s.move_with(|map, selection| {
 9886                selection.collapse_to(
 9887                    movement::start_of_paragraph(map, selection.head(), 1),
 9888                    SelectionGoal::None,
 9889                )
 9890            });
 9891        })
 9892    }
 9893
 9894    pub fn move_to_end_of_paragraph(
 9895        &mut self,
 9896        _: &MoveToEndOfParagraph,
 9897        window: &mut Window,
 9898        cx: &mut Context<Self>,
 9899    ) {
 9900        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9901            cx.propagate();
 9902            return;
 9903        }
 9904
 9905        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9906            s.move_with(|map, selection| {
 9907                selection.collapse_to(
 9908                    movement::end_of_paragraph(map, selection.head(), 1),
 9909                    SelectionGoal::None,
 9910                )
 9911            });
 9912        })
 9913    }
 9914
 9915    pub fn select_to_start_of_paragraph(
 9916        &mut self,
 9917        _: &SelectToStartOfParagraph,
 9918        window: &mut Window,
 9919        cx: &mut Context<Self>,
 9920    ) {
 9921        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9922            cx.propagate();
 9923            return;
 9924        }
 9925
 9926        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9927            s.move_heads_with(|map, head, _| {
 9928                (
 9929                    movement::start_of_paragraph(map, head, 1),
 9930                    SelectionGoal::None,
 9931                )
 9932            });
 9933        })
 9934    }
 9935
 9936    pub fn select_to_end_of_paragraph(
 9937        &mut self,
 9938        _: &SelectToEndOfParagraph,
 9939        window: &mut Window,
 9940        cx: &mut Context<Self>,
 9941    ) {
 9942        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9943            cx.propagate();
 9944            return;
 9945        }
 9946
 9947        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9948            s.move_heads_with(|map, head, _| {
 9949                (
 9950                    movement::end_of_paragraph(map, head, 1),
 9951                    SelectionGoal::None,
 9952                )
 9953            });
 9954        })
 9955    }
 9956
 9957    pub fn move_to_start_of_excerpt(
 9958        &mut self,
 9959        _: &MoveToStartOfExcerpt,
 9960        window: &mut Window,
 9961        cx: &mut Context<Self>,
 9962    ) {
 9963        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9964            cx.propagate();
 9965            return;
 9966        }
 9967
 9968        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9969            s.move_with(|map, selection| {
 9970                selection.collapse_to(
 9971                    movement::start_of_excerpt(
 9972                        map,
 9973                        selection.head(),
 9974                        workspace::searchable::Direction::Prev,
 9975                    ),
 9976                    SelectionGoal::None,
 9977                )
 9978            });
 9979        })
 9980    }
 9981
 9982    pub fn move_to_start_of_next_excerpt(
 9983        &mut self,
 9984        _: &MoveToStartOfNextExcerpt,
 9985        window: &mut Window,
 9986        cx: &mut Context<Self>,
 9987    ) {
 9988        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9989            cx.propagate();
 9990            return;
 9991        }
 9992
 9993        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9994            s.move_with(|map, selection| {
 9995                selection.collapse_to(
 9996                    movement::start_of_excerpt(
 9997                        map,
 9998                        selection.head(),
 9999                        workspace::searchable::Direction::Next,
10000                    ),
10001                    SelectionGoal::None,
10002                )
10003            });
10004        })
10005    }
10006
10007    pub fn move_to_end_of_excerpt(
10008        &mut self,
10009        _: &MoveToEndOfExcerpt,
10010        window: &mut Window,
10011        cx: &mut Context<Self>,
10012    ) {
10013        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10014            cx.propagate();
10015            return;
10016        }
10017
10018        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10019            s.move_with(|map, selection| {
10020                selection.collapse_to(
10021                    movement::end_of_excerpt(
10022                        map,
10023                        selection.head(),
10024                        workspace::searchable::Direction::Next,
10025                    ),
10026                    SelectionGoal::None,
10027                )
10028            });
10029        })
10030    }
10031
10032    pub fn move_to_end_of_previous_excerpt(
10033        &mut self,
10034        _: &MoveToEndOfPreviousExcerpt,
10035        window: &mut Window,
10036        cx: &mut Context<Self>,
10037    ) {
10038        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10039            cx.propagate();
10040            return;
10041        }
10042
10043        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10044            s.move_with(|map, selection| {
10045                selection.collapse_to(
10046                    movement::end_of_excerpt(
10047                        map,
10048                        selection.head(),
10049                        workspace::searchable::Direction::Prev,
10050                    ),
10051                    SelectionGoal::None,
10052                )
10053            });
10054        })
10055    }
10056
10057    pub fn select_to_start_of_excerpt(
10058        &mut self,
10059        _: &SelectToStartOfExcerpt,
10060        window: &mut Window,
10061        cx: &mut Context<Self>,
10062    ) {
10063        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10064            cx.propagate();
10065            return;
10066        }
10067
10068        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10069            s.move_heads_with(|map, head, _| {
10070                (
10071                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
10072                    SelectionGoal::None,
10073                )
10074            });
10075        })
10076    }
10077
10078    pub fn select_to_start_of_next_excerpt(
10079        &mut self,
10080        _: &SelectToStartOfNextExcerpt,
10081        window: &mut Window,
10082        cx: &mut Context<Self>,
10083    ) {
10084        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10085            cx.propagate();
10086            return;
10087        }
10088
10089        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10090            s.move_heads_with(|map, head, _| {
10091                (
10092                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
10093                    SelectionGoal::None,
10094                )
10095            });
10096        })
10097    }
10098
10099    pub fn select_to_end_of_excerpt(
10100        &mut self,
10101        _: &SelectToEndOfExcerpt,
10102        window: &mut Window,
10103        cx: &mut Context<Self>,
10104    ) {
10105        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10106            cx.propagate();
10107            return;
10108        }
10109
10110        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10111            s.move_heads_with(|map, head, _| {
10112                (
10113                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
10114                    SelectionGoal::None,
10115                )
10116            });
10117        })
10118    }
10119
10120    pub fn select_to_end_of_previous_excerpt(
10121        &mut self,
10122        _: &SelectToEndOfPreviousExcerpt,
10123        window: &mut Window,
10124        cx: &mut Context<Self>,
10125    ) {
10126        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10127            cx.propagate();
10128            return;
10129        }
10130
10131        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10132            s.move_heads_with(|map, head, _| {
10133                (
10134                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
10135                    SelectionGoal::None,
10136                )
10137            });
10138        })
10139    }
10140
10141    pub fn move_to_beginning(
10142        &mut self,
10143        _: &MoveToBeginning,
10144        window: &mut Window,
10145        cx: &mut Context<Self>,
10146    ) {
10147        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10148            cx.propagate();
10149            return;
10150        }
10151
10152        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10153            s.select_ranges(vec![0..0]);
10154        });
10155    }
10156
10157    pub fn select_to_beginning(
10158        &mut self,
10159        _: &SelectToBeginning,
10160        window: &mut Window,
10161        cx: &mut Context<Self>,
10162    ) {
10163        let mut selection = self.selections.last::<Point>(cx);
10164        selection.set_head(Point::zero(), SelectionGoal::None);
10165
10166        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10167            s.select(vec![selection]);
10168        });
10169    }
10170
10171    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
10172        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10173            cx.propagate();
10174            return;
10175        }
10176
10177        let cursor = self.buffer.read(cx).read(cx).len();
10178        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10179            s.select_ranges(vec![cursor..cursor])
10180        });
10181    }
10182
10183    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
10184        self.nav_history = nav_history;
10185    }
10186
10187    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
10188        self.nav_history.as_ref()
10189    }
10190
10191    fn push_to_nav_history(
10192        &mut self,
10193        cursor_anchor: Anchor,
10194        new_position: Option<Point>,
10195        cx: &mut Context<Self>,
10196    ) {
10197        if let Some(nav_history) = self.nav_history.as_mut() {
10198            let buffer = self.buffer.read(cx).read(cx);
10199            let cursor_position = cursor_anchor.to_point(&buffer);
10200            let scroll_state = self.scroll_manager.anchor();
10201            let scroll_top_row = scroll_state.top_row(&buffer);
10202            drop(buffer);
10203
10204            if let Some(new_position) = new_position {
10205                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
10206                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
10207                    return;
10208                }
10209            }
10210
10211            nav_history.push(
10212                Some(NavigationData {
10213                    cursor_anchor,
10214                    cursor_position,
10215                    scroll_anchor: scroll_state,
10216                    scroll_top_row,
10217                }),
10218                cx,
10219            );
10220        }
10221    }
10222
10223    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
10224        let buffer = self.buffer.read(cx).snapshot(cx);
10225        let mut selection = self.selections.first::<usize>(cx);
10226        selection.set_head(buffer.len(), SelectionGoal::None);
10227        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10228            s.select(vec![selection]);
10229        });
10230    }
10231
10232    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
10233        let end = self.buffer.read(cx).read(cx).len();
10234        self.change_selections(None, window, cx, |s| {
10235            s.select_ranges(vec![0..end]);
10236        });
10237    }
10238
10239    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
10240        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10241        let mut selections = self.selections.all::<Point>(cx);
10242        let max_point = display_map.buffer_snapshot.max_point();
10243        for selection in &mut selections {
10244            let rows = selection.spanned_rows(true, &display_map);
10245            selection.start = Point::new(rows.start.0, 0);
10246            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
10247            selection.reversed = false;
10248        }
10249        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10250            s.select(selections);
10251        });
10252    }
10253
10254    pub fn split_selection_into_lines(
10255        &mut self,
10256        _: &SplitSelectionIntoLines,
10257        window: &mut Window,
10258        cx: &mut Context<Self>,
10259    ) {
10260        let selections = self
10261            .selections
10262            .all::<Point>(cx)
10263            .into_iter()
10264            .map(|selection| selection.start..selection.end)
10265            .collect::<Vec<_>>();
10266        self.unfold_ranges(&selections, true, true, cx);
10267
10268        let mut new_selection_ranges = Vec::new();
10269        {
10270            let buffer = self.buffer.read(cx).read(cx);
10271            for selection in selections {
10272                for row in selection.start.row..selection.end.row {
10273                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
10274                    new_selection_ranges.push(cursor..cursor);
10275                }
10276
10277                let is_multiline_selection = selection.start.row != selection.end.row;
10278                // Don't insert last one if it's a multi-line selection ending at the start of a line,
10279                // so this action feels more ergonomic when paired with other selection operations
10280                let should_skip_last = is_multiline_selection && selection.end.column == 0;
10281                if !should_skip_last {
10282                    new_selection_ranges.push(selection.end..selection.end);
10283                }
10284            }
10285        }
10286        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10287            s.select_ranges(new_selection_ranges);
10288        });
10289    }
10290
10291    pub fn add_selection_above(
10292        &mut self,
10293        _: &AddSelectionAbove,
10294        window: &mut Window,
10295        cx: &mut Context<Self>,
10296    ) {
10297        self.add_selection(true, window, cx);
10298    }
10299
10300    pub fn add_selection_below(
10301        &mut self,
10302        _: &AddSelectionBelow,
10303        window: &mut Window,
10304        cx: &mut Context<Self>,
10305    ) {
10306        self.add_selection(false, window, cx);
10307    }
10308
10309    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
10310        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10311        let mut selections = self.selections.all::<Point>(cx);
10312        let text_layout_details = self.text_layout_details(window);
10313        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
10314            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
10315            let range = oldest_selection.display_range(&display_map).sorted();
10316
10317            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
10318            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
10319            let positions = start_x.min(end_x)..start_x.max(end_x);
10320
10321            selections.clear();
10322            let mut stack = Vec::new();
10323            for row in range.start.row().0..=range.end.row().0 {
10324                if let Some(selection) = self.selections.build_columnar_selection(
10325                    &display_map,
10326                    DisplayRow(row),
10327                    &positions,
10328                    oldest_selection.reversed,
10329                    &text_layout_details,
10330                ) {
10331                    stack.push(selection.id);
10332                    selections.push(selection);
10333                }
10334            }
10335
10336            if above {
10337                stack.reverse();
10338            }
10339
10340            AddSelectionsState { above, stack }
10341        });
10342
10343        let last_added_selection = *state.stack.last().unwrap();
10344        let mut new_selections = Vec::new();
10345        if above == state.above {
10346            let end_row = if above {
10347                DisplayRow(0)
10348            } else {
10349                display_map.max_point().row()
10350            };
10351
10352            'outer: for selection in selections {
10353                if selection.id == last_added_selection {
10354                    let range = selection.display_range(&display_map).sorted();
10355                    debug_assert_eq!(range.start.row(), range.end.row());
10356                    let mut row = range.start.row();
10357                    let positions =
10358                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
10359                            px(start)..px(end)
10360                        } else {
10361                            let start_x =
10362                                display_map.x_for_display_point(range.start, &text_layout_details);
10363                            let end_x =
10364                                display_map.x_for_display_point(range.end, &text_layout_details);
10365                            start_x.min(end_x)..start_x.max(end_x)
10366                        };
10367
10368                    while row != end_row {
10369                        if above {
10370                            row.0 -= 1;
10371                        } else {
10372                            row.0 += 1;
10373                        }
10374
10375                        if let Some(new_selection) = self.selections.build_columnar_selection(
10376                            &display_map,
10377                            row,
10378                            &positions,
10379                            selection.reversed,
10380                            &text_layout_details,
10381                        ) {
10382                            state.stack.push(new_selection.id);
10383                            if above {
10384                                new_selections.push(new_selection);
10385                                new_selections.push(selection);
10386                            } else {
10387                                new_selections.push(selection);
10388                                new_selections.push(new_selection);
10389                            }
10390
10391                            continue 'outer;
10392                        }
10393                    }
10394                }
10395
10396                new_selections.push(selection);
10397            }
10398        } else {
10399            new_selections = selections;
10400            new_selections.retain(|s| s.id != last_added_selection);
10401            state.stack.pop();
10402        }
10403
10404        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10405            s.select(new_selections);
10406        });
10407        if state.stack.len() > 1 {
10408            self.add_selections_state = Some(state);
10409        }
10410    }
10411
10412    pub fn select_next_match_internal(
10413        &mut self,
10414        display_map: &DisplaySnapshot,
10415        replace_newest: bool,
10416        autoscroll: Option<Autoscroll>,
10417        window: &mut Window,
10418        cx: &mut Context<Self>,
10419    ) -> Result<()> {
10420        fn select_next_match_ranges(
10421            this: &mut Editor,
10422            range: Range<usize>,
10423            replace_newest: bool,
10424            auto_scroll: Option<Autoscroll>,
10425            window: &mut Window,
10426            cx: &mut Context<Editor>,
10427        ) {
10428            this.unfold_ranges(&[range.clone()], false, true, cx);
10429            this.change_selections(auto_scroll, window, cx, |s| {
10430                if replace_newest {
10431                    s.delete(s.newest_anchor().id);
10432                }
10433                s.insert_range(range.clone());
10434            });
10435        }
10436
10437        let buffer = &display_map.buffer_snapshot;
10438        let mut selections = self.selections.all::<usize>(cx);
10439        if let Some(mut select_next_state) = self.select_next_state.take() {
10440            let query = &select_next_state.query;
10441            if !select_next_state.done {
10442                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10443                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10444                let mut next_selected_range = None;
10445
10446                let bytes_after_last_selection =
10447                    buffer.bytes_in_range(last_selection.end..buffer.len());
10448                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
10449                let query_matches = query
10450                    .stream_find_iter(bytes_after_last_selection)
10451                    .map(|result| (last_selection.end, result))
10452                    .chain(
10453                        query
10454                            .stream_find_iter(bytes_before_first_selection)
10455                            .map(|result| (0, result)),
10456                    );
10457
10458                for (start_offset, query_match) in query_matches {
10459                    let query_match = query_match.unwrap(); // can only fail due to I/O
10460                    let offset_range =
10461                        start_offset + query_match.start()..start_offset + query_match.end();
10462                    let display_range = offset_range.start.to_display_point(display_map)
10463                        ..offset_range.end.to_display_point(display_map);
10464
10465                    if !select_next_state.wordwise
10466                        || (!movement::is_inside_word(display_map, display_range.start)
10467                            && !movement::is_inside_word(display_map, display_range.end))
10468                    {
10469                        // TODO: This is n^2, because we might check all the selections
10470                        if !selections
10471                            .iter()
10472                            .any(|selection| selection.range().overlaps(&offset_range))
10473                        {
10474                            next_selected_range = Some(offset_range);
10475                            break;
10476                        }
10477                    }
10478                }
10479
10480                if let Some(next_selected_range) = next_selected_range {
10481                    select_next_match_ranges(
10482                        self,
10483                        next_selected_range,
10484                        replace_newest,
10485                        autoscroll,
10486                        window,
10487                        cx,
10488                    );
10489                } else {
10490                    select_next_state.done = true;
10491                }
10492            }
10493
10494            self.select_next_state = Some(select_next_state);
10495        } else {
10496            let mut only_carets = true;
10497            let mut same_text_selected = true;
10498            let mut selected_text = None;
10499
10500            let mut selections_iter = selections.iter().peekable();
10501            while let Some(selection) = selections_iter.next() {
10502                if selection.start != selection.end {
10503                    only_carets = false;
10504                }
10505
10506                if same_text_selected {
10507                    if selected_text.is_none() {
10508                        selected_text =
10509                            Some(buffer.text_for_range(selection.range()).collect::<String>());
10510                    }
10511
10512                    if let Some(next_selection) = selections_iter.peek() {
10513                        if next_selection.range().len() == selection.range().len() {
10514                            let next_selected_text = buffer
10515                                .text_for_range(next_selection.range())
10516                                .collect::<String>();
10517                            if Some(next_selected_text) != selected_text {
10518                                same_text_selected = false;
10519                                selected_text = None;
10520                            }
10521                        } else {
10522                            same_text_selected = false;
10523                            selected_text = None;
10524                        }
10525                    }
10526                }
10527            }
10528
10529            if only_carets {
10530                for selection in &mut selections {
10531                    let word_range = movement::surrounding_word(
10532                        display_map,
10533                        selection.start.to_display_point(display_map),
10534                    );
10535                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
10536                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
10537                    selection.goal = SelectionGoal::None;
10538                    selection.reversed = false;
10539                    select_next_match_ranges(
10540                        self,
10541                        selection.start..selection.end,
10542                        replace_newest,
10543                        autoscroll,
10544                        window,
10545                        cx,
10546                    );
10547                }
10548
10549                if selections.len() == 1 {
10550                    let selection = selections
10551                        .last()
10552                        .expect("ensured that there's only one selection");
10553                    let query = buffer
10554                        .text_for_range(selection.start..selection.end)
10555                        .collect::<String>();
10556                    let is_empty = query.is_empty();
10557                    let select_state = SelectNextState {
10558                        query: AhoCorasick::new(&[query])?,
10559                        wordwise: true,
10560                        done: is_empty,
10561                    };
10562                    self.select_next_state = Some(select_state);
10563                } else {
10564                    self.select_next_state = None;
10565                }
10566            } else if let Some(selected_text) = selected_text {
10567                self.select_next_state = Some(SelectNextState {
10568                    query: AhoCorasick::new(&[selected_text])?,
10569                    wordwise: false,
10570                    done: false,
10571                });
10572                self.select_next_match_internal(
10573                    display_map,
10574                    replace_newest,
10575                    autoscroll,
10576                    window,
10577                    cx,
10578                )?;
10579            }
10580        }
10581        Ok(())
10582    }
10583
10584    pub fn select_all_matches(
10585        &mut self,
10586        _action: &SelectAllMatches,
10587        window: &mut Window,
10588        cx: &mut Context<Self>,
10589    ) -> Result<()> {
10590        self.push_to_selection_history();
10591        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10592
10593        self.select_next_match_internal(&display_map, false, None, window, cx)?;
10594        let Some(select_next_state) = self.select_next_state.as_mut() else {
10595            return Ok(());
10596        };
10597        if select_next_state.done {
10598            return Ok(());
10599        }
10600
10601        let mut new_selections = self.selections.all::<usize>(cx);
10602
10603        let buffer = &display_map.buffer_snapshot;
10604        let query_matches = select_next_state
10605            .query
10606            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
10607
10608        for query_match in query_matches {
10609            let query_match = query_match.unwrap(); // can only fail due to I/O
10610            let offset_range = query_match.start()..query_match.end();
10611            let display_range = offset_range.start.to_display_point(&display_map)
10612                ..offset_range.end.to_display_point(&display_map);
10613
10614            if !select_next_state.wordwise
10615                || (!movement::is_inside_word(&display_map, display_range.start)
10616                    && !movement::is_inside_word(&display_map, display_range.end))
10617            {
10618                self.selections.change_with(cx, |selections| {
10619                    new_selections.push(Selection {
10620                        id: selections.new_selection_id(),
10621                        start: offset_range.start,
10622                        end: offset_range.end,
10623                        reversed: false,
10624                        goal: SelectionGoal::None,
10625                    });
10626                });
10627            }
10628        }
10629
10630        new_selections.sort_by_key(|selection| selection.start);
10631        let mut ix = 0;
10632        while ix + 1 < new_selections.len() {
10633            let current_selection = &new_selections[ix];
10634            let next_selection = &new_selections[ix + 1];
10635            if current_selection.range().overlaps(&next_selection.range()) {
10636                if current_selection.id < next_selection.id {
10637                    new_selections.remove(ix + 1);
10638                } else {
10639                    new_selections.remove(ix);
10640                }
10641            } else {
10642                ix += 1;
10643            }
10644        }
10645
10646        let reversed = self.selections.oldest::<usize>(cx).reversed;
10647
10648        for selection in new_selections.iter_mut() {
10649            selection.reversed = reversed;
10650        }
10651
10652        select_next_state.done = true;
10653        self.unfold_ranges(
10654            &new_selections
10655                .iter()
10656                .map(|selection| selection.range())
10657                .collect::<Vec<_>>(),
10658            false,
10659            false,
10660            cx,
10661        );
10662        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
10663            selections.select(new_selections)
10664        });
10665
10666        Ok(())
10667    }
10668
10669    pub fn select_next(
10670        &mut self,
10671        action: &SelectNext,
10672        window: &mut Window,
10673        cx: &mut Context<Self>,
10674    ) -> Result<()> {
10675        self.push_to_selection_history();
10676        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10677        self.select_next_match_internal(
10678            &display_map,
10679            action.replace_newest,
10680            Some(Autoscroll::newest()),
10681            window,
10682            cx,
10683        )?;
10684        Ok(())
10685    }
10686
10687    pub fn select_previous(
10688        &mut self,
10689        action: &SelectPrevious,
10690        window: &mut Window,
10691        cx: &mut Context<Self>,
10692    ) -> Result<()> {
10693        self.push_to_selection_history();
10694        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10695        let buffer = &display_map.buffer_snapshot;
10696        let mut selections = self.selections.all::<usize>(cx);
10697        if let Some(mut select_prev_state) = self.select_prev_state.take() {
10698            let query = &select_prev_state.query;
10699            if !select_prev_state.done {
10700                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10701                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10702                let mut next_selected_range = None;
10703                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
10704                let bytes_before_last_selection =
10705                    buffer.reversed_bytes_in_range(0..last_selection.start);
10706                let bytes_after_first_selection =
10707                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
10708                let query_matches = query
10709                    .stream_find_iter(bytes_before_last_selection)
10710                    .map(|result| (last_selection.start, result))
10711                    .chain(
10712                        query
10713                            .stream_find_iter(bytes_after_first_selection)
10714                            .map(|result| (buffer.len(), result)),
10715                    );
10716                for (end_offset, query_match) in query_matches {
10717                    let query_match = query_match.unwrap(); // can only fail due to I/O
10718                    let offset_range =
10719                        end_offset - query_match.end()..end_offset - query_match.start();
10720                    let display_range = offset_range.start.to_display_point(&display_map)
10721                        ..offset_range.end.to_display_point(&display_map);
10722
10723                    if !select_prev_state.wordwise
10724                        || (!movement::is_inside_word(&display_map, display_range.start)
10725                            && !movement::is_inside_word(&display_map, display_range.end))
10726                    {
10727                        next_selected_range = Some(offset_range);
10728                        break;
10729                    }
10730                }
10731
10732                if let Some(next_selected_range) = next_selected_range {
10733                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
10734                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10735                        if action.replace_newest {
10736                            s.delete(s.newest_anchor().id);
10737                        }
10738                        s.insert_range(next_selected_range);
10739                    });
10740                } else {
10741                    select_prev_state.done = true;
10742                }
10743            }
10744
10745            self.select_prev_state = Some(select_prev_state);
10746        } else {
10747            let mut only_carets = true;
10748            let mut same_text_selected = true;
10749            let mut selected_text = None;
10750
10751            let mut selections_iter = selections.iter().peekable();
10752            while let Some(selection) = selections_iter.next() {
10753                if selection.start != selection.end {
10754                    only_carets = false;
10755                }
10756
10757                if same_text_selected {
10758                    if selected_text.is_none() {
10759                        selected_text =
10760                            Some(buffer.text_for_range(selection.range()).collect::<String>());
10761                    }
10762
10763                    if let Some(next_selection) = selections_iter.peek() {
10764                        if next_selection.range().len() == selection.range().len() {
10765                            let next_selected_text = buffer
10766                                .text_for_range(next_selection.range())
10767                                .collect::<String>();
10768                            if Some(next_selected_text) != selected_text {
10769                                same_text_selected = false;
10770                                selected_text = None;
10771                            }
10772                        } else {
10773                            same_text_selected = false;
10774                            selected_text = None;
10775                        }
10776                    }
10777                }
10778            }
10779
10780            if only_carets {
10781                for selection in &mut selections {
10782                    let word_range = movement::surrounding_word(
10783                        &display_map,
10784                        selection.start.to_display_point(&display_map),
10785                    );
10786                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
10787                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
10788                    selection.goal = SelectionGoal::None;
10789                    selection.reversed = false;
10790                }
10791                if selections.len() == 1 {
10792                    let selection = selections
10793                        .last()
10794                        .expect("ensured that there's only one selection");
10795                    let query = buffer
10796                        .text_for_range(selection.start..selection.end)
10797                        .collect::<String>();
10798                    let is_empty = query.is_empty();
10799                    let select_state = SelectNextState {
10800                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
10801                        wordwise: true,
10802                        done: is_empty,
10803                    };
10804                    self.select_prev_state = Some(select_state);
10805                } else {
10806                    self.select_prev_state = None;
10807                }
10808
10809                self.unfold_ranges(
10810                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
10811                    false,
10812                    true,
10813                    cx,
10814                );
10815                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10816                    s.select(selections);
10817                });
10818            } else if let Some(selected_text) = selected_text {
10819                self.select_prev_state = Some(SelectNextState {
10820                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
10821                    wordwise: false,
10822                    done: false,
10823                });
10824                self.select_previous(action, window, cx)?;
10825            }
10826        }
10827        Ok(())
10828    }
10829
10830    pub fn toggle_comments(
10831        &mut self,
10832        action: &ToggleComments,
10833        window: &mut Window,
10834        cx: &mut Context<Self>,
10835    ) {
10836        if self.read_only(cx) {
10837            return;
10838        }
10839        let text_layout_details = &self.text_layout_details(window);
10840        self.transact(window, cx, |this, window, cx| {
10841            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
10842            let mut edits = Vec::new();
10843            let mut selection_edit_ranges = Vec::new();
10844            let mut last_toggled_row = None;
10845            let snapshot = this.buffer.read(cx).read(cx);
10846            let empty_str: Arc<str> = Arc::default();
10847            let mut suffixes_inserted = Vec::new();
10848            let ignore_indent = action.ignore_indent;
10849
10850            fn comment_prefix_range(
10851                snapshot: &MultiBufferSnapshot,
10852                row: MultiBufferRow,
10853                comment_prefix: &str,
10854                comment_prefix_whitespace: &str,
10855                ignore_indent: bool,
10856            ) -> Range<Point> {
10857                let indent_size = if ignore_indent {
10858                    0
10859                } else {
10860                    snapshot.indent_size_for_line(row).len
10861                };
10862
10863                let start = Point::new(row.0, indent_size);
10864
10865                let mut line_bytes = snapshot
10866                    .bytes_in_range(start..snapshot.max_point())
10867                    .flatten()
10868                    .copied();
10869
10870                // If this line currently begins with the line comment prefix, then record
10871                // the range containing the prefix.
10872                if line_bytes
10873                    .by_ref()
10874                    .take(comment_prefix.len())
10875                    .eq(comment_prefix.bytes())
10876                {
10877                    // Include any whitespace that matches the comment prefix.
10878                    let matching_whitespace_len = line_bytes
10879                        .zip(comment_prefix_whitespace.bytes())
10880                        .take_while(|(a, b)| a == b)
10881                        .count() as u32;
10882                    let end = Point::new(
10883                        start.row,
10884                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
10885                    );
10886                    start..end
10887                } else {
10888                    start..start
10889                }
10890            }
10891
10892            fn comment_suffix_range(
10893                snapshot: &MultiBufferSnapshot,
10894                row: MultiBufferRow,
10895                comment_suffix: &str,
10896                comment_suffix_has_leading_space: bool,
10897            ) -> Range<Point> {
10898                let end = Point::new(row.0, snapshot.line_len(row));
10899                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
10900
10901                let mut line_end_bytes = snapshot
10902                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
10903                    .flatten()
10904                    .copied();
10905
10906                let leading_space_len = if suffix_start_column > 0
10907                    && line_end_bytes.next() == Some(b' ')
10908                    && comment_suffix_has_leading_space
10909                {
10910                    1
10911                } else {
10912                    0
10913                };
10914
10915                // If this line currently begins with the line comment prefix, then record
10916                // the range containing the prefix.
10917                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
10918                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
10919                    start..end
10920                } else {
10921                    end..end
10922                }
10923            }
10924
10925            // TODO: Handle selections that cross excerpts
10926            for selection in &mut selections {
10927                let start_column = snapshot
10928                    .indent_size_for_line(MultiBufferRow(selection.start.row))
10929                    .len;
10930                let language = if let Some(language) =
10931                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
10932                {
10933                    language
10934                } else {
10935                    continue;
10936                };
10937
10938                selection_edit_ranges.clear();
10939
10940                // If multiple selections contain a given row, avoid processing that
10941                // row more than once.
10942                let mut start_row = MultiBufferRow(selection.start.row);
10943                if last_toggled_row == Some(start_row) {
10944                    start_row = start_row.next_row();
10945                }
10946                let end_row =
10947                    if selection.end.row > selection.start.row && selection.end.column == 0 {
10948                        MultiBufferRow(selection.end.row - 1)
10949                    } else {
10950                        MultiBufferRow(selection.end.row)
10951                    };
10952                last_toggled_row = Some(end_row);
10953
10954                if start_row > end_row {
10955                    continue;
10956                }
10957
10958                // If the language has line comments, toggle those.
10959                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
10960
10961                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
10962                if ignore_indent {
10963                    full_comment_prefixes = full_comment_prefixes
10964                        .into_iter()
10965                        .map(|s| Arc::from(s.trim_end()))
10966                        .collect();
10967                }
10968
10969                if !full_comment_prefixes.is_empty() {
10970                    let first_prefix = full_comment_prefixes
10971                        .first()
10972                        .expect("prefixes is non-empty");
10973                    let prefix_trimmed_lengths = full_comment_prefixes
10974                        .iter()
10975                        .map(|p| p.trim_end_matches(' ').len())
10976                        .collect::<SmallVec<[usize; 4]>>();
10977
10978                    let mut all_selection_lines_are_comments = true;
10979
10980                    for row in start_row.0..=end_row.0 {
10981                        let row = MultiBufferRow(row);
10982                        if start_row < end_row && snapshot.is_line_blank(row) {
10983                            continue;
10984                        }
10985
10986                        let prefix_range = full_comment_prefixes
10987                            .iter()
10988                            .zip(prefix_trimmed_lengths.iter().copied())
10989                            .map(|(prefix, trimmed_prefix_len)| {
10990                                comment_prefix_range(
10991                                    snapshot.deref(),
10992                                    row,
10993                                    &prefix[..trimmed_prefix_len],
10994                                    &prefix[trimmed_prefix_len..],
10995                                    ignore_indent,
10996                                )
10997                            })
10998                            .max_by_key(|range| range.end.column - range.start.column)
10999                            .expect("prefixes is non-empty");
11000
11001                        if prefix_range.is_empty() {
11002                            all_selection_lines_are_comments = false;
11003                        }
11004
11005                        selection_edit_ranges.push(prefix_range);
11006                    }
11007
11008                    if all_selection_lines_are_comments {
11009                        edits.extend(
11010                            selection_edit_ranges
11011                                .iter()
11012                                .cloned()
11013                                .map(|range| (range, empty_str.clone())),
11014                        );
11015                    } else {
11016                        let min_column = selection_edit_ranges
11017                            .iter()
11018                            .map(|range| range.start.column)
11019                            .min()
11020                            .unwrap_or(0);
11021                        edits.extend(selection_edit_ranges.iter().map(|range| {
11022                            let position = Point::new(range.start.row, min_column);
11023                            (position..position, first_prefix.clone())
11024                        }));
11025                    }
11026                } else if let Some((full_comment_prefix, comment_suffix)) =
11027                    language.block_comment_delimiters()
11028                {
11029                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
11030                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
11031                    let prefix_range = comment_prefix_range(
11032                        snapshot.deref(),
11033                        start_row,
11034                        comment_prefix,
11035                        comment_prefix_whitespace,
11036                        ignore_indent,
11037                    );
11038                    let suffix_range = comment_suffix_range(
11039                        snapshot.deref(),
11040                        end_row,
11041                        comment_suffix.trim_start_matches(' '),
11042                        comment_suffix.starts_with(' '),
11043                    );
11044
11045                    if prefix_range.is_empty() || suffix_range.is_empty() {
11046                        edits.push((
11047                            prefix_range.start..prefix_range.start,
11048                            full_comment_prefix.clone(),
11049                        ));
11050                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
11051                        suffixes_inserted.push((end_row, comment_suffix.len()));
11052                    } else {
11053                        edits.push((prefix_range, empty_str.clone()));
11054                        edits.push((suffix_range, empty_str.clone()));
11055                    }
11056                } else {
11057                    continue;
11058                }
11059            }
11060
11061            drop(snapshot);
11062            this.buffer.update(cx, |buffer, cx| {
11063                buffer.edit(edits, None, cx);
11064            });
11065
11066            // Adjust selections so that they end before any comment suffixes that
11067            // were inserted.
11068            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
11069            let mut selections = this.selections.all::<Point>(cx);
11070            let snapshot = this.buffer.read(cx).read(cx);
11071            for selection in &mut selections {
11072                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
11073                    match row.cmp(&MultiBufferRow(selection.end.row)) {
11074                        Ordering::Less => {
11075                            suffixes_inserted.next();
11076                            continue;
11077                        }
11078                        Ordering::Greater => break,
11079                        Ordering::Equal => {
11080                            if selection.end.column == snapshot.line_len(row) {
11081                                if selection.is_empty() {
11082                                    selection.start.column -= suffix_len as u32;
11083                                }
11084                                selection.end.column -= suffix_len as u32;
11085                            }
11086                            break;
11087                        }
11088                    }
11089                }
11090            }
11091
11092            drop(snapshot);
11093            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11094                s.select(selections)
11095            });
11096
11097            let selections = this.selections.all::<Point>(cx);
11098            let selections_on_single_row = selections.windows(2).all(|selections| {
11099                selections[0].start.row == selections[1].start.row
11100                    && selections[0].end.row == selections[1].end.row
11101                    && selections[0].start.row == selections[0].end.row
11102            });
11103            let selections_selecting = selections
11104                .iter()
11105                .any(|selection| selection.start != selection.end);
11106            let advance_downwards = action.advance_downwards
11107                && selections_on_single_row
11108                && !selections_selecting
11109                && !matches!(this.mode, EditorMode::SingleLine { .. });
11110
11111            if advance_downwards {
11112                let snapshot = this.buffer.read(cx).snapshot(cx);
11113
11114                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11115                    s.move_cursors_with(|display_snapshot, display_point, _| {
11116                        let mut point = display_point.to_point(display_snapshot);
11117                        point.row += 1;
11118                        point = snapshot.clip_point(point, Bias::Left);
11119                        let display_point = point.to_display_point(display_snapshot);
11120                        let goal = SelectionGoal::HorizontalPosition(
11121                            display_snapshot
11122                                .x_for_display_point(display_point, text_layout_details)
11123                                .into(),
11124                        );
11125                        (display_point, goal)
11126                    })
11127                });
11128            }
11129        });
11130    }
11131
11132    pub fn select_enclosing_symbol(
11133        &mut self,
11134        _: &SelectEnclosingSymbol,
11135        window: &mut Window,
11136        cx: &mut Context<Self>,
11137    ) {
11138        let buffer = self.buffer.read(cx).snapshot(cx);
11139        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
11140
11141        fn update_selection(
11142            selection: &Selection<usize>,
11143            buffer_snap: &MultiBufferSnapshot,
11144        ) -> Option<Selection<usize>> {
11145            let cursor = selection.head();
11146            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
11147            for symbol in symbols.iter().rev() {
11148                let start = symbol.range.start.to_offset(buffer_snap);
11149                let end = symbol.range.end.to_offset(buffer_snap);
11150                let new_range = start..end;
11151                if start < selection.start || end > selection.end {
11152                    return Some(Selection {
11153                        id: selection.id,
11154                        start: new_range.start,
11155                        end: new_range.end,
11156                        goal: SelectionGoal::None,
11157                        reversed: selection.reversed,
11158                    });
11159                }
11160            }
11161            None
11162        }
11163
11164        let mut selected_larger_symbol = false;
11165        let new_selections = old_selections
11166            .iter()
11167            .map(|selection| match update_selection(selection, &buffer) {
11168                Some(new_selection) => {
11169                    if new_selection.range() != selection.range() {
11170                        selected_larger_symbol = true;
11171                    }
11172                    new_selection
11173                }
11174                None => selection.clone(),
11175            })
11176            .collect::<Vec<_>>();
11177
11178        if selected_larger_symbol {
11179            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11180                s.select(new_selections);
11181            });
11182        }
11183    }
11184
11185    pub fn select_larger_syntax_node(
11186        &mut self,
11187        _: &SelectLargerSyntaxNode,
11188        window: &mut Window,
11189        cx: &mut Context<Self>,
11190    ) {
11191        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11192        let buffer = self.buffer.read(cx).snapshot(cx);
11193        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
11194
11195        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
11196        let mut selected_larger_node = false;
11197        let new_selections = old_selections
11198            .iter()
11199            .map(|selection| {
11200                let old_range = selection.start..selection.end;
11201                let mut new_range = old_range.clone();
11202                let mut new_node = None;
11203                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
11204                {
11205                    new_node = Some(node);
11206                    new_range = match containing_range {
11207                        MultiOrSingleBufferOffsetRange::Single(_) => break,
11208                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
11209                    };
11210                    if !display_map.intersects_fold(new_range.start)
11211                        && !display_map.intersects_fold(new_range.end)
11212                    {
11213                        break;
11214                    }
11215                }
11216
11217                if let Some(node) = new_node {
11218                    // Log the ancestor, to support using this action as a way to explore TreeSitter
11219                    // nodes. Parent and grandparent are also logged because this operation will not
11220                    // visit nodes that have the same range as their parent.
11221                    log::info!("Node: {node:?}");
11222                    let parent = node.parent();
11223                    log::info!("Parent: {parent:?}");
11224                    let grandparent = parent.and_then(|x| x.parent());
11225                    log::info!("Grandparent: {grandparent:?}");
11226                }
11227
11228                selected_larger_node |= new_range != old_range;
11229                Selection {
11230                    id: selection.id,
11231                    start: new_range.start,
11232                    end: new_range.end,
11233                    goal: SelectionGoal::None,
11234                    reversed: selection.reversed,
11235                }
11236            })
11237            .collect::<Vec<_>>();
11238
11239        if selected_larger_node {
11240            stack.push(old_selections);
11241            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11242                s.select(new_selections);
11243            });
11244        }
11245        self.select_larger_syntax_node_stack = stack;
11246    }
11247
11248    pub fn select_smaller_syntax_node(
11249        &mut self,
11250        _: &SelectSmallerSyntaxNode,
11251        window: &mut Window,
11252        cx: &mut Context<Self>,
11253    ) {
11254        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
11255        if let Some(selections) = stack.pop() {
11256            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11257                s.select(selections.to_vec());
11258            });
11259        }
11260        self.select_larger_syntax_node_stack = stack;
11261    }
11262
11263    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
11264        if !EditorSettings::get_global(cx).gutter.runnables {
11265            self.clear_tasks();
11266            return Task::ready(());
11267        }
11268        let project = self.project.as_ref().map(Entity::downgrade);
11269        cx.spawn_in(window, |this, mut cx| async move {
11270            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
11271            let Some(project) = project.and_then(|p| p.upgrade()) else {
11272                return;
11273            };
11274            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
11275                this.display_map.update(cx, |map, cx| map.snapshot(cx))
11276            }) else {
11277                return;
11278            };
11279
11280            let hide_runnables = project
11281                .update(&mut cx, |project, cx| {
11282                    // Do not display any test indicators in non-dev server remote projects.
11283                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
11284                })
11285                .unwrap_or(true);
11286            if hide_runnables {
11287                return;
11288            }
11289            let new_rows =
11290                cx.background_spawn({
11291                    let snapshot = display_snapshot.clone();
11292                    async move {
11293                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
11294                    }
11295                })
11296                    .await;
11297
11298            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
11299            this.update(&mut cx, |this, _| {
11300                this.clear_tasks();
11301                for (key, value) in rows {
11302                    this.insert_tasks(key, value);
11303                }
11304            })
11305            .ok();
11306        })
11307    }
11308    fn fetch_runnable_ranges(
11309        snapshot: &DisplaySnapshot,
11310        range: Range<Anchor>,
11311    ) -> Vec<language::RunnableRange> {
11312        snapshot.buffer_snapshot.runnable_ranges(range).collect()
11313    }
11314
11315    fn runnable_rows(
11316        project: Entity<Project>,
11317        snapshot: DisplaySnapshot,
11318        runnable_ranges: Vec<RunnableRange>,
11319        mut cx: AsyncWindowContext,
11320    ) -> Vec<((BufferId, u32), RunnableTasks)> {
11321        runnable_ranges
11322            .into_iter()
11323            .filter_map(|mut runnable| {
11324                let tasks = cx
11325                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
11326                    .ok()?;
11327                if tasks.is_empty() {
11328                    return None;
11329                }
11330
11331                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
11332
11333                let row = snapshot
11334                    .buffer_snapshot
11335                    .buffer_line_for_row(MultiBufferRow(point.row))?
11336                    .1
11337                    .start
11338                    .row;
11339
11340                let context_range =
11341                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
11342                Some((
11343                    (runnable.buffer_id, row),
11344                    RunnableTasks {
11345                        templates: tasks,
11346                        offset: snapshot
11347                            .buffer_snapshot
11348                            .anchor_before(runnable.run_range.start),
11349                        context_range,
11350                        column: point.column,
11351                        extra_variables: runnable.extra_captures,
11352                    },
11353                ))
11354            })
11355            .collect()
11356    }
11357
11358    fn templates_with_tags(
11359        project: &Entity<Project>,
11360        runnable: &mut Runnable,
11361        cx: &mut App,
11362    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
11363        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
11364            let (worktree_id, file) = project
11365                .buffer_for_id(runnable.buffer, cx)
11366                .and_then(|buffer| buffer.read(cx).file())
11367                .map(|file| (file.worktree_id(cx), file.clone()))
11368                .unzip();
11369
11370            (
11371                project.task_store().read(cx).task_inventory().cloned(),
11372                worktree_id,
11373                file,
11374            )
11375        });
11376
11377        let tags = mem::take(&mut runnable.tags);
11378        let mut tags: Vec<_> = tags
11379            .into_iter()
11380            .flat_map(|tag| {
11381                let tag = tag.0.clone();
11382                inventory
11383                    .as_ref()
11384                    .into_iter()
11385                    .flat_map(|inventory| {
11386                        inventory.read(cx).list_tasks(
11387                            file.clone(),
11388                            Some(runnable.language.clone()),
11389                            worktree_id,
11390                            cx,
11391                        )
11392                    })
11393                    .filter(move |(_, template)| {
11394                        template.tags.iter().any(|source_tag| source_tag == &tag)
11395                    })
11396            })
11397            .sorted_by_key(|(kind, _)| kind.to_owned())
11398            .collect();
11399        if let Some((leading_tag_source, _)) = tags.first() {
11400            // Strongest source wins; if we have worktree tag binding, prefer that to
11401            // global and language bindings;
11402            // if we have a global binding, prefer that to language binding.
11403            let first_mismatch = tags
11404                .iter()
11405                .position(|(tag_source, _)| tag_source != leading_tag_source);
11406            if let Some(index) = first_mismatch {
11407                tags.truncate(index);
11408            }
11409        }
11410
11411        tags
11412    }
11413
11414    pub fn move_to_enclosing_bracket(
11415        &mut self,
11416        _: &MoveToEnclosingBracket,
11417        window: &mut Window,
11418        cx: &mut Context<Self>,
11419    ) {
11420        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11421            s.move_offsets_with(|snapshot, selection| {
11422                let Some(enclosing_bracket_ranges) =
11423                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
11424                else {
11425                    return;
11426                };
11427
11428                let mut best_length = usize::MAX;
11429                let mut best_inside = false;
11430                let mut best_in_bracket_range = false;
11431                let mut best_destination = None;
11432                for (open, close) in enclosing_bracket_ranges {
11433                    let close = close.to_inclusive();
11434                    let length = close.end() - open.start;
11435                    let inside = selection.start >= open.end && selection.end <= *close.start();
11436                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
11437                        || close.contains(&selection.head());
11438
11439                    // If best is next to a bracket and current isn't, skip
11440                    if !in_bracket_range && best_in_bracket_range {
11441                        continue;
11442                    }
11443
11444                    // Prefer smaller lengths unless best is inside and current isn't
11445                    if length > best_length && (best_inside || !inside) {
11446                        continue;
11447                    }
11448
11449                    best_length = length;
11450                    best_inside = inside;
11451                    best_in_bracket_range = in_bracket_range;
11452                    best_destination = Some(
11453                        if close.contains(&selection.start) && close.contains(&selection.end) {
11454                            if inside {
11455                                open.end
11456                            } else {
11457                                open.start
11458                            }
11459                        } else if inside {
11460                            *close.start()
11461                        } else {
11462                            *close.end()
11463                        },
11464                    );
11465                }
11466
11467                if let Some(destination) = best_destination {
11468                    selection.collapse_to(destination, SelectionGoal::None);
11469                }
11470            })
11471        });
11472    }
11473
11474    pub fn undo_selection(
11475        &mut self,
11476        _: &UndoSelection,
11477        window: &mut Window,
11478        cx: &mut Context<Self>,
11479    ) {
11480        self.end_selection(window, cx);
11481        self.selection_history.mode = SelectionHistoryMode::Undoing;
11482        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
11483            self.change_selections(None, window, cx, |s| {
11484                s.select_anchors(entry.selections.to_vec())
11485            });
11486            self.select_next_state = entry.select_next_state;
11487            self.select_prev_state = entry.select_prev_state;
11488            self.add_selections_state = entry.add_selections_state;
11489            self.request_autoscroll(Autoscroll::newest(), cx);
11490        }
11491        self.selection_history.mode = SelectionHistoryMode::Normal;
11492    }
11493
11494    pub fn redo_selection(
11495        &mut self,
11496        _: &RedoSelection,
11497        window: &mut Window,
11498        cx: &mut Context<Self>,
11499    ) {
11500        self.end_selection(window, cx);
11501        self.selection_history.mode = SelectionHistoryMode::Redoing;
11502        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
11503            self.change_selections(None, window, cx, |s| {
11504                s.select_anchors(entry.selections.to_vec())
11505            });
11506            self.select_next_state = entry.select_next_state;
11507            self.select_prev_state = entry.select_prev_state;
11508            self.add_selections_state = entry.add_selections_state;
11509            self.request_autoscroll(Autoscroll::newest(), cx);
11510        }
11511        self.selection_history.mode = SelectionHistoryMode::Normal;
11512    }
11513
11514    pub fn expand_excerpts(
11515        &mut self,
11516        action: &ExpandExcerpts,
11517        _: &mut Window,
11518        cx: &mut Context<Self>,
11519    ) {
11520        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
11521    }
11522
11523    pub fn expand_excerpts_down(
11524        &mut self,
11525        action: &ExpandExcerptsDown,
11526        _: &mut Window,
11527        cx: &mut Context<Self>,
11528    ) {
11529        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
11530    }
11531
11532    pub fn expand_excerpts_up(
11533        &mut self,
11534        action: &ExpandExcerptsUp,
11535        _: &mut Window,
11536        cx: &mut Context<Self>,
11537    ) {
11538        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
11539    }
11540
11541    pub fn expand_excerpts_for_direction(
11542        &mut self,
11543        lines: u32,
11544        direction: ExpandExcerptDirection,
11545
11546        cx: &mut Context<Self>,
11547    ) {
11548        let selections = self.selections.disjoint_anchors();
11549
11550        let lines = if lines == 0 {
11551            EditorSettings::get_global(cx).expand_excerpt_lines
11552        } else {
11553            lines
11554        };
11555
11556        self.buffer.update(cx, |buffer, cx| {
11557            let snapshot = buffer.snapshot(cx);
11558            let mut excerpt_ids = selections
11559                .iter()
11560                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
11561                .collect::<Vec<_>>();
11562            excerpt_ids.sort();
11563            excerpt_ids.dedup();
11564            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
11565        })
11566    }
11567
11568    pub fn expand_excerpt(
11569        &mut self,
11570        excerpt: ExcerptId,
11571        direction: ExpandExcerptDirection,
11572        cx: &mut Context<Self>,
11573    ) {
11574        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
11575        self.buffer.update(cx, |buffer, cx| {
11576            buffer.expand_excerpts([excerpt], lines, direction, cx)
11577        })
11578    }
11579
11580    pub fn go_to_singleton_buffer_point(
11581        &mut self,
11582        point: Point,
11583        window: &mut Window,
11584        cx: &mut Context<Self>,
11585    ) {
11586        self.go_to_singleton_buffer_range(point..point, window, cx);
11587    }
11588
11589    pub fn go_to_singleton_buffer_range(
11590        &mut self,
11591        range: Range<Point>,
11592        window: &mut Window,
11593        cx: &mut Context<Self>,
11594    ) {
11595        let multibuffer = self.buffer().read(cx);
11596        let Some(buffer) = multibuffer.as_singleton() else {
11597            return;
11598        };
11599        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
11600            return;
11601        };
11602        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
11603            return;
11604        };
11605        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
11606            s.select_anchor_ranges([start..end])
11607        });
11608    }
11609
11610    fn go_to_diagnostic(
11611        &mut self,
11612        _: &GoToDiagnostic,
11613        window: &mut Window,
11614        cx: &mut Context<Self>,
11615    ) {
11616        self.go_to_diagnostic_impl(Direction::Next, window, cx)
11617    }
11618
11619    fn go_to_prev_diagnostic(
11620        &mut self,
11621        _: &GoToPreviousDiagnostic,
11622        window: &mut Window,
11623        cx: &mut Context<Self>,
11624    ) {
11625        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
11626    }
11627
11628    pub fn go_to_diagnostic_impl(
11629        &mut self,
11630        direction: Direction,
11631        window: &mut Window,
11632        cx: &mut Context<Self>,
11633    ) {
11634        let buffer = self.buffer.read(cx).snapshot(cx);
11635        let selection = self.selections.newest::<usize>(cx);
11636
11637        // If there is an active Diagnostic Popover jump to its diagnostic instead.
11638        if direction == Direction::Next {
11639            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
11640                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
11641                    return;
11642                };
11643                self.activate_diagnostics(
11644                    buffer_id,
11645                    popover.local_diagnostic.diagnostic.group_id,
11646                    window,
11647                    cx,
11648                );
11649                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
11650                    let primary_range_start = active_diagnostics.primary_range.start;
11651                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11652                        let mut new_selection = s.newest_anchor().clone();
11653                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
11654                        s.select_anchors(vec![new_selection.clone()]);
11655                    });
11656                    self.refresh_inline_completion(false, true, window, cx);
11657                }
11658                return;
11659            }
11660        }
11661
11662        let active_group_id = self
11663            .active_diagnostics
11664            .as_ref()
11665            .map(|active_group| active_group.group_id);
11666        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
11667            active_diagnostics
11668                .primary_range
11669                .to_offset(&buffer)
11670                .to_inclusive()
11671        });
11672        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
11673            if active_primary_range.contains(&selection.head()) {
11674                *active_primary_range.start()
11675            } else {
11676                selection.head()
11677            }
11678        } else {
11679            selection.head()
11680        };
11681
11682        let snapshot = self.snapshot(window, cx);
11683        let primary_diagnostics_before = buffer
11684            .diagnostics_in_range::<usize>(0..search_start)
11685            .filter(|entry| entry.diagnostic.is_primary)
11686            .filter(|entry| entry.range.start != entry.range.end)
11687            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11688            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
11689            .collect::<Vec<_>>();
11690        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
11691            primary_diagnostics_before
11692                .iter()
11693                .position(|entry| entry.diagnostic.group_id == active_group_id)
11694        });
11695
11696        let primary_diagnostics_after = buffer
11697            .diagnostics_in_range::<usize>(search_start..buffer.len())
11698            .filter(|entry| entry.diagnostic.is_primary)
11699            .filter(|entry| entry.range.start != entry.range.end)
11700            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11701            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
11702            .collect::<Vec<_>>();
11703        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
11704            primary_diagnostics_after
11705                .iter()
11706                .enumerate()
11707                .rev()
11708                .find_map(|(i, entry)| {
11709                    if entry.diagnostic.group_id == active_group_id {
11710                        Some(i)
11711                    } else {
11712                        None
11713                    }
11714                })
11715        });
11716
11717        let next_primary_diagnostic = match direction {
11718            Direction::Prev => primary_diagnostics_before
11719                .iter()
11720                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
11721                .rev()
11722                .next(),
11723            Direction::Next => primary_diagnostics_after
11724                .iter()
11725                .skip(
11726                    last_same_group_diagnostic_after
11727                        .map(|index| index + 1)
11728                        .unwrap_or(0),
11729                )
11730                .next(),
11731        };
11732
11733        // Cycle around to the start of the buffer, potentially moving back to the start of
11734        // the currently active diagnostic.
11735        let cycle_around = || match direction {
11736            Direction::Prev => primary_diagnostics_after
11737                .iter()
11738                .rev()
11739                .chain(primary_diagnostics_before.iter().rev())
11740                .next(),
11741            Direction::Next => primary_diagnostics_before
11742                .iter()
11743                .chain(primary_diagnostics_after.iter())
11744                .next(),
11745        };
11746
11747        if let Some((primary_range, group_id)) = next_primary_diagnostic
11748            .or_else(cycle_around)
11749            .map(|entry| (&entry.range, entry.diagnostic.group_id))
11750        {
11751            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
11752                return;
11753            };
11754            self.activate_diagnostics(buffer_id, group_id, window, cx);
11755            if self.active_diagnostics.is_some() {
11756                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11757                    s.select(vec![Selection {
11758                        id: selection.id,
11759                        start: primary_range.start,
11760                        end: primary_range.start,
11761                        reversed: false,
11762                        goal: SelectionGoal::None,
11763                    }]);
11764                });
11765                self.refresh_inline_completion(false, true, window, cx);
11766            }
11767        }
11768    }
11769
11770    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
11771        let snapshot = self.snapshot(window, cx);
11772        let selection = self.selections.newest::<Point>(cx);
11773        self.go_to_hunk_before_or_after_position(
11774            &snapshot,
11775            selection.head(),
11776            Direction::Next,
11777            window,
11778            cx,
11779        );
11780    }
11781
11782    fn go_to_hunk_before_or_after_position(
11783        &mut self,
11784        snapshot: &EditorSnapshot,
11785        position: Point,
11786        direction: Direction,
11787        window: &mut Window,
11788        cx: &mut Context<Editor>,
11789    ) {
11790        let row = if direction == Direction::Next {
11791            self.hunk_after_position(snapshot, position)
11792                .map(|hunk| hunk.row_range.start)
11793        } else {
11794            self.hunk_before_position(snapshot, position)
11795        };
11796
11797        if let Some(row) = row {
11798            let destination = Point::new(row.0, 0);
11799            let autoscroll = Autoscroll::center();
11800
11801            self.unfold_ranges(&[destination..destination], false, false, cx);
11802            self.change_selections(Some(autoscroll), window, cx, |s| {
11803                s.select_ranges([destination..destination]);
11804            });
11805        }
11806    }
11807
11808    fn hunk_after_position(
11809        &mut self,
11810        snapshot: &EditorSnapshot,
11811        position: Point,
11812    ) -> Option<MultiBufferDiffHunk> {
11813        snapshot
11814            .buffer_snapshot
11815            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
11816            .find(|hunk| hunk.row_range.start.0 > position.row)
11817            .or_else(|| {
11818                snapshot
11819                    .buffer_snapshot
11820                    .diff_hunks_in_range(Point::zero()..position)
11821                    .find(|hunk| hunk.row_range.end.0 < position.row)
11822            })
11823    }
11824
11825    fn go_to_prev_hunk(
11826        &mut self,
11827        _: &GoToPreviousHunk,
11828        window: &mut Window,
11829        cx: &mut Context<Self>,
11830    ) {
11831        let snapshot = self.snapshot(window, cx);
11832        let selection = self.selections.newest::<Point>(cx);
11833        self.go_to_hunk_before_or_after_position(
11834            &snapshot,
11835            selection.head(),
11836            Direction::Prev,
11837            window,
11838            cx,
11839        );
11840    }
11841
11842    fn hunk_before_position(
11843        &mut self,
11844        snapshot: &EditorSnapshot,
11845        position: Point,
11846    ) -> Option<MultiBufferRow> {
11847        snapshot
11848            .buffer_snapshot
11849            .diff_hunk_before(position)
11850            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
11851    }
11852
11853    pub fn go_to_definition(
11854        &mut self,
11855        _: &GoToDefinition,
11856        window: &mut Window,
11857        cx: &mut Context<Self>,
11858    ) -> Task<Result<Navigated>> {
11859        let definition =
11860            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
11861        cx.spawn_in(window, |editor, mut cx| async move {
11862            if definition.await? == Navigated::Yes {
11863                return Ok(Navigated::Yes);
11864            }
11865            match editor.update_in(&mut cx, |editor, window, cx| {
11866                editor.find_all_references(&FindAllReferences, window, cx)
11867            })? {
11868                Some(references) => references.await,
11869                None => Ok(Navigated::No),
11870            }
11871        })
11872    }
11873
11874    pub fn go_to_declaration(
11875        &mut self,
11876        _: &GoToDeclaration,
11877        window: &mut Window,
11878        cx: &mut Context<Self>,
11879    ) -> Task<Result<Navigated>> {
11880        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
11881    }
11882
11883    pub fn go_to_declaration_split(
11884        &mut self,
11885        _: &GoToDeclaration,
11886        window: &mut Window,
11887        cx: &mut Context<Self>,
11888    ) -> Task<Result<Navigated>> {
11889        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
11890    }
11891
11892    pub fn go_to_implementation(
11893        &mut self,
11894        _: &GoToImplementation,
11895        window: &mut Window,
11896        cx: &mut Context<Self>,
11897    ) -> Task<Result<Navigated>> {
11898        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
11899    }
11900
11901    pub fn go_to_implementation_split(
11902        &mut self,
11903        _: &GoToImplementationSplit,
11904        window: &mut Window,
11905        cx: &mut Context<Self>,
11906    ) -> Task<Result<Navigated>> {
11907        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
11908    }
11909
11910    pub fn go_to_type_definition(
11911        &mut self,
11912        _: &GoToTypeDefinition,
11913        window: &mut Window,
11914        cx: &mut Context<Self>,
11915    ) -> Task<Result<Navigated>> {
11916        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
11917    }
11918
11919    pub fn go_to_definition_split(
11920        &mut self,
11921        _: &GoToDefinitionSplit,
11922        window: &mut Window,
11923        cx: &mut Context<Self>,
11924    ) -> Task<Result<Navigated>> {
11925        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
11926    }
11927
11928    pub fn go_to_type_definition_split(
11929        &mut self,
11930        _: &GoToTypeDefinitionSplit,
11931        window: &mut Window,
11932        cx: &mut Context<Self>,
11933    ) -> Task<Result<Navigated>> {
11934        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
11935    }
11936
11937    fn go_to_definition_of_kind(
11938        &mut self,
11939        kind: GotoDefinitionKind,
11940        split: bool,
11941        window: &mut Window,
11942        cx: &mut Context<Self>,
11943    ) -> Task<Result<Navigated>> {
11944        let Some(provider) = self.semantics_provider.clone() else {
11945            return Task::ready(Ok(Navigated::No));
11946        };
11947        let head = self.selections.newest::<usize>(cx).head();
11948        let buffer = self.buffer.read(cx);
11949        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
11950            text_anchor
11951        } else {
11952            return Task::ready(Ok(Navigated::No));
11953        };
11954
11955        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
11956            return Task::ready(Ok(Navigated::No));
11957        };
11958
11959        cx.spawn_in(window, |editor, mut cx| async move {
11960            let definitions = definitions.await?;
11961            let navigated = editor
11962                .update_in(&mut cx, |editor, window, cx| {
11963                    editor.navigate_to_hover_links(
11964                        Some(kind),
11965                        definitions
11966                            .into_iter()
11967                            .filter(|location| {
11968                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
11969                            })
11970                            .map(HoverLink::Text)
11971                            .collect::<Vec<_>>(),
11972                        split,
11973                        window,
11974                        cx,
11975                    )
11976                })?
11977                .await?;
11978            anyhow::Ok(navigated)
11979        })
11980    }
11981
11982    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
11983        let selection = self.selections.newest_anchor();
11984        let head = selection.head();
11985        let tail = selection.tail();
11986
11987        let Some((buffer, start_position)) =
11988            self.buffer.read(cx).text_anchor_for_position(head, cx)
11989        else {
11990            return;
11991        };
11992
11993        let end_position = if head != tail {
11994            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
11995                return;
11996            };
11997            Some(pos)
11998        } else {
11999            None
12000        };
12001
12002        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
12003            let url = if let Some(end_pos) = end_position {
12004                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
12005            } else {
12006                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
12007            };
12008
12009            if let Some(url) = url {
12010                editor.update(&mut cx, |_, cx| {
12011                    cx.open_url(&url);
12012                })
12013            } else {
12014                Ok(())
12015            }
12016        });
12017
12018        url_finder.detach();
12019    }
12020
12021    pub fn open_selected_filename(
12022        &mut self,
12023        _: &OpenSelectedFilename,
12024        window: &mut Window,
12025        cx: &mut Context<Self>,
12026    ) {
12027        let Some(workspace) = self.workspace() else {
12028            return;
12029        };
12030
12031        let position = self.selections.newest_anchor().head();
12032
12033        let Some((buffer, buffer_position)) =
12034            self.buffer.read(cx).text_anchor_for_position(position, cx)
12035        else {
12036            return;
12037        };
12038
12039        let project = self.project.clone();
12040
12041        cx.spawn_in(window, |_, mut cx| async move {
12042            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
12043
12044            if let Some((_, path)) = result {
12045                workspace
12046                    .update_in(&mut cx, |workspace, window, cx| {
12047                        workspace.open_resolved_path(path, window, cx)
12048                    })?
12049                    .await?;
12050            }
12051            anyhow::Ok(())
12052        })
12053        .detach();
12054    }
12055
12056    pub(crate) fn navigate_to_hover_links(
12057        &mut self,
12058        kind: Option<GotoDefinitionKind>,
12059        mut definitions: Vec<HoverLink>,
12060        split: bool,
12061        window: &mut Window,
12062        cx: &mut Context<Editor>,
12063    ) -> Task<Result<Navigated>> {
12064        // If there is one definition, just open it directly
12065        if definitions.len() == 1 {
12066            let definition = definitions.pop().unwrap();
12067
12068            enum TargetTaskResult {
12069                Location(Option<Location>),
12070                AlreadyNavigated,
12071            }
12072
12073            let target_task = match definition {
12074                HoverLink::Text(link) => {
12075                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
12076                }
12077                HoverLink::InlayHint(lsp_location, server_id) => {
12078                    let computation =
12079                        self.compute_target_location(lsp_location, server_id, window, cx);
12080                    cx.background_spawn(async move {
12081                        let location = computation.await?;
12082                        Ok(TargetTaskResult::Location(location))
12083                    })
12084                }
12085                HoverLink::Url(url) => {
12086                    cx.open_url(&url);
12087                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
12088                }
12089                HoverLink::File(path) => {
12090                    if let Some(workspace) = self.workspace() {
12091                        cx.spawn_in(window, |_, mut cx| async move {
12092                            workspace
12093                                .update_in(&mut cx, |workspace, window, cx| {
12094                                    workspace.open_resolved_path(path, window, cx)
12095                                })?
12096                                .await
12097                                .map(|_| TargetTaskResult::AlreadyNavigated)
12098                        })
12099                    } else {
12100                        Task::ready(Ok(TargetTaskResult::Location(None)))
12101                    }
12102                }
12103            };
12104            cx.spawn_in(window, |editor, mut cx| async move {
12105                let target = match target_task.await.context("target resolution task")? {
12106                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
12107                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
12108                    TargetTaskResult::Location(Some(target)) => target,
12109                };
12110
12111                editor.update_in(&mut cx, |editor, window, cx| {
12112                    let Some(workspace) = editor.workspace() else {
12113                        return Navigated::No;
12114                    };
12115                    let pane = workspace.read(cx).active_pane().clone();
12116
12117                    let range = target.range.to_point(target.buffer.read(cx));
12118                    let range = editor.range_for_match(&range);
12119                    let range = collapse_multiline_range(range);
12120
12121                    if !split
12122                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
12123                    {
12124                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
12125                    } else {
12126                        window.defer(cx, move |window, cx| {
12127                            let target_editor: Entity<Self> =
12128                                workspace.update(cx, |workspace, cx| {
12129                                    let pane = if split {
12130                                        workspace.adjacent_pane(window, cx)
12131                                    } else {
12132                                        workspace.active_pane().clone()
12133                                    };
12134
12135                                    workspace.open_project_item(
12136                                        pane,
12137                                        target.buffer.clone(),
12138                                        true,
12139                                        true,
12140                                        window,
12141                                        cx,
12142                                    )
12143                                });
12144                            target_editor.update(cx, |target_editor, cx| {
12145                                // When selecting a definition in a different buffer, disable the nav history
12146                                // to avoid creating a history entry at the previous cursor location.
12147                                pane.update(cx, |pane, _| pane.disable_history());
12148                                target_editor.go_to_singleton_buffer_range(range, window, cx);
12149                                pane.update(cx, |pane, _| pane.enable_history());
12150                            });
12151                        });
12152                    }
12153                    Navigated::Yes
12154                })
12155            })
12156        } else if !definitions.is_empty() {
12157            cx.spawn_in(window, |editor, mut cx| async move {
12158                let (title, location_tasks, workspace) = editor
12159                    .update_in(&mut cx, |editor, window, cx| {
12160                        let tab_kind = match kind {
12161                            Some(GotoDefinitionKind::Implementation) => "Implementations",
12162                            _ => "Definitions",
12163                        };
12164                        let title = definitions
12165                            .iter()
12166                            .find_map(|definition| match definition {
12167                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
12168                                    let buffer = origin.buffer.read(cx);
12169                                    format!(
12170                                        "{} for {}",
12171                                        tab_kind,
12172                                        buffer
12173                                            .text_for_range(origin.range.clone())
12174                                            .collect::<String>()
12175                                    )
12176                                }),
12177                                HoverLink::InlayHint(_, _) => None,
12178                                HoverLink::Url(_) => None,
12179                                HoverLink::File(_) => None,
12180                            })
12181                            .unwrap_or(tab_kind.to_string());
12182                        let location_tasks = definitions
12183                            .into_iter()
12184                            .map(|definition| match definition {
12185                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
12186                                HoverLink::InlayHint(lsp_location, server_id) => editor
12187                                    .compute_target_location(lsp_location, server_id, window, cx),
12188                                HoverLink::Url(_) => Task::ready(Ok(None)),
12189                                HoverLink::File(_) => Task::ready(Ok(None)),
12190                            })
12191                            .collect::<Vec<_>>();
12192                        (title, location_tasks, editor.workspace().clone())
12193                    })
12194                    .context("location tasks preparation")?;
12195
12196                let locations = future::join_all(location_tasks)
12197                    .await
12198                    .into_iter()
12199                    .filter_map(|location| location.transpose())
12200                    .collect::<Result<_>>()
12201                    .context("location tasks")?;
12202
12203                let Some(workspace) = workspace else {
12204                    return Ok(Navigated::No);
12205                };
12206                let opened = workspace
12207                    .update_in(&mut cx, |workspace, window, cx| {
12208                        Self::open_locations_in_multibuffer(
12209                            workspace,
12210                            locations,
12211                            title,
12212                            split,
12213                            MultibufferSelectionMode::First,
12214                            window,
12215                            cx,
12216                        )
12217                    })
12218                    .ok();
12219
12220                anyhow::Ok(Navigated::from_bool(opened.is_some()))
12221            })
12222        } else {
12223            Task::ready(Ok(Navigated::No))
12224        }
12225    }
12226
12227    fn compute_target_location(
12228        &self,
12229        lsp_location: lsp::Location,
12230        server_id: LanguageServerId,
12231        window: &mut Window,
12232        cx: &mut Context<Self>,
12233    ) -> Task<anyhow::Result<Option<Location>>> {
12234        let Some(project) = self.project.clone() else {
12235            return Task::ready(Ok(None));
12236        };
12237
12238        cx.spawn_in(window, move |editor, mut cx| async move {
12239            let location_task = editor.update(&mut cx, |_, cx| {
12240                project.update(cx, |project, cx| {
12241                    let language_server_name = project
12242                        .language_server_statuses(cx)
12243                        .find(|(id, _)| server_id == *id)
12244                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
12245                    language_server_name.map(|language_server_name| {
12246                        project.open_local_buffer_via_lsp(
12247                            lsp_location.uri.clone(),
12248                            server_id,
12249                            language_server_name,
12250                            cx,
12251                        )
12252                    })
12253                })
12254            })?;
12255            let location = match location_task {
12256                Some(task) => Some({
12257                    let target_buffer_handle = task.await.context("open local buffer")?;
12258                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
12259                        let target_start = target_buffer
12260                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
12261                        let target_end = target_buffer
12262                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
12263                        target_buffer.anchor_after(target_start)
12264                            ..target_buffer.anchor_before(target_end)
12265                    })?;
12266                    Location {
12267                        buffer: target_buffer_handle,
12268                        range,
12269                    }
12270                }),
12271                None => None,
12272            };
12273            Ok(location)
12274        })
12275    }
12276
12277    pub fn find_all_references(
12278        &mut self,
12279        _: &FindAllReferences,
12280        window: &mut Window,
12281        cx: &mut Context<Self>,
12282    ) -> Option<Task<Result<Navigated>>> {
12283        let selection = self.selections.newest::<usize>(cx);
12284        let multi_buffer = self.buffer.read(cx);
12285        let head = selection.head();
12286
12287        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12288        let head_anchor = multi_buffer_snapshot.anchor_at(
12289            head,
12290            if head < selection.tail() {
12291                Bias::Right
12292            } else {
12293                Bias::Left
12294            },
12295        );
12296
12297        match self
12298            .find_all_references_task_sources
12299            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
12300        {
12301            Ok(_) => {
12302                log::info!(
12303                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
12304                );
12305                return None;
12306            }
12307            Err(i) => {
12308                self.find_all_references_task_sources.insert(i, head_anchor);
12309            }
12310        }
12311
12312        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
12313        let workspace = self.workspace()?;
12314        let project = workspace.read(cx).project().clone();
12315        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
12316        Some(cx.spawn_in(window, |editor, mut cx| async move {
12317            let _cleanup = defer({
12318                let mut cx = cx.clone();
12319                move || {
12320                    let _ = editor.update(&mut cx, |editor, _| {
12321                        if let Ok(i) =
12322                            editor
12323                                .find_all_references_task_sources
12324                                .binary_search_by(|anchor| {
12325                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
12326                                })
12327                        {
12328                            editor.find_all_references_task_sources.remove(i);
12329                        }
12330                    });
12331                }
12332            });
12333
12334            let locations = references.await?;
12335            if locations.is_empty() {
12336                return anyhow::Ok(Navigated::No);
12337            }
12338
12339            workspace.update_in(&mut cx, |workspace, window, cx| {
12340                let title = locations
12341                    .first()
12342                    .as_ref()
12343                    .map(|location| {
12344                        let buffer = location.buffer.read(cx);
12345                        format!(
12346                            "References to `{}`",
12347                            buffer
12348                                .text_for_range(location.range.clone())
12349                                .collect::<String>()
12350                        )
12351                    })
12352                    .unwrap();
12353                Self::open_locations_in_multibuffer(
12354                    workspace,
12355                    locations,
12356                    title,
12357                    false,
12358                    MultibufferSelectionMode::First,
12359                    window,
12360                    cx,
12361                );
12362                Navigated::Yes
12363            })
12364        }))
12365    }
12366
12367    /// Opens a multibuffer with the given project locations in it
12368    pub fn open_locations_in_multibuffer(
12369        workspace: &mut Workspace,
12370        mut locations: Vec<Location>,
12371        title: String,
12372        split: bool,
12373        multibuffer_selection_mode: MultibufferSelectionMode,
12374        window: &mut Window,
12375        cx: &mut Context<Workspace>,
12376    ) {
12377        // If there are multiple definitions, open them in a multibuffer
12378        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
12379        let mut locations = locations.into_iter().peekable();
12380        let mut ranges = Vec::new();
12381        let capability = workspace.project().read(cx).capability();
12382
12383        let excerpt_buffer = cx.new(|cx| {
12384            let mut multibuffer = MultiBuffer::new(capability);
12385            while let Some(location) = locations.next() {
12386                let buffer = location.buffer.read(cx);
12387                let mut ranges_for_buffer = Vec::new();
12388                let range = location.range.to_offset(buffer);
12389                ranges_for_buffer.push(range.clone());
12390
12391                while let Some(next_location) = locations.peek() {
12392                    if next_location.buffer == location.buffer {
12393                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
12394                        locations.next();
12395                    } else {
12396                        break;
12397                    }
12398                }
12399
12400                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
12401                ranges.extend(multibuffer.push_excerpts_with_context_lines(
12402                    location.buffer.clone(),
12403                    ranges_for_buffer,
12404                    DEFAULT_MULTIBUFFER_CONTEXT,
12405                    cx,
12406                ))
12407            }
12408
12409            multibuffer.with_title(title)
12410        });
12411
12412        let editor = cx.new(|cx| {
12413            Editor::for_multibuffer(
12414                excerpt_buffer,
12415                Some(workspace.project().clone()),
12416                window,
12417                cx,
12418            )
12419        });
12420        editor.update(cx, |editor, cx| {
12421            match multibuffer_selection_mode {
12422                MultibufferSelectionMode::First => {
12423                    if let Some(first_range) = ranges.first() {
12424                        editor.change_selections(None, window, cx, |selections| {
12425                            selections.clear_disjoint();
12426                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
12427                        });
12428                    }
12429                    editor.highlight_background::<Self>(
12430                        &ranges,
12431                        |theme| theme.editor_highlighted_line_background,
12432                        cx,
12433                    );
12434                }
12435                MultibufferSelectionMode::All => {
12436                    editor.change_selections(None, window, cx, |selections| {
12437                        selections.clear_disjoint();
12438                        selections.select_anchor_ranges(ranges);
12439                    });
12440                }
12441            }
12442            editor.register_buffers_with_language_servers(cx);
12443        });
12444
12445        let item = Box::new(editor);
12446        let item_id = item.item_id();
12447
12448        if split {
12449            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
12450        } else {
12451            if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
12452                let (preview_item_id, preview_item_idx) =
12453                    workspace.active_pane().update(cx, |pane, _| {
12454                        (pane.preview_item_id(), pane.preview_item_idx())
12455                    });
12456
12457                workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
12458
12459                if let Some(preview_item_id) = preview_item_id {
12460                    workspace.active_pane().update(cx, |pane, cx| {
12461                        pane.remove_item(preview_item_id, false, false, window, cx);
12462                    });
12463                }
12464            } else {
12465                workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
12466            }
12467        }
12468        workspace.active_pane().update(cx, |pane, cx| {
12469            pane.set_preview_item_id(Some(item_id), cx);
12470        });
12471    }
12472
12473    pub fn rename(
12474        &mut self,
12475        _: &Rename,
12476        window: &mut Window,
12477        cx: &mut Context<Self>,
12478    ) -> Option<Task<Result<()>>> {
12479        use language::ToOffset as _;
12480
12481        let provider = self.semantics_provider.clone()?;
12482        let selection = self.selections.newest_anchor().clone();
12483        let (cursor_buffer, cursor_buffer_position) = self
12484            .buffer
12485            .read(cx)
12486            .text_anchor_for_position(selection.head(), cx)?;
12487        let (tail_buffer, cursor_buffer_position_end) = self
12488            .buffer
12489            .read(cx)
12490            .text_anchor_for_position(selection.tail(), cx)?;
12491        if tail_buffer != cursor_buffer {
12492            return None;
12493        }
12494
12495        let snapshot = cursor_buffer.read(cx).snapshot();
12496        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
12497        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
12498        let prepare_rename = provider
12499            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
12500            .unwrap_or_else(|| Task::ready(Ok(None)));
12501        drop(snapshot);
12502
12503        Some(cx.spawn_in(window, |this, mut cx| async move {
12504            let rename_range = if let Some(range) = prepare_rename.await? {
12505                Some(range)
12506            } else {
12507                this.update(&mut cx, |this, cx| {
12508                    let buffer = this.buffer.read(cx).snapshot(cx);
12509                    let mut buffer_highlights = this
12510                        .document_highlights_for_position(selection.head(), &buffer)
12511                        .filter(|highlight| {
12512                            highlight.start.excerpt_id == selection.head().excerpt_id
12513                                && highlight.end.excerpt_id == selection.head().excerpt_id
12514                        });
12515                    buffer_highlights
12516                        .next()
12517                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
12518                })?
12519            };
12520            if let Some(rename_range) = rename_range {
12521                this.update_in(&mut cx, |this, window, cx| {
12522                    let snapshot = cursor_buffer.read(cx).snapshot();
12523                    let rename_buffer_range = rename_range.to_offset(&snapshot);
12524                    let cursor_offset_in_rename_range =
12525                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
12526                    let cursor_offset_in_rename_range_end =
12527                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
12528
12529                    this.take_rename(false, window, cx);
12530                    let buffer = this.buffer.read(cx).read(cx);
12531                    let cursor_offset = selection.head().to_offset(&buffer);
12532                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
12533                    let rename_end = rename_start + rename_buffer_range.len();
12534                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
12535                    let mut old_highlight_id = None;
12536                    let old_name: Arc<str> = buffer
12537                        .chunks(rename_start..rename_end, true)
12538                        .map(|chunk| {
12539                            if old_highlight_id.is_none() {
12540                                old_highlight_id = chunk.syntax_highlight_id;
12541                            }
12542                            chunk.text
12543                        })
12544                        .collect::<String>()
12545                        .into();
12546
12547                    drop(buffer);
12548
12549                    // Position the selection in the rename editor so that it matches the current selection.
12550                    this.show_local_selections = false;
12551                    let rename_editor = cx.new(|cx| {
12552                        let mut editor = Editor::single_line(window, cx);
12553                        editor.buffer.update(cx, |buffer, cx| {
12554                            buffer.edit([(0..0, old_name.clone())], None, cx)
12555                        });
12556                        let rename_selection_range = match cursor_offset_in_rename_range
12557                            .cmp(&cursor_offset_in_rename_range_end)
12558                        {
12559                            Ordering::Equal => {
12560                                editor.select_all(&SelectAll, window, cx);
12561                                return editor;
12562                            }
12563                            Ordering::Less => {
12564                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
12565                            }
12566                            Ordering::Greater => {
12567                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
12568                            }
12569                        };
12570                        if rename_selection_range.end > old_name.len() {
12571                            editor.select_all(&SelectAll, window, cx);
12572                        } else {
12573                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12574                                s.select_ranges([rename_selection_range]);
12575                            });
12576                        }
12577                        editor
12578                    });
12579                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
12580                        if e == &EditorEvent::Focused {
12581                            cx.emit(EditorEvent::FocusedIn)
12582                        }
12583                    })
12584                    .detach();
12585
12586                    let write_highlights =
12587                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
12588                    let read_highlights =
12589                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
12590                    let ranges = write_highlights
12591                        .iter()
12592                        .flat_map(|(_, ranges)| ranges.iter())
12593                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
12594                        .cloned()
12595                        .collect();
12596
12597                    this.highlight_text::<Rename>(
12598                        ranges,
12599                        HighlightStyle {
12600                            fade_out: Some(0.6),
12601                            ..Default::default()
12602                        },
12603                        cx,
12604                    );
12605                    let rename_focus_handle = rename_editor.focus_handle(cx);
12606                    window.focus(&rename_focus_handle);
12607                    let block_id = this.insert_blocks(
12608                        [BlockProperties {
12609                            style: BlockStyle::Flex,
12610                            placement: BlockPlacement::Below(range.start),
12611                            height: 1,
12612                            render: Arc::new({
12613                                let rename_editor = rename_editor.clone();
12614                                move |cx: &mut BlockContext| {
12615                                    let mut text_style = cx.editor_style.text.clone();
12616                                    if let Some(highlight_style) = old_highlight_id
12617                                        .and_then(|h| h.style(&cx.editor_style.syntax))
12618                                    {
12619                                        text_style = text_style.highlight(highlight_style);
12620                                    }
12621                                    div()
12622                                        .block_mouse_down()
12623                                        .pl(cx.anchor_x)
12624                                        .child(EditorElement::new(
12625                                            &rename_editor,
12626                                            EditorStyle {
12627                                                background: cx.theme().system().transparent,
12628                                                local_player: cx.editor_style.local_player,
12629                                                text: text_style,
12630                                                scrollbar_width: cx.editor_style.scrollbar_width,
12631                                                syntax: cx.editor_style.syntax.clone(),
12632                                                status: cx.editor_style.status.clone(),
12633                                                inlay_hints_style: HighlightStyle {
12634                                                    font_weight: Some(FontWeight::BOLD),
12635                                                    ..make_inlay_hints_style(cx.app)
12636                                                },
12637                                                inline_completion_styles: make_suggestion_styles(
12638                                                    cx.app,
12639                                                ),
12640                                                ..EditorStyle::default()
12641                                            },
12642                                        ))
12643                                        .into_any_element()
12644                                }
12645                            }),
12646                            priority: 0,
12647                        }],
12648                        Some(Autoscroll::fit()),
12649                        cx,
12650                    )[0];
12651                    this.pending_rename = Some(RenameState {
12652                        range,
12653                        old_name,
12654                        editor: rename_editor,
12655                        block_id,
12656                    });
12657                })?;
12658            }
12659
12660            Ok(())
12661        }))
12662    }
12663
12664    pub fn confirm_rename(
12665        &mut self,
12666        _: &ConfirmRename,
12667        window: &mut Window,
12668        cx: &mut Context<Self>,
12669    ) -> Option<Task<Result<()>>> {
12670        let rename = self.take_rename(false, window, cx)?;
12671        let workspace = self.workspace()?.downgrade();
12672        let (buffer, start) = self
12673            .buffer
12674            .read(cx)
12675            .text_anchor_for_position(rename.range.start, cx)?;
12676        let (end_buffer, _) = self
12677            .buffer
12678            .read(cx)
12679            .text_anchor_for_position(rename.range.end, cx)?;
12680        if buffer != end_buffer {
12681            return None;
12682        }
12683
12684        let old_name = rename.old_name;
12685        let new_name = rename.editor.read(cx).text(cx);
12686
12687        let rename = self.semantics_provider.as_ref()?.perform_rename(
12688            &buffer,
12689            start,
12690            new_name.clone(),
12691            cx,
12692        )?;
12693
12694        Some(cx.spawn_in(window, |editor, mut cx| async move {
12695            let project_transaction = rename.await?;
12696            Self::open_project_transaction(
12697                &editor,
12698                workspace,
12699                project_transaction,
12700                format!("Rename: {}{}", old_name, new_name),
12701                cx.clone(),
12702            )
12703            .await?;
12704
12705            editor.update(&mut cx, |editor, cx| {
12706                editor.refresh_document_highlights(cx);
12707            })?;
12708            Ok(())
12709        }))
12710    }
12711
12712    fn take_rename(
12713        &mut self,
12714        moving_cursor: bool,
12715        window: &mut Window,
12716        cx: &mut Context<Self>,
12717    ) -> Option<RenameState> {
12718        let rename = self.pending_rename.take()?;
12719        if rename.editor.focus_handle(cx).is_focused(window) {
12720            window.focus(&self.focus_handle);
12721        }
12722
12723        self.remove_blocks(
12724            [rename.block_id].into_iter().collect(),
12725            Some(Autoscroll::fit()),
12726            cx,
12727        );
12728        self.clear_highlights::<Rename>(cx);
12729        self.show_local_selections = true;
12730
12731        if moving_cursor {
12732            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
12733                editor.selections.newest::<usize>(cx).head()
12734            });
12735
12736            // Update the selection to match the position of the selection inside
12737            // the rename editor.
12738            let snapshot = self.buffer.read(cx).read(cx);
12739            let rename_range = rename.range.to_offset(&snapshot);
12740            let cursor_in_editor = snapshot
12741                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
12742                .min(rename_range.end);
12743            drop(snapshot);
12744
12745            self.change_selections(None, window, cx, |s| {
12746                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
12747            });
12748        } else {
12749            self.refresh_document_highlights(cx);
12750        }
12751
12752        Some(rename)
12753    }
12754
12755    pub fn pending_rename(&self) -> Option<&RenameState> {
12756        self.pending_rename.as_ref()
12757    }
12758
12759    fn format(
12760        &mut self,
12761        _: &Format,
12762        window: &mut Window,
12763        cx: &mut Context<Self>,
12764    ) -> Option<Task<Result<()>>> {
12765        let project = match &self.project {
12766            Some(project) => project.clone(),
12767            None => return None,
12768        };
12769
12770        Some(self.perform_format(
12771            project,
12772            FormatTrigger::Manual,
12773            FormatTarget::Buffers,
12774            window,
12775            cx,
12776        ))
12777    }
12778
12779    fn format_selections(
12780        &mut self,
12781        _: &FormatSelections,
12782        window: &mut Window,
12783        cx: &mut Context<Self>,
12784    ) -> Option<Task<Result<()>>> {
12785        let project = match &self.project {
12786            Some(project) => project.clone(),
12787            None => return None,
12788        };
12789
12790        let ranges = self
12791            .selections
12792            .all_adjusted(cx)
12793            .into_iter()
12794            .map(|selection| selection.range())
12795            .collect_vec();
12796
12797        Some(self.perform_format(
12798            project,
12799            FormatTrigger::Manual,
12800            FormatTarget::Ranges(ranges),
12801            window,
12802            cx,
12803        ))
12804    }
12805
12806    fn perform_format(
12807        &mut self,
12808        project: Entity<Project>,
12809        trigger: FormatTrigger,
12810        target: FormatTarget,
12811        window: &mut Window,
12812        cx: &mut Context<Self>,
12813    ) -> Task<Result<()>> {
12814        let buffer = self.buffer.clone();
12815        let (buffers, target) = match target {
12816            FormatTarget::Buffers => {
12817                let mut buffers = buffer.read(cx).all_buffers();
12818                if trigger == FormatTrigger::Save {
12819                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
12820                }
12821                (buffers, LspFormatTarget::Buffers)
12822            }
12823            FormatTarget::Ranges(selection_ranges) => {
12824                let multi_buffer = buffer.read(cx);
12825                let snapshot = multi_buffer.read(cx);
12826                let mut buffers = HashSet::default();
12827                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
12828                    BTreeMap::new();
12829                for selection_range in selection_ranges {
12830                    for (buffer, buffer_range, _) in
12831                        snapshot.range_to_buffer_ranges(selection_range)
12832                    {
12833                        let buffer_id = buffer.remote_id();
12834                        let start = buffer.anchor_before(buffer_range.start);
12835                        let end = buffer.anchor_after(buffer_range.end);
12836                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
12837                        buffer_id_to_ranges
12838                            .entry(buffer_id)
12839                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
12840                            .or_insert_with(|| vec![start..end]);
12841                    }
12842                }
12843                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
12844            }
12845        };
12846
12847        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
12848        let format = project.update(cx, |project, cx| {
12849            project.format(buffers, target, true, trigger, cx)
12850        });
12851
12852        cx.spawn_in(window, |_, mut cx| async move {
12853            let transaction = futures::select_biased! {
12854                transaction = format.log_err().fuse() => transaction,
12855                () = timeout => {
12856                    log::warn!("timed out waiting for formatting");
12857                    None
12858                }
12859            };
12860
12861            buffer
12862                .update(&mut cx, |buffer, cx| {
12863                    if let Some(transaction) = transaction {
12864                        if !buffer.is_singleton() {
12865                            buffer.push_transaction(&transaction.0, cx);
12866                        }
12867                    }
12868                    cx.notify();
12869                })
12870                .ok();
12871
12872            Ok(())
12873        })
12874    }
12875
12876    fn organize_imports(
12877        &mut self,
12878        _: &OrganizeImports,
12879        window: &mut Window,
12880        cx: &mut Context<Self>,
12881    ) -> Option<Task<Result<()>>> {
12882        let project = match &self.project {
12883            Some(project) => project.clone(),
12884            None => return None,
12885        };
12886        Some(self.perform_code_action_kind(
12887            project,
12888            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
12889            window,
12890            cx,
12891        ))
12892    }
12893
12894    fn perform_code_action_kind(
12895        &mut self,
12896        project: Entity<Project>,
12897        kind: CodeActionKind,
12898        window: &mut Window,
12899        cx: &mut Context<Self>,
12900    ) -> Task<Result<()>> {
12901        let buffer = self.buffer.clone();
12902        let buffers = buffer.read(cx).all_buffers();
12903        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
12904        let apply_action = project.update(cx, |project, cx| {
12905            project.apply_code_action_kind(buffers, kind, true, cx)
12906        });
12907        cx.spawn_in(window, |_, mut cx| async move {
12908            let transaction = futures::select_biased! {
12909                () = timeout => {
12910                    log::warn!("timed out waiting for executing code action");
12911                    None
12912                }
12913                transaction = apply_action.log_err().fuse() => transaction,
12914            };
12915            buffer
12916                .update(&mut cx, |buffer, cx| {
12917                    // check if we need this
12918                    if let Some(transaction) = transaction {
12919                        if !buffer.is_singleton() {
12920                            buffer.push_transaction(&transaction.0, cx);
12921                        }
12922                    }
12923                    cx.notify();
12924                })
12925                .ok();
12926            Ok(())
12927        })
12928    }
12929
12930    fn restart_language_server(
12931        &mut self,
12932        _: &RestartLanguageServer,
12933        _: &mut Window,
12934        cx: &mut Context<Self>,
12935    ) {
12936        if let Some(project) = self.project.clone() {
12937            self.buffer.update(cx, |multi_buffer, cx| {
12938                project.update(cx, |project, cx| {
12939                    project.restart_language_servers_for_buffers(
12940                        multi_buffer.all_buffers().into_iter().collect(),
12941                        cx,
12942                    );
12943                });
12944            })
12945        }
12946    }
12947
12948    fn cancel_language_server_work(
12949        workspace: &mut Workspace,
12950        _: &actions::CancelLanguageServerWork,
12951        _: &mut Window,
12952        cx: &mut Context<Workspace>,
12953    ) {
12954        let project = workspace.project();
12955        let buffers = workspace
12956            .active_item(cx)
12957            .and_then(|item| item.act_as::<Editor>(cx))
12958            .map_or(HashSet::default(), |editor| {
12959                editor.read(cx).buffer.read(cx).all_buffers()
12960            });
12961        project.update(cx, |project, cx| {
12962            project.cancel_language_server_work_for_buffers(buffers, cx);
12963        });
12964    }
12965
12966    fn show_character_palette(
12967        &mut self,
12968        _: &ShowCharacterPalette,
12969        window: &mut Window,
12970        _: &mut Context<Self>,
12971    ) {
12972        window.show_character_palette();
12973    }
12974
12975    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
12976        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
12977            let buffer = self.buffer.read(cx).snapshot(cx);
12978            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
12979            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
12980            let is_valid = buffer
12981                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
12982                .any(|entry| {
12983                    entry.diagnostic.is_primary
12984                        && !entry.range.is_empty()
12985                        && entry.range.start == primary_range_start
12986                        && entry.diagnostic.message == active_diagnostics.primary_message
12987                });
12988
12989            if is_valid != active_diagnostics.is_valid {
12990                active_diagnostics.is_valid = is_valid;
12991                if is_valid {
12992                    let mut new_styles = HashMap::default();
12993                    for (block_id, diagnostic) in &active_diagnostics.blocks {
12994                        new_styles.insert(
12995                            *block_id,
12996                            diagnostic_block_renderer(diagnostic.clone(), None, true),
12997                        );
12998                    }
12999                    self.display_map.update(cx, |display_map, _cx| {
13000                        display_map.replace_blocks(new_styles);
13001                    });
13002                } else {
13003                    self.dismiss_diagnostics(cx);
13004                }
13005            }
13006        }
13007    }
13008
13009    fn activate_diagnostics(
13010        &mut self,
13011        buffer_id: BufferId,
13012        group_id: usize,
13013        window: &mut Window,
13014        cx: &mut Context<Self>,
13015    ) {
13016        self.dismiss_diagnostics(cx);
13017        let snapshot = self.snapshot(window, cx);
13018        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
13019            let buffer = self.buffer.read(cx).snapshot(cx);
13020
13021            let mut primary_range = None;
13022            let mut primary_message = None;
13023            let diagnostic_group = buffer
13024                .diagnostic_group(buffer_id, group_id)
13025                .filter_map(|entry| {
13026                    let start = entry.range.start;
13027                    let end = entry.range.end;
13028                    if snapshot.is_line_folded(MultiBufferRow(start.row))
13029                        && (start.row == end.row
13030                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
13031                    {
13032                        return None;
13033                    }
13034                    if entry.diagnostic.is_primary {
13035                        primary_range = Some(entry.range.clone());
13036                        primary_message = Some(entry.diagnostic.message.clone());
13037                    }
13038                    Some(entry)
13039                })
13040                .collect::<Vec<_>>();
13041            let primary_range = primary_range?;
13042            let primary_message = primary_message?;
13043
13044            let blocks = display_map
13045                .insert_blocks(
13046                    diagnostic_group.iter().map(|entry| {
13047                        let diagnostic = entry.diagnostic.clone();
13048                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
13049                        BlockProperties {
13050                            style: BlockStyle::Fixed,
13051                            placement: BlockPlacement::Below(
13052                                buffer.anchor_after(entry.range.start),
13053                            ),
13054                            height: message_height,
13055                            render: diagnostic_block_renderer(diagnostic, None, true),
13056                            priority: 0,
13057                        }
13058                    }),
13059                    cx,
13060                )
13061                .into_iter()
13062                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
13063                .collect();
13064
13065            Some(ActiveDiagnosticGroup {
13066                primary_range: buffer.anchor_before(primary_range.start)
13067                    ..buffer.anchor_after(primary_range.end),
13068                primary_message,
13069                group_id,
13070                blocks,
13071                is_valid: true,
13072            })
13073        });
13074    }
13075
13076    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
13077        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
13078            self.display_map.update(cx, |display_map, cx| {
13079                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
13080            });
13081            cx.notify();
13082        }
13083    }
13084
13085    /// Disable inline diagnostics rendering for this editor.
13086    pub fn disable_inline_diagnostics(&mut self) {
13087        self.inline_diagnostics_enabled = false;
13088        self.inline_diagnostics_update = Task::ready(());
13089        self.inline_diagnostics.clear();
13090    }
13091
13092    pub fn inline_diagnostics_enabled(&self) -> bool {
13093        self.inline_diagnostics_enabled
13094    }
13095
13096    pub fn show_inline_diagnostics(&self) -> bool {
13097        self.show_inline_diagnostics
13098    }
13099
13100    pub fn toggle_inline_diagnostics(
13101        &mut self,
13102        _: &ToggleInlineDiagnostics,
13103        window: &mut Window,
13104        cx: &mut Context<'_, Editor>,
13105    ) {
13106        self.show_inline_diagnostics = !self.show_inline_diagnostics;
13107        self.refresh_inline_diagnostics(false, window, cx);
13108    }
13109
13110    fn refresh_inline_diagnostics(
13111        &mut self,
13112        debounce: bool,
13113        window: &mut Window,
13114        cx: &mut Context<Self>,
13115    ) {
13116        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
13117            self.inline_diagnostics_update = Task::ready(());
13118            self.inline_diagnostics.clear();
13119            return;
13120        }
13121
13122        let debounce_ms = ProjectSettings::get_global(cx)
13123            .diagnostics
13124            .inline
13125            .update_debounce_ms;
13126        let debounce = if debounce && debounce_ms > 0 {
13127            Some(Duration::from_millis(debounce_ms))
13128        } else {
13129            None
13130        };
13131        self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
13132            if let Some(debounce) = debounce {
13133                cx.background_executor().timer(debounce).await;
13134            }
13135            let Some(snapshot) = editor
13136                .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
13137                .ok()
13138            else {
13139                return;
13140            };
13141
13142            let new_inline_diagnostics = cx
13143                .background_spawn(async move {
13144                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
13145                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
13146                        let message = diagnostic_entry
13147                            .diagnostic
13148                            .message
13149                            .split_once('\n')
13150                            .map(|(line, _)| line)
13151                            .map(SharedString::new)
13152                            .unwrap_or_else(|| {
13153                                SharedString::from(diagnostic_entry.diagnostic.message)
13154                            });
13155                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
13156                        let (Ok(i) | Err(i)) = inline_diagnostics
13157                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
13158                        inline_diagnostics.insert(
13159                            i,
13160                            (
13161                                start_anchor,
13162                                InlineDiagnostic {
13163                                    message,
13164                                    group_id: diagnostic_entry.diagnostic.group_id,
13165                                    start: diagnostic_entry.range.start.to_point(&snapshot),
13166                                    is_primary: diagnostic_entry.diagnostic.is_primary,
13167                                    severity: diagnostic_entry.diagnostic.severity,
13168                                },
13169                            ),
13170                        );
13171                    }
13172                    inline_diagnostics
13173                })
13174                .await;
13175
13176            editor
13177                .update(&mut cx, |editor, cx| {
13178                    editor.inline_diagnostics = new_inline_diagnostics;
13179                    cx.notify();
13180                })
13181                .ok();
13182        });
13183    }
13184
13185    pub fn set_selections_from_remote(
13186        &mut self,
13187        selections: Vec<Selection<Anchor>>,
13188        pending_selection: Option<Selection<Anchor>>,
13189        window: &mut Window,
13190        cx: &mut Context<Self>,
13191    ) {
13192        let old_cursor_position = self.selections.newest_anchor().head();
13193        self.selections.change_with(cx, |s| {
13194            s.select_anchors(selections);
13195            if let Some(pending_selection) = pending_selection {
13196                s.set_pending(pending_selection, SelectMode::Character);
13197            } else {
13198                s.clear_pending();
13199            }
13200        });
13201        self.selections_did_change(false, &old_cursor_position, true, window, cx);
13202    }
13203
13204    fn push_to_selection_history(&mut self) {
13205        self.selection_history.push(SelectionHistoryEntry {
13206            selections: self.selections.disjoint_anchors(),
13207            select_next_state: self.select_next_state.clone(),
13208            select_prev_state: self.select_prev_state.clone(),
13209            add_selections_state: self.add_selections_state.clone(),
13210        });
13211    }
13212
13213    pub fn transact(
13214        &mut self,
13215        window: &mut Window,
13216        cx: &mut Context<Self>,
13217        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
13218    ) -> Option<TransactionId> {
13219        self.start_transaction_at(Instant::now(), window, cx);
13220        update(self, window, cx);
13221        self.end_transaction_at(Instant::now(), cx)
13222    }
13223
13224    pub fn start_transaction_at(
13225        &mut self,
13226        now: Instant,
13227        window: &mut Window,
13228        cx: &mut Context<Self>,
13229    ) {
13230        self.end_selection(window, cx);
13231        if let Some(tx_id) = self
13232            .buffer
13233            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
13234        {
13235            self.selection_history
13236                .insert_transaction(tx_id, self.selections.disjoint_anchors());
13237            cx.emit(EditorEvent::TransactionBegun {
13238                transaction_id: tx_id,
13239            })
13240        }
13241    }
13242
13243    pub fn end_transaction_at(
13244        &mut self,
13245        now: Instant,
13246        cx: &mut Context<Self>,
13247    ) -> Option<TransactionId> {
13248        if let Some(transaction_id) = self
13249            .buffer
13250            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
13251        {
13252            if let Some((_, end_selections)) =
13253                self.selection_history.transaction_mut(transaction_id)
13254            {
13255                *end_selections = Some(self.selections.disjoint_anchors());
13256            } else {
13257                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
13258            }
13259
13260            cx.emit(EditorEvent::Edited { transaction_id });
13261            Some(transaction_id)
13262        } else {
13263            None
13264        }
13265    }
13266
13267    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
13268        if self.selection_mark_mode {
13269            self.change_selections(None, window, cx, |s| {
13270                s.move_with(|_, sel| {
13271                    sel.collapse_to(sel.head(), SelectionGoal::None);
13272                });
13273            })
13274        }
13275        self.selection_mark_mode = true;
13276        cx.notify();
13277    }
13278
13279    pub fn swap_selection_ends(
13280        &mut self,
13281        _: &actions::SwapSelectionEnds,
13282        window: &mut Window,
13283        cx: &mut Context<Self>,
13284    ) {
13285        self.change_selections(None, window, cx, |s| {
13286            s.move_with(|_, sel| {
13287                if sel.start != sel.end {
13288                    sel.reversed = !sel.reversed
13289                }
13290            });
13291        });
13292        self.request_autoscroll(Autoscroll::newest(), cx);
13293        cx.notify();
13294    }
13295
13296    pub fn toggle_fold(
13297        &mut self,
13298        _: &actions::ToggleFold,
13299        window: &mut Window,
13300        cx: &mut Context<Self>,
13301    ) {
13302        if self.is_singleton(cx) {
13303            let selection = self.selections.newest::<Point>(cx);
13304
13305            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13306            let range = if selection.is_empty() {
13307                let point = selection.head().to_display_point(&display_map);
13308                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13309                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13310                    .to_point(&display_map);
13311                start..end
13312            } else {
13313                selection.range()
13314            };
13315            if display_map.folds_in_range(range).next().is_some() {
13316                self.unfold_lines(&Default::default(), window, cx)
13317            } else {
13318                self.fold(&Default::default(), window, cx)
13319            }
13320        } else {
13321            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13322            let buffer_ids: HashSet<_> = self
13323                .selections
13324                .disjoint_anchor_ranges()
13325                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13326                .collect();
13327
13328            let should_unfold = buffer_ids
13329                .iter()
13330                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
13331
13332            for buffer_id in buffer_ids {
13333                if should_unfold {
13334                    self.unfold_buffer(buffer_id, cx);
13335                } else {
13336                    self.fold_buffer(buffer_id, cx);
13337                }
13338            }
13339        }
13340    }
13341
13342    pub fn toggle_fold_recursive(
13343        &mut self,
13344        _: &actions::ToggleFoldRecursive,
13345        window: &mut Window,
13346        cx: &mut Context<Self>,
13347    ) {
13348        let selection = self.selections.newest::<Point>(cx);
13349
13350        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13351        let range = if selection.is_empty() {
13352            let point = selection.head().to_display_point(&display_map);
13353            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13354            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13355                .to_point(&display_map);
13356            start..end
13357        } else {
13358            selection.range()
13359        };
13360        if display_map.folds_in_range(range).next().is_some() {
13361            self.unfold_recursive(&Default::default(), window, cx)
13362        } else {
13363            self.fold_recursive(&Default::default(), window, cx)
13364        }
13365    }
13366
13367    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
13368        if self.is_singleton(cx) {
13369            let mut to_fold = Vec::new();
13370            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13371            let selections = self.selections.all_adjusted(cx);
13372
13373            for selection in selections {
13374                let range = selection.range().sorted();
13375                let buffer_start_row = range.start.row;
13376
13377                if range.start.row != range.end.row {
13378                    let mut found = false;
13379                    let mut row = range.start.row;
13380                    while row <= range.end.row {
13381                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
13382                        {
13383                            found = true;
13384                            row = crease.range().end.row + 1;
13385                            to_fold.push(crease);
13386                        } else {
13387                            row += 1
13388                        }
13389                    }
13390                    if found {
13391                        continue;
13392                    }
13393                }
13394
13395                for row in (0..=range.start.row).rev() {
13396                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13397                        if crease.range().end.row >= buffer_start_row {
13398                            to_fold.push(crease);
13399                            if row <= range.start.row {
13400                                break;
13401                            }
13402                        }
13403                    }
13404                }
13405            }
13406
13407            self.fold_creases(to_fold, true, window, cx);
13408        } else {
13409            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13410            let buffer_ids = self
13411                .selections
13412                .disjoint_anchor_ranges()
13413                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13414                .collect::<HashSet<_>>();
13415            for buffer_id in buffer_ids {
13416                self.fold_buffer(buffer_id, cx);
13417            }
13418        }
13419    }
13420
13421    fn fold_at_level(
13422        &mut self,
13423        fold_at: &FoldAtLevel,
13424        window: &mut Window,
13425        cx: &mut Context<Self>,
13426    ) {
13427        if !self.buffer.read(cx).is_singleton() {
13428            return;
13429        }
13430
13431        let fold_at_level = fold_at.0;
13432        let snapshot = self.buffer.read(cx).snapshot(cx);
13433        let mut to_fold = Vec::new();
13434        let mut stack = vec![(0, snapshot.max_row().0, 1)];
13435
13436        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
13437            while start_row < end_row {
13438                match self
13439                    .snapshot(window, cx)
13440                    .crease_for_buffer_row(MultiBufferRow(start_row))
13441                {
13442                    Some(crease) => {
13443                        let nested_start_row = crease.range().start.row + 1;
13444                        let nested_end_row = crease.range().end.row;
13445
13446                        if current_level < fold_at_level {
13447                            stack.push((nested_start_row, nested_end_row, current_level + 1));
13448                        } else if current_level == fold_at_level {
13449                            to_fold.push(crease);
13450                        }
13451
13452                        start_row = nested_end_row + 1;
13453                    }
13454                    None => start_row += 1,
13455                }
13456            }
13457        }
13458
13459        self.fold_creases(to_fold, true, window, cx);
13460    }
13461
13462    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
13463        if self.buffer.read(cx).is_singleton() {
13464            let mut fold_ranges = Vec::new();
13465            let snapshot = self.buffer.read(cx).snapshot(cx);
13466
13467            for row in 0..snapshot.max_row().0 {
13468                if let Some(foldable_range) = self
13469                    .snapshot(window, cx)
13470                    .crease_for_buffer_row(MultiBufferRow(row))
13471                {
13472                    fold_ranges.push(foldable_range);
13473                }
13474            }
13475
13476            self.fold_creases(fold_ranges, true, window, cx);
13477        } else {
13478            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
13479                editor
13480                    .update_in(&mut cx, |editor, _, cx| {
13481                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13482                            editor.fold_buffer(buffer_id, cx);
13483                        }
13484                    })
13485                    .ok();
13486            });
13487        }
13488    }
13489
13490    pub fn fold_function_bodies(
13491        &mut self,
13492        _: &actions::FoldFunctionBodies,
13493        window: &mut Window,
13494        cx: &mut Context<Self>,
13495    ) {
13496        let snapshot = self.buffer.read(cx).snapshot(cx);
13497
13498        let ranges = snapshot
13499            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
13500            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
13501            .collect::<Vec<_>>();
13502
13503        let creases = ranges
13504            .into_iter()
13505            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
13506            .collect();
13507
13508        self.fold_creases(creases, true, window, cx);
13509    }
13510
13511    pub fn fold_recursive(
13512        &mut self,
13513        _: &actions::FoldRecursive,
13514        window: &mut Window,
13515        cx: &mut Context<Self>,
13516    ) {
13517        let mut to_fold = Vec::new();
13518        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13519        let selections = self.selections.all_adjusted(cx);
13520
13521        for selection in selections {
13522            let range = selection.range().sorted();
13523            let buffer_start_row = range.start.row;
13524
13525            if range.start.row != range.end.row {
13526                let mut found = false;
13527                for row in range.start.row..=range.end.row {
13528                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13529                        found = true;
13530                        to_fold.push(crease);
13531                    }
13532                }
13533                if found {
13534                    continue;
13535                }
13536            }
13537
13538            for row in (0..=range.start.row).rev() {
13539                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13540                    if crease.range().end.row >= buffer_start_row {
13541                        to_fold.push(crease);
13542                    } else {
13543                        break;
13544                    }
13545                }
13546            }
13547        }
13548
13549        self.fold_creases(to_fold, true, window, cx);
13550    }
13551
13552    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
13553        let buffer_row = fold_at.buffer_row;
13554        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13555
13556        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
13557            let autoscroll = self
13558                .selections
13559                .all::<Point>(cx)
13560                .iter()
13561                .any(|selection| crease.range().overlaps(&selection.range()));
13562
13563            self.fold_creases(vec![crease], autoscroll, window, cx);
13564        }
13565    }
13566
13567    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
13568        if self.is_singleton(cx) {
13569            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13570            let buffer = &display_map.buffer_snapshot;
13571            let selections = self.selections.all::<Point>(cx);
13572            let ranges = selections
13573                .iter()
13574                .map(|s| {
13575                    let range = s.display_range(&display_map).sorted();
13576                    let mut start = range.start.to_point(&display_map);
13577                    let mut end = range.end.to_point(&display_map);
13578                    start.column = 0;
13579                    end.column = buffer.line_len(MultiBufferRow(end.row));
13580                    start..end
13581                })
13582                .collect::<Vec<_>>();
13583
13584            self.unfold_ranges(&ranges, true, true, cx);
13585        } else {
13586            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13587            let buffer_ids = self
13588                .selections
13589                .disjoint_anchor_ranges()
13590                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13591                .collect::<HashSet<_>>();
13592            for buffer_id in buffer_ids {
13593                self.unfold_buffer(buffer_id, cx);
13594            }
13595        }
13596    }
13597
13598    pub fn unfold_recursive(
13599        &mut self,
13600        _: &UnfoldRecursive,
13601        _window: &mut Window,
13602        cx: &mut Context<Self>,
13603    ) {
13604        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13605        let selections = self.selections.all::<Point>(cx);
13606        let ranges = selections
13607            .iter()
13608            .map(|s| {
13609                let mut range = s.display_range(&display_map).sorted();
13610                *range.start.column_mut() = 0;
13611                *range.end.column_mut() = display_map.line_len(range.end.row());
13612                let start = range.start.to_point(&display_map);
13613                let end = range.end.to_point(&display_map);
13614                start..end
13615            })
13616            .collect::<Vec<_>>();
13617
13618        self.unfold_ranges(&ranges, true, true, cx);
13619    }
13620
13621    pub fn unfold_at(
13622        &mut self,
13623        unfold_at: &UnfoldAt,
13624        _window: &mut Window,
13625        cx: &mut Context<Self>,
13626    ) {
13627        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13628
13629        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
13630            ..Point::new(
13631                unfold_at.buffer_row.0,
13632                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
13633            );
13634
13635        let autoscroll = self
13636            .selections
13637            .all::<Point>(cx)
13638            .iter()
13639            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
13640
13641        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
13642    }
13643
13644    pub fn unfold_all(
13645        &mut self,
13646        _: &actions::UnfoldAll,
13647        _window: &mut Window,
13648        cx: &mut Context<Self>,
13649    ) {
13650        if self.buffer.read(cx).is_singleton() {
13651            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13652            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
13653        } else {
13654            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
13655                editor
13656                    .update(&mut cx, |editor, cx| {
13657                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13658                            editor.unfold_buffer(buffer_id, cx);
13659                        }
13660                    })
13661                    .ok();
13662            });
13663        }
13664    }
13665
13666    pub fn fold_selected_ranges(
13667        &mut self,
13668        _: &FoldSelectedRanges,
13669        window: &mut Window,
13670        cx: &mut Context<Self>,
13671    ) {
13672        let selections = self.selections.all::<Point>(cx);
13673        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13674        let line_mode = self.selections.line_mode;
13675        let ranges = selections
13676            .into_iter()
13677            .map(|s| {
13678                if line_mode {
13679                    let start = Point::new(s.start.row, 0);
13680                    let end = Point::new(
13681                        s.end.row,
13682                        display_map
13683                            .buffer_snapshot
13684                            .line_len(MultiBufferRow(s.end.row)),
13685                    );
13686                    Crease::simple(start..end, display_map.fold_placeholder.clone())
13687                } else {
13688                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
13689                }
13690            })
13691            .collect::<Vec<_>>();
13692        self.fold_creases(ranges, true, window, cx);
13693    }
13694
13695    pub fn fold_ranges<T: ToOffset + Clone>(
13696        &mut self,
13697        ranges: Vec<Range<T>>,
13698        auto_scroll: bool,
13699        window: &mut Window,
13700        cx: &mut Context<Self>,
13701    ) {
13702        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13703        let ranges = ranges
13704            .into_iter()
13705            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
13706            .collect::<Vec<_>>();
13707        self.fold_creases(ranges, auto_scroll, window, cx);
13708    }
13709
13710    pub fn fold_creases<T: ToOffset + Clone>(
13711        &mut self,
13712        creases: Vec<Crease<T>>,
13713        auto_scroll: bool,
13714        window: &mut Window,
13715        cx: &mut Context<Self>,
13716    ) {
13717        if creases.is_empty() {
13718            return;
13719        }
13720
13721        let mut buffers_affected = HashSet::default();
13722        let multi_buffer = self.buffer().read(cx);
13723        for crease in &creases {
13724            if let Some((_, buffer, _)) =
13725                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
13726            {
13727                buffers_affected.insert(buffer.read(cx).remote_id());
13728            };
13729        }
13730
13731        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
13732
13733        if auto_scroll {
13734            self.request_autoscroll(Autoscroll::fit(), cx);
13735        }
13736
13737        cx.notify();
13738
13739        if let Some(active_diagnostics) = self.active_diagnostics.take() {
13740            // Clear diagnostics block when folding a range that contains it.
13741            let snapshot = self.snapshot(window, cx);
13742            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
13743                drop(snapshot);
13744                self.active_diagnostics = Some(active_diagnostics);
13745                self.dismiss_diagnostics(cx);
13746            } else {
13747                self.active_diagnostics = Some(active_diagnostics);
13748            }
13749        }
13750
13751        self.scrollbar_marker_state.dirty = true;
13752    }
13753
13754    /// Removes any folds whose ranges intersect any of the given ranges.
13755    pub fn unfold_ranges<T: ToOffset + Clone>(
13756        &mut self,
13757        ranges: &[Range<T>],
13758        inclusive: bool,
13759        auto_scroll: bool,
13760        cx: &mut Context<Self>,
13761    ) {
13762        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13763            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
13764        });
13765    }
13766
13767    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13768        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
13769            return;
13770        }
13771        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13772        self.display_map.update(cx, |display_map, cx| {
13773            display_map.fold_buffers([buffer_id], cx)
13774        });
13775        cx.emit(EditorEvent::BufferFoldToggled {
13776            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
13777            folded: true,
13778        });
13779        cx.notify();
13780    }
13781
13782    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13783        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
13784            return;
13785        }
13786        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13787        self.display_map.update(cx, |display_map, cx| {
13788            display_map.unfold_buffers([buffer_id], cx);
13789        });
13790        cx.emit(EditorEvent::BufferFoldToggled {
13791            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
13792            folded: false,
13793        });
13794        cx.notify();
13795    }
13796
13797    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
13798        self.display_map.read(cx).is_buffer_folded(buffer)
13799    }
13800
13801    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
13802        self.display_map.read(cx).folded_buffers()
13803    }
13804
13805    /// Removes any folds with the given ranges.
13806    pub fn remove_folds_with_type<T: ToOffset + Clone>(
13807        &mut self,
13808        ranges: &[Range<T>],
13809        type_id: TypeId,
13810        auto_scroll: bool,
13811        cx: &mut Context<Self>,
13812    ) {
13813        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13814            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
13815        });
13816    }
13817
13818    fn remove_folds_with<T: ToOffset + Clone>(
13819        &mut self,
13820        ranges: &[Range<T>],
13821        auto_scroll: bool,
13822        cx: &mut Context<Self>,
13823        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
13824    ) {
13825        if ranges.is_empty() {
13826            return;
13827        }
13828
13829        let mut buffers_affected = HashSet::default();
13830        let multi_buffer = self.buffer().read(cx);
13831        for range in ranges {
13832            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
13833                buffers_affected.insert(buffer.read(cx).remote_id());
13834            };
13835        }
13836
13837        self.display_map.update(cx, update);
13838
13839        if auto_scroll {
13840            self.request_autoscroll(Autoscroll::fit(), cx);
13841        }
13842
13843        cx.notify();
13844        self.scrollbar_marker_state.dirty = true;
13845        self.active_indent_guides_state.dirty = true;
13846    }
13847
13848    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
13849        self.display_map.read(cx).fold_placeholder.clone()
13850    }
13851
13852    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
13853        self.buffer.update(cx, |buffer, cx| {
13854            buffer.set_all_diff_hunks_expanded(cx);
13855        });
13856    }
13857
13858    pub fn expand_all_diff_hunks(
13859        &mut self,
13860        _: &ExpandAllDiffHunks,
13861        _window: &mut Window,
13862        cx: &mut Context<Self>,
13863    ) {
13864        self.buffer.update(cx, |buffer, cx| {
13865            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
13866        });
13867    }
13868
13869    pub fn toggle_selected_diff_hunks(
13870        &mut self,
13871        _: &ToggleSelectedDiffHunks,
13872        _window: &mut Window,
13873        cx: &mut Context<Self>,
13874    ) {
13875        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13876        self.toggle_diff_hunks_in_ranges(ranges, cx);
13877    }
13878
13879    pub fn diff_hunks_in_ranges<'a>(
13880        &'a self,
13881        ranges: &'a [Range<Anchor>],
13882        buffer: &'a MultiBufferSnapshot,
13883    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
13884        ranges.iter().flat_map(move |range| {
13885            let end_excerpt_id = range.end.excerpt_id;
13886            let range = range.to_point(buffer);
13887            let mut peek_end = range.end;
13888            if range.end.row < buffer.max_row().0 {
13889                peek_end = Point::new(range.end.row + 1, 0);
13890            }
13891            buffer
13892                .diff_hunks_in_range(range.start..peek_end)
13893                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
13894        })
13895    }
13896
13897    pub fn has_stageable_diff_hunks_in_ranges(
13898        &self,
13899        ranges: &[Range<Anchor>],
13900        snapshot: &MultiBufferSnapshot,
13901    ) -> bool {
13902        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
13903        hunks.any(|hunk| hunk.status().has_secondary_hunk())
13904    }
13905
13906    pub fn toggle_staged_selected_diff_hunks(
13907        &mut self,
13908        _: &::git::ToggleStaged,
13909        _: &mut Window,
13910        cx: &mut Context<Self>,
13911    ) {
13912        let snapshot = self.buffer.read(cx).snapshot(cx);
13913        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13914        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
13915        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13916    }
13917
13918    pub fn stage_and_next(
13919        &mut self,
13920        _: &::git::StageAndNext,
13921        window: &mut Window,
13922        cx: &mut Context<Self>,
13923    ) {
13924        self.do_stage_or_unstage_and_next(true, window, cx);
13925    }
13926
13927    pub fn unstage_and_next(
13928        &mut self,
13929        _: &::git::UnstageAndNext,
13930        window: &mut Window,
13931        cx: &mut Context<Self>,
13932    ) {
13933        self.do_stage_or_unstage_and_next(false, window, cx);
13934    }
13935
13936    pub fn stage_or_unstage_diff_hunks(
13937        &mut self,
13938        stage: bool,
13939        ranges: Vec<Range<Anchor>>,
13940        cx: &mut Context<Self>,
13941    ) {
13942        let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
13943        cx.spawn(|this, mut cx| async move {
13944            task.await?;
13945            this.update(&mut cx, |this, cx| {
13946                let snapshot = this.buffer.read(cx).snapshot(cx);
13947                let chunk_by = this
13948                    .diff_hunks_in_ranges(&ranges, &snapshot)
13949                    .chunk_by(|hunk| hunk.buffer_id);
13950                for (buffer_id, hunks) in &chunk_by {
13951                    this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
13952                }
13953            })
13954        })
13955        .detach_and_log_err(cx);
13956    }
13957
13958    fn save_buffers_for_ranges_if_needed(
13959        &mut self,
13960        ranges: &[Range<Anchor>],
13961        cx: &mut Context<'_, Editor>,
13962    ) -> Task<Result<()>> {
13963        let multibuffer = self.buffer.read(cx);
13964        let snapshot = multibuffer.read(cx);
13965        let buffer_ids: HashSet<_> = ranges
13966            .iter()
13967            .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
13968            .collect();
13969        drop(snapshot);
13970
13971        let mut buffers = HashSet::default();
13972        for buffer_id in buffer_ids {
13973            if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
13974                let buffer = buffer_entity.read(cx);
13975                if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
13976                {
13977                    buffers.insert(buffer_entity);
13978                }
13979            }
13980        }
13981
13982        if let Some(project) = &self.project {
13983            project.update(cx, |project, cx| project.save_buffers(buffers, cx))
13984        } else {
13985            Task::ready(Ok(()))
13986        }
13987    }
13988
13989    fn do_stage_or_unstage_and_next(
13990        &mut self,
13991        stage: bool,
13992        window: &mut Window,
13993        cx: &mut Context<Self>,
13994    ) {
13995        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
13996
13997        if ranges.iter().any(|range| range.start != range.end) {
13998            self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13999            return;
14000        }
14001
14002        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
14003        let snapshot = self.snapshot(window, cx);
14004        let position = self.selections.newest::<Point>(cx).head();
14005        let mut row = snapshot
14006            .buffer_snapshot
14007            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
14008            .find(|hunk| hunk.row_range.start.0 > position.row)
14009            .map(|hunk| hunk.row_range.start);
14010
14011        let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
14012        // Outside of the project diff editor, wrap around to the beginning.
14013        if !all_diff_hunks_expanded {
14014            row = row.or_else(|| {
14015                snapshot
14016                    .buffer_snapshot
14017                    .diff_hunks_in_range(Point::zero()..position)
14018                    .find(|hunk| hunk.row_range.end.0 < position.row)
14019                    .map(|hunk| hunk.row_range.start)
14020            });
14021        }
14022
14023        if let Some(row) = row {
14024            let destination = Point::new(row.0, 0);
14025            let autoscroll = Autoscroll::center();
14026
14027            self.unfold_ranges(&[destination..destination], false, false, cx);
14028            self.change_selections(Some(autoscroll), window, cx, |s| {
14029                s.select_ranges([destination..destination]);
14030            });
14031        }
14032    }
14033
14034    fn do_stage_or_unstage(
14035        &self,
14036        stage: bool,
14037        buffer_id: BufferId,
14038        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
14039        cx: &mut App,
14040    ) -> Option<()> {
14041        let project = self.project.as_ref()?;
14042        let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
14043        let diff = self.buffer.read(cx).diff_for(buffer_id)?;
14044        let buffer_snapshot = buffer.read(cx).snapshot();
14045        let file_exists = buffer_snapshot
14046            .file()
14047            .is_some_and(|file| file.disk_state().exists());
14048        diff.update(cx, |diff, cx| {
14049            diff.stage_or_unstage_hunks(
14050                stage,
14051                &hunks
14052                    .map(|hunk| buffer_diff::DiffHunk {
14053                        buffer_range: hunk.buffer_range,
14054                        diff_base_byte_range: hunk.diff_base_byte_range,
14055                        secondary_status: hunk.secondary_status,
14056                        range: Point::zero()..Point::zero(), // unused
14057                    })
14058                    .collect::<Vec<_>>(),
14059                &buffer_snapshot,
14060                file_exists,
14061                cx,
14062            )
14063        });
14064        None
14065    }
14066
14067    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
14068        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
14069        self.buffer
14070            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
14071    }
14072
14073    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
14074        self.buffer.update(cx, |buffer, cx| {
14075            let ranges = vec![Anchor::min()..Anchor::max()];
14076            if !buffer.all_diff_hunks_expanded()
14077                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
14078            {
14079                buffer.collapse_diff_hunks(ranges, cx);
14080                true
14081            } else {
14082                false
14083            }
14084        })
14085    }
14086
14087    fn toggle_diff_hunks_in_ranges(
14088        &mut self,
14089        ranges: Vec<Range<Anchor>>,
14090        cx: &mut Context<'_, Editor>,
14091    ) {
14092        self.buffer.update(cx, |buffer, cx| {
14093            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
14094            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
14095        })
14096    }
14097
14098    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
14099        self.buffer.update(cx, |buffer, cx| {
14100            let snapshot = buffer.snapshot(cx);
14101            let excerpt_id = range.end.excerpt_id;
14102            let point_range = range.to_point(&snapshot);
14103            let expand = !buffer.single_hunk_is_expanded(range, cx);
14104            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
14105        })
14106    }
14107
14108    pub(crate) fn apply_all_diff_hunks(
14109        &mut self,
14110        _: &ApplyAllDiffHunks,
14111        window: &mut Window,
14112        cx: &mut Context<Self>,
14113    ) {
14114        let buffers = self.buffer.read(cx).all_buffers();
14115        for branch_buffer in buffers {
14116            branch_buffer.update(cx, |branch_buffer, cx| {
14117                branch_buffer.merge_into_base(Vec::new(), cx);
14118            });
14119        }
14120
14121        if let Some(project) = self.project.clone() {
14122            self.save(true, project, window, cx).detach_and_log_err(cx);
14123        }
14124    }
14125
14126    pub(crate) fn apply_selected_diff_hunks(
14127        &mut self,
14128        _: &ApplyDiffHunk,
14129        window: &mut Window,
14130        cx: &mut Context<Self>,
14131    ) {
14132        let snapshot = self.snapshot(window, cx);
14133        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
14134        let mut ranges_by_buffer = HashMap::default();
14135        self.transact(window, cx, |editor, _window, cx| {
14136            for hunk in hunks {
14137                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
14138                    ranges_by_buffer
14139                        .entry(buffer.clone())
14140                        .or_insert_with(Vec::new)
14141                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
14142                }
14143            }
14144
14145            for (buffer, ranges) in ranges_by_buffer {
14146                buffer.update(cx, |buffer, cx| {
14147                    buffer.merge_into_base(ranges, cx);
14148                });
14149            }
14150        });
14151
14152        if let Some(project) = self.project.clone() {
14153            self.save(true, project, window, cx).detach_and_log_err(cx);
14154        }
14155    }
14156
14157    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
14158        if hovered != self.gutter_hovered {
14159            self.gutter_hovered = hovered;
14160            cx.notify();
14161        }
14162    }
14163
14164    pub fn insert_blocks(
14165        &mut self,
14166        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
14167        autoscroll: Option<Autoscroll>,
14168        cx: &mut Context<Self>,
14169    ) -> Vec<CustomBlockId> {
14170        let blocks = self
14171            .display_map
14172            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
14173        if let Some(autoscroll) = autoscroll {
14174            self.request_autoscroll(autoscroll, cx);
14175        }
14176        cx.notify();
14177        blocks
14178    }
14179
14180    pub fn resize_blocks(
14181        &mut self,
14182        heights: HashMap<CustomBlockId, u32>,
14183        autoscroll: Option<Autoscroll>,
14184        cx: &mut Context<Self>,
14185    ) {
14186        self.display_map
14187            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
14188        if let Some(autoscroll) = autoscroll {
14189            self.request_autoscroll(autoscroll, cx);
14190        }
14191        cx.notify();
14192    }
14193
14194    pub fn replace_blocks(
14195        &mut self,
14196        renderers: HashMap<CustomBlockId, RenderBlock>,
14197        autoscroll: Option<Autoscroll>,
14198        cx: &mut Context<Self>,
14199    ) {
14200        self.display_map
14201            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
14202        if let Some(autoscroll) = autoscroll {
14203            self.request_autoscroll(autoscroll, cx);
14204        }
14205        cx.notify();
14206    }
14207
14208    pub fn remove_blocks(
14209        &mut self,
14210        block_ids: HashSet<CustomBlockId>,
14211        autoscroll: Option<Autoscroll>,
14212        cx: &mut Context<Self>,
14213    ) {
14214        self.display_map.update(cx, |display_map, cx| {
14215            display_map.remove_blocks(block_ids, cx)
14216        });
14217        if let Some(autoscroll) = autoscroll {
14218            self.request_autoscroll(autoscroll, cx);
14219        }
14220        cx.notify();
14221    }
14222
14223    pub fn row_for_block(
14224        &self,
14225        block_id: CustomBlockId,
14226        cx: &mut Context<Self>,
14227    ) -> Option<DisplayRow> {
14228        self.display_map
14229            .update(cx, |map, cx| map.row_for_block(block_id, cx))
14230    }
14231
14232    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
14233        self.focused_block = Some(focused_block);
14234    }
14235
14236    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
14237        self.focused_block.take()
14238    }
14239
14240    pub fn insert_creases(
14241        &mut self,
14242        creases: impl IntoIterator<Item = Crease<Anchor>>,
14243        cx: &mut Context<Self>,
14244    ) -> Vec<CreaseId> {
14245        self.display_map
14246            .update(cx, |map, cx| map.insert_creases(creases, cx))
14247    }
14248
14249    pub fn remove_creases(
14250        &mut self,
14251        ids: impl IntoIterator<Item = CreaseId>,
14252        cx: &mut Context<Self>,
14253    ) {
14254        self.display_map
14255            .update(cx, |map, cx| map.remove_creases(ids, cx));
14256    }
14257
14258    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
14259        self.display_map
14260            .update(cx, |map, cx| map.snapshot(cx))
14261            .longest_row()
14262    }
14263
14264    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
14265        self.display_map
14266            .update(cx, |map, cx| map.snapshot(cx))
14267            .max_point()
14268    }
14269
14270    pub fn text(&self, cx: &App) -> String {
14271        self.buffer.read(cx).read(cx).text()
14272    }
14273
14274    pub fn is_empty(&self, cx: &App) -> bool {
14275        self.buffer.read(cx).read(cx).is_empty()
14276    }
14277
14278    pub fn text_option(&self, cx: &App) -> Option<String> {
14279        let text = self.text(cx);
14280        let text = text.trim();
14281
14282        if text.is_empty() {
14283            return None;
14284        }
14285
14286        Some(text.to_string())
14287    }
14288
14289    pub fn set_text(
14290        &mut self,
14291        text: impl Into<Arc<str>>,
14292        window: &mut Window,
14293        cx: &mut Context<Self>,
14294    ) {
14295        self.transact(window, cx, |this, _, cx| {
14296            this.buffer
14297                .read(cx)
14298                .as_singleton()
14299                .expect("you can only call set_text on editors for singleton buffers")
14300                .update(cx, |buffer, cx| buffer.set_text(text, cx));
14301        });
14302    }
14303
14304    pub fn display_text(&self, cx: &mut App) -> String {
14305        self.display_map
14306            .update(cx, |map, cx| map.snapshot(cx))
14307            .text()
14308    }
14309
14310    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
14311        let mut wrap_guides = smallvec::smallvec![];
14312
14313        if self.show_wrap_guides == Some(false) {
14314            return wrap_guides;
14315        }
14316
14317        let settings = self.buffer.read(cx).language_settings(cx);
14318        if settings.show_wrap_guides {
14319            match self.soft_wrap_mode(cx) {
14320                SoftWrap::Column(soft_wrap) => {
14321                    wrap_guides.push((soft_wrap as usize, true));
14322                }
14323                SoftWrap::Bounded(soft_wrap) => {
14324                    wrap_guides.push((soft_wrap as usize, true));
14325                }
14326                SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
14327            }
14328            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
14329        }
14330
14331        wrap_guides
14332    }
14333
14334    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
14335        let settings = self.buffer.read(cx).language_settings(cx);
14336        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
14337        match mode {
14338            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
14339                SoftWrap::None
14340            }
14341            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
14342            language_settings::SoftWrap::PreferredLineLength => {
14343                SoftWrap::Column(settings.preferred_line_length)
14344            }
14345            language_settings::SoftWrap::Bounded => {
14346                SoftWrap::Bounded(settings.preferred_line_length)
14347            }
14348        }
14349    }
14350
14351    pub fn set_soft_wrap_mode(
14352        &mut self,
14353        mode: language_settings::SoftWrap,
14354
14355        cx: &mut Context<Self>,
14356    ) {
14357        self.soft_wrap_mode_override = Some(mode);
14358        cx.notify();
14359    }
14360
14361    pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
14362        self.hard_wrap = hard_wrap;
14363        cx.notify();
14364    }
14365
14366    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
14367        self.text_style_refinement = Some(style);
14368    }
14369
14370    /// called by the Element so we know what style we were most recently rendered with.
14371    pub(crate) fn set_style(
14372        &mut self,
14373        style: EditorStyle,
14374        window: &mut Window,
14375        cx: &mut Context<Self>,
14376    ) {
14377        let rem_size = window.rem_size();
14378        self.display_map.update(cx, |map, cx| {
14379            map.set_font(
14380                style.text.font(),
14381                style.text.font_size.to_pixels(rem_size),
14382                cx,
14383            )
14384        });
14385        self.style = Some(style);
14386    }
14387
14388    pub fn style(&self) -> Option<&EditorStyle> {
14389        self.style.as_ref()
14390    }
14391
14392    // Called by the element. This method is not designed to be called outside of the editor
14393    // element's layout code because it does not notify when rewrapping is computed synchronously.
14394    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
14395        self.display_map
14396            .update(cx, |map, cx| map.set_wrap_width(width, cx))
14397    }
14398
14399    pub fn set_soft_wrap(&mut self) {
14400        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
14401    }
14402
14403    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
14404        if self.soft_wrap_mode_override.is_some() {
14405            self.soft_wrap_mode_override.take();
14406        } else {
14407            let soft_wrap = match self.soft_wrap_mode(cx) {
14408                SoftWrap::GitDiff => return,
14409                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
14410                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
14411                    language_settings::SoftWrap::None
14412                }
14413            };
14414            self.soft_wrap_mode_override = Some(soft_wrap);
14415        }
14416        cx.notify();
14417    }
14418
14419    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
14420        let Some(workspace) = self.workspace() else {
14421            return;
14422        };
14423        let fs = workspace.read(cx).app_state().fs.clone();
14424        let current_show = TabBarSettings::get_global(cx).show;
14425        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
14426            setting.show = Some(!current_show);
14427        });
14428    }
14429
14430    pub fn toggle_indent_guides(
14431        &mut self,
14432        _: &ToggleIndentGuides,
14433        _: &mut Window,
14434        cx: &mut Context<Self>,
14435    ) {
14436        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
14437            self.buffer
14438                .read(cx)
14439                .language_settings(cx)
14440                .indent_guides
14441                .enabled
14442        });
14443        self.show_indent_guides = Some(!currently_enabled);
14444        cx.notify();
14445    }
14446
14447    fn should_show_indent_guides(&self) -> Option<bool> {
14448        self.show_indent_guides
14449    }
14450
14451    pub fn toggle_line_numbers(
14452        &mut self,
14453        _: &ToggleLineNumbers,
14454        _: &mut Window,
14455        cx: &mut Context<Self>,
14456    ) {
14457        let mut editor_settings = EditorSettings::get_global(cx).clone();
14458        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
14459        EditorSettings::override_global(editor_settings, cx);
14460    }
14461
14462    pub fn line_numbers_enabled(&self, cx: &App) -> bool {
14463        if let Some(show_line_numbers) = self.show_line_numbers {
14464            return show_line_numbers;
14465        }
14466        EditorSettings::get_global(cx).gutter.line_numbers
14467    }
14468
14469    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
14470        self.use_relative_line_numbers
14471            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
14472    }
14473
14474    pub fn toggle_relative_line_numbers(
14475        &mut self,
14476        _: &ToggleRelativeLineNumbers,
14477        _: &mut Window,
14478        cx: &mut Context<Self>,
14479    ) {
14480        let is_relative = self.should_use_relative_line_numbers(cx);
14481        self.set_relative_line_number(Some(!is_relative), cx)
14482    }
14483
14484    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
14485        self.use_relative_line_numbers = is_relative;
14486        cx.notify();
14487    }
14488
14489    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
14490        self.show_gutter = show_gutter;
14491        cx.notify();
14492    }
14493
14494    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
14495        self.show_scrollbars = show_scrollbars;
14496        cx.notify();
14497    }
14498
14499    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
14500        self.show_line_numbers = Some(show_line_numbers);
14501        cx.notify();
14502    }
14503
14504    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
14505        self.show_git_diff_gutter = Some(show_git_diff_gutter);
14506        cx.notify();
14507    }
14508
14509    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
14510        self.show_code_actions = Some(show_code_actions);
14511        cx.notify();
14512    }
14513
14514    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
14515        self.show_runnables = Some(show_runnables);
14516        cx.notify();
14517    }
14518
14519    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
14520        if self.display_map.read(cx).masked != masked {
14521            self.display_map.update(cx, |map, _| map.masked = masked);
14522        }
14523        cx.notify()
14524    }
14525
14526    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
14527        self.show_wrap_guides = Some(show_wrap_guides);
14528        cx.notify();
14529    }
14530
14531    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
14532        self.show_indent_guides = Some(show_indent_guides);
14533        cx.notify();
14534    }
14535
14536    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
14537        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
14538            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
14539                if let Some(dir) = file.abs_path(cx).parent() {
14540                    return Some(dir.to_owned());
14541                }
14542            }
14543
14544            if let Some(project_path) = buffer.read(cx).project_path(cx) {
14545                return Some(project_path.path.to_path_buf());
14546            }
14547        }
14548
14549        None
14550    }
14551
14552    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
14553        self.active_excerpt(cx)?
14554            .1
14555            .read(cx)
14556            .file()
14557            .and_then(|f| f.as_local())
14558    }
14559
14560    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14561        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14562            let buffer = buffer.read(cx);
14563            if let Some(project_path) = buffer.project_path(cx) {
14564                let project = self.project.as_ref()?.read(cx);
14565                project.absolute_path(&project_path, cx)
14566            } else {
14567                buffer
14568                    .file()
14569                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
14570            }
14571        })
14572    }
14573
14574    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14575        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14576            let project_path = buffer.read(cx).project_path(cx)?;
14577            let project = self.project.as_ref()?.read(cx);
14578            let entry = project.entry_for_path(&project_path, cx)?;
14579            let path = entry.path.to_path_buf();
14580            Some(path)
14581        })
14582    }
14583
14584    pub fn reveal_in_finder(
14585        &mut self,
14586        _: &RevealInFileManager,
14587        _window: &mut Window,
14588        cx: &mut Context<Self>,
14589    ) {
14590        if let Some(target) = self.target_file(cx) {
14591            cx.reveal_path(&target.abs_path(cx));
14592        }
14593    }
14594
14595    pub fn copy_path(
14596        &mut self,
14597        _: &zed_actions::workspace::CopyPath,
14598        _window: &mut Window,
14599        cx: &mut Context<Self>,
14600    ) {
14601        if let Some(path) = self.target_file_abs_path(cx) {
14602            if let Some(path) = path.to_str() {
14603                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14604            }
14605        }
14606    }
14607
14608    pub fn copy_relative_path(
14609        &mut self,
14610        _: &zed_actions::workspace::CopyRelativePath,
14611        _window: &mut Window,
14612        cx: &mut Context<Self>,
14613    ) {
14614        if let Some(path) = self.target_file_path(cx) {
14615            if let Some(path) = path.to_str() {
14616                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14617            }
14618        }
14619    }
14620
14621    pub fn copy_file_name_without_extension(
14622        &mut self,
14623        _: &CopyFileNameWithoutExtension,
14624        _: &mut Window,
14625        cx: &mut Context<Self>,
14626    ) {
14627        if let Some(file) = self.target_file(cx) {
14628            if let Some(file_stem) = file.path().file_stem() {
14629                if let Some(name) = file_stem.to_str() {
14630                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14631                }
14632            }
14633        }
14634    }
14635
14636    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
14637        if let Some(file) = self.target_file(cx) {
14638            if let Some(file_name) = file.path().file_name() {
14639                if let Some(name) = file_name.to_str() {
14640                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14641                }
14642            }
14643        }
14644    }
14645
14646    pub fn toggle_git_blame(
14647        &mut self,
14648        _: &::git::Blame,
14649        window: &mut Window,
14650        cx: &mut Context<Self>,
14651    ) {
14652        self.show_git_blame_gutter = !self.show_git_blame_gutter;
14653
14654        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
14655            self.start_git_blame(true, window, cx);
14656        }
14657
14658        cx.notify();
14659    }
14660
14661    pub fn toggle_git_blame_inline(
14662        &mut self,
14663        _: &ToggleGitBlameInline,
14664        window: &mut Window,
14665        cx: &mut Context<Self>,
14666    ) {
14667        self.toggle_git_blame_inline_internal(true, window, cx);
14668        cx.notify();
14669    }
14670
14671    pub fn git_blame_inline_enabled(&self) -> bool {
14672        self.git_blame_inline_enabled
14673    }
14674
14675    pub fn toggle_selection_menu(
14676        &mut self,
14677        _: &ToggleSelectionMenu,
14678        _: &mut Window,
14679        cx: &mut Context<Self>,
14680    ) {
14681        self.show_selection_menu = self
14682            .show_selection_menu
14683            .map(|show_selections_menu| !show_selections_menu)
14684            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
14685
14686        cx.notify();
14687    }
14688
14689    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
14690        self.show_selection_menu
14691            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
14692    }
14693
14694    fn start_git_blame(
14695        &mut self,
14696        user_triggered: bool,
14697        window: &mut Window,
14698        cx: &mut Context<Self>,
14699    ) {
14700        if let Some(project) = self.project.as_ref() {
14701            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
14702                return;
14703            };
14704
14705            if buffer.read(cx).file().is_none() {
14706                return;
14707            }
14708
14709            let focused = self.focus_handle(cx).contains_focused(window, cx);
14710
14711            let project = project.clone();
14712            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
14713            self.blame_subscription =
14714                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
14715            self.blame = Some(blame);
14716        }
14717    }
14718
14719    fn toggle_git_blame_inline_internal(
14720        &mut self,
14721        user_triggered: bool,
14722        window: &mut Window,
14723        cx: &mut Context<Self>,
14724    ) {
14725        if self.git_blame_inline_enabled {
14726            self.git_blame_inline_enabled = false;
14727            self.show_git_blame_inline = false;
14728            self.show_git_blame_inline_delay_task.take();
14729        } else {
14730            self.git_blame_inline_enabled = true;
14731            self.start_git_blame_inline(user_triggered, window, cx);
14732        }
14733
14734        cx.notify();
14735    }
14736
14737    fn start_git_blame_inline(
14738        &mut self,
14739        user_triggered: bool,
14740        window: &mut Window,
14741        cx: &mut Context<Self>,
14742    ) {
14743        self.start_git_blame(user_triggered, window, cx);
14744
14745        if ProjectSettings::get_global(cx)
14746            .git
14747            .inline_blame_delay()
14748            .is_some()
14749        {
14750            self.start_inline_blame_timer(window, cx);
14751        } else {
14752            self.show_git_blame_inline = true
14753        }
14754    }
14755
14756    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
14757        self.blame.as_ref()
14758    }
14759
14760    pub fn show_git_blame_gutter(&self) -> bool {
14761        self.show_git_blame_gutter
14762    }
14763
14764    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
14765        self.show_git_blame_gutter && self.has_blame_entries(cx)
14766    }
14767
14768    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
14769        self.show_git_blame_inline
14770            && (self.focus_handle.is_focused(window)
14771                || self
14772                    .git_blame_inline_tooltip
14773                    .as_ref()
14774                    .and_then(|t| t.upgrade())
14775                    .is_some())
14776            && !self.newest_selection_head_on_empty_line(cx)
14777            && self.has_blame_entries(cx)
14778    }
14779
14780    fn has_blame_entries(&self, cx: &App) -> bool {
14781        self.blame()
14782            .map_or(false, |blame| blame.read(cx).has_generated_entries())
14783    }
14784
14785    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
14786        let cursor_anchor = self.selections.newest_anchor().head();
14787
14788        let snapshot = self.buffer.read(cx).snapshot(cx);
14789        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
14790
14791        snapshot.line_len(buffer_row) == 0
14792    }
14793
14794    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
14795        let buffer_and_selection = maybe!({
14796            let selection = self.selections.newest::<Point>(cx);
14797            let selection_range = selection.range();
14798
14799            let multi_buffer = self.buffer().read(cx);
14800            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14801            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
14802
14803            let (buffer, range, _) = if selection.reversed {
14804                buffer_ranges.first()
14805            } else {
14806                buffer_ranges.last()
14807            }?;
14808
14809            let selection = text::ToPoint::to_point(&range.start, &buffer).row
14810                ..text::ToPoint::to_point(&range.end, &buffer).row;
14811            Some((
14812                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
14813                selection,
14814            ))
14815        });
14816
14817        let Some((buffer, selection)) = buffer_and_selection else {
14818            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
14819        };
14820
14821        let Some(project) = self.project.as_ref() else {
14822            return Task::ready(Err(anyhow!("editor does not have project")));
14823        };
14824
14825        project.update(cx, |project, cx| {
14826            project.get_permalink_to_line(&buffer, selection, cx)
14827        })
14828    }
14829
14830    pub fn copy_permalink_to_line(
14831        &mut self,
14832        _: &CopyPermalinkToLine,
14833        window: &mut Window,
14834        cx: &mut Context<Self>,
14835    ) {
14836        let permalink_task = self.get_permalink_to_line(cx);
14837        let workspace = self.workspace();
14838
14839        cx.spawn_in(window, |_, mut cx| async move {
14840            match permalink_task.await {
14841                Ok(permalink) => {
14842                    cx.update(|_, cx| {
14843                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
14844                    })
14845                    .ok();
14846                }
14847                Err(err) => {
14848                    let message = format!("Failed to copy permalink: {err}");
14849
14850                    Err::<(), anyhow::Error>(err).log_err();
14851
14852                    if let Some(workspace) = workspace {
14853                        workspace
14854                            .update_in(&mut cx, |workspace, _, cx| {
14855                                struct CopyPermalinkToLine;
14856
14857                                workspace.show_toast(
14858                                    Toast::new(
14859                                        NotificationId::unique::<CopyPermalinkToLine>(),
14860                                        message,
14861                                    ),
14862                                    cx,
14863                                )
14864                            })
14865                            .ok();
14866                    }
14867                }
14868            }
14869        })
14870        .detach();
14871    }
14872
14873    pub fn copy_file_location(
14874        &mut self,
14875        _: &CopyFileLocation,
14876        _: &mut Window,
14877        cx: &mut Context<Self>,
14878    ) {
14879        let selection = self.selections.newest::<Point>(cx).start.row + 1;
14880        if let Some(file) = self.target_file(cx) {
14881            if let Some(path) = file.path().to_str() {
14882                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
14883            }
14884        }
14885    }
14886
14887    pub fn open_permalink_to_line(
14888        &mut self,
14889        _: &OpenPermalinkToLine,
14890        window: &mut Window,
14891        cx: &mut Context<Self>,
14892    ) {
14893        let permalink_task = self.get_permalink_to_line(cx);
14894        let workspace = self.workspace();
14895
14896        cx.spawn_in(window, |_, mut cx| async move {
14897            match permalink_task.await {
14898                Ok(permalink) => {
14899                    cx.update(|_, cx| {
14900                        cx.open_url(permalink.as_ref());
14901                    })
14902                    .ok();
14903                }
14904                Err(err) => {
14905                    let message = format!("Failed to open permalink: {err}");
14906
14907                    Err::<(), anyhow::Error>(err).log_err();
14908
14909                    if let Some(workspace) = workspace {
14910                        workspace
14911                            .update(&mut cx, |workspace, cx| {
14912                                struct OpenPermalinkToLine;
14913
14914                                workspace.show_toast(
14915                                    Toast::new(
14916                                        NotificationId::unique::<OpenPermalinkToLine>(),
14917                                        message,
14918                                    ),
14919                                    cx,
14920                                )
14921                            })
14922                            .ok();
14923                    }
14924                }
14925            }
14926        })
14927        .detach();
14928    }
14929
14930    pub fn insert_uuid_v4(
14931        &mut self,
14932        _: &InsertUuidV4,
14933        window: &mut Window,
14934        cx: &mut Context<Self>,
14935    ) {
14936        self.insert_uuid(UuidVersion::V4, window, cx);
14937    }
14938
14939    pub fn insert_uuid_v7(
14940        &mut self,
14941        _: &InsertUuidV7,
14942        window: &mut Window,
14943        cx: &mut Context<Self>,
14944    ) {
14945        self.insert_uuid(UuidVersion::V7, window, cx);
14946    }
14947
14948    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
14949        self.transact(window, cx, |this, window, cx| {
14950            let edits = this
14951                .selections
14952                .all::<Point>(cx)
14953                .into_iter()
14954                .map(|selection| {
14955                    let uuid = match version {
14956                        UuidVersion::V4 => uuid::Uuid::new_v4(),
14957                        UuidVersion::V7 => uuid::Uuid::now_v7(),
14958                    };
14959
14960                    (selection.range(), uuid.to_string())
14961                });
14962            this.edit(edits, cx);
14963            this.refresh_inline_completion(true, false, window, cx);
14964        });
14965    }
14966
14967    pub fn open_selections_in_multibuffer(
14968        &mut self,
14969        _: &OpenSelectionsInMultibuffer,
14970        window: &mut Window,
14971        cx: &mut Context<Self>,
14972    ) {
14973        let multibuffer = self.buffer.read(cx);
14974
14975        let Some(buffer) = multibuffer.as_singleton() else {
14976            return;
14977        };
14978
14979        let Some(workspace) = self.workspace() else {
14980            return;
14981        };
14982
14983        let locations = self
14984            .selections
14985            .disjoint_anchors()
14986            .iter()
14987            .map(|range| Location {
14988                buffer: buffer.clone(),
14989                range: range.start.text_anchor..range.end.text_anchor,
14990            })
14991            .collect::<Vec<_>>();
14992
14993        let title = multibuffer.title(cx).to_string();
14994
14995        cx.spawn_in(window, |_, mut cx| async move {
14996            workspace.update_in(&mut cx, |workspace, window, cx| {
14997                Self::open_locations_in_multibuffer(
14998                    workspace,
14999                    locations,
15000                    format!("Selections for '{title}'"),
15001                    false,
15002                    MultibufferSelectionMode::All,
15003                    window,
15004                    cx,
15005                );
15006            })
15007        })
15008        .detach();
15009    }
15010
15011    /// Adds a row highlight for the given range. If a row has multiple highlights, the
15012    /// last highlight added will be used.
15013    ///
15014    /// If the range ends at the beginning of a line, then that line will not be highlighted.
15015    pub fn highlight_rows<T: 'static>(
15016        &mut self,
15017        range: Range<Anchor>,
15018        color: Hsla,
15019        should_autoscroll: bool,
15020        cx: &mut Context<Self>,
15021    ) {
15022        let snapshot = self.buffer().read(cx).snapshot(cx);
15023        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
15024        let ix = row_highlights.binary_search_by(|highlight| {
15025            Ordering::Equal
15026                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
15027                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
15028        });
15029
15030        if let Err(mut ix) = ix {
15031            let index = post_inc(&mut self.highlight_order);
15032
15033            // If this range intersects with the preceding highlight, then merge it with
15034            // the preceding highlight. Otherwise insert a new highlight.
15035            let mut merged = false;
15036            if ix > 0 {
15037                let prev_highlight = &mut row_highlights[ix - 1];
15038                if prev_highlight
15039                    .range
15040                    .end
15041                    .cmp(&range.start, &snapshot)
15042                    .is_ge()
15043                {
15044                    ix -= 1;
15045                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
15046                        prev_highlight.range.end = range.end;
15047                    }
15048                    merged = true;
15049                    prev_highlight.index = index;
15050                    prev_highlight.color = color;
15051                    prev_highlight.should_autoscroll = should_autoscroll;
15052                }
15053            }
15054
15055            if !merged {
15056                row_highlights.insert(
15057                    ix,
15058                    RowHighlight {
15059                        range: range.clone(),
15060                        index,
15061                        color,
15062                        should_autoscroll,
15063                    },
15064                );
15065            }
15066
15067            // If any of the following highlights intersect with this one, merge them.
15068            while let Some(next_highlight) = row_highlights.get(ix + 1) {
15069                let highlight = &row_highlights[ix];
15070                if next_highlight
15071                    .range
15072                    .start
15073                    .cmp(&highlight.range.end, &snapshot)
15074                    .is_le()
15075                {
15076                    if next_highlight
15077                        .range
15078                        .end
15079                        .cmp(&highlight.range.end, &snapshot)
15080                        .is_gt()
15081                    {
15082                        row_highlights[ix].range.end = next_highlight.range.end;
15083                    }
15084                    row_highlights.remove(ix + 1);
15085                } else {
15086                    break;
15087                }
15088            }
15089        }
15090    }
15091
15092    /// Remove any highlighted row ranges of the given type that intersect the
15093    /// given ranges.
15094    pub fn remove_highlighted_rows<T: 'static>(
15095        &mut self,
15096        ranges_to_remove: Vec<Range<Anchor>>,
15097        cx: &mut Context<Self>,
15098    ) {
15099        let snapshot = self.buffer().read(cx).snapshot(cx);
15100        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
15101        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
15102        row_highlights.retain(|highlight| {
15103            while let Some(range_to_remove) = ranges_to_remove.peek() {
15104                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
15105                    Ordering::Less | Ordering::Equal => {
15106                        ranges_to_remove.next();
15107                    }
15108                    Ordering::Greater => {
15109                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
15110                            Ordering::Less | Ordering::Equal => {
15111                                return false;
15112                            }
15113                            Ordering::Greater => break,
15114                        }
15115                    }
15116                }
15117            }
15118
15119            true
15120        })
15121    }
15122
15123    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
15124    pub fn clear_row_highlights<T: 'static>(&mut self) {
15125        self.highlighted_rows.remove(&TypeId::of::<T>());
15126    }
15127
15128    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
15129    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
15130        self.highlighted_rows
15131            .get(&TypeId::of::<T>())
15132            .map_or(&[] as &[_], |vec| vec.as_slice())
15133            .iter()
15134            .map(|highlight| (highlight.range.clone(), highlight.color))
15135    }
15136
15137    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
15138    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
15139    /// Allows to ignore certain kinds of highlights.
15140    pub fn highlighted_display_rows(
15141        &self,
15142        window: &mut Window,
15143        cx: &mut App,
15144    ) -> BTreeMap<DisplayRow, LineHighlight> {
15145        let snapshot = self.snapshot(window, cx);
15146        let mut used_highlight_orders = HashMap::default();
15147        self.highlighted_rows
15148            .iter()
15149            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
15150            .fold(
15151                BTreeMap::<DisplayRow, LineHighlight>::new(),
15152                |mut unique_rows, highlight| {
15153                    let start = highlight.range.start.to_display_point(&snapshot);
15154                    let end = highlight.range.end.to_display_point(&snapshot);
15155                    let start_row = start.row().0;
15156                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
15157                        && end.column() == 0
15158                    {
15159                        end.row().0.saturating_sub(1)
15160                    } else {
15161                        end.row().0
15162                    };
15163                    for row in start_row..=end_row {
15164                        let used_index =
15165                            used_highlight_orders.entry(row).or_insert(highlight.index);
15166                        if highlight.index >= *used_index {
15167                            *used_index = highlight.index;
15168                            unique_rows.insert(DisplayRow(row), highlight.color.into());
15169                        }
15170                    }
15171                    unique_rows
15172                },
15173            )
15174    }
15175
15176    pub fn highlighted_display_row_for_autoscroll(
15177        &self,
15178        snapshot: &DisplaySnapshot,
15179    ) -> Option<DisplayRow> {
15180        self.highlighted_rows
15181            .values()
15182            .flat_map(|highlighted_rows| highlighted_rows.iter())
15183            .filter_map(|highlight| {
15184                if highlight.should_autoscroll {
15185                    Some(highlight.range.start.to_display_point(snapshot).row())
15186                } else {
15187                    None
15188                }
15189            })
15190            .min()
15191    }
15192
15193    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
15194        self.highlight_background::<SearchWithinRange>(
15195            ranges,
15196            |colors| colors.editor_document_highlight_read_background,
15197            cx,
15198        )
15199    }
15200
15201    pub fn set_breadcrumb_header(&mut self, new_header: String) {
15202        self.breadcrumb_header = Some(new_header);
15203    }
15204
15205    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
15206        self.clear_background_highlights::<SearchWithinRange>(cx);
15207    }
15208
15209    pub fn highlight_background<T: 'static>(
15210        &mut self,
15211        ranges: &[Range<Anchor>],
15212        color_fetcher: fn(&ThemeColors) -> Hsla,
15213        cx: &mut Context<Self>,
15214    ) {
15215        self.background_highlights
15216            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
15217        self.scrollbar_marker_state.dirty = true;
15218        cx.notify();
15219    }
15220
15221    pub fn clear_background_highlights<T: 'static>(
15222        &mut self,
15223        cx: &mut Context<Self>,
15224    ) -> Option<BackgroundHighlight> {
15225        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
15226        if !text_highlights.1.is_empty() {
15227            self.scrollbar_marker_state.dirty = true;
15228            cx.notify();
15229        }
15230        Some(text_highlights)
15231    }
15232
15233    pub fn highlight_gutter<T: 'static>(
15234        &mut self,
15235        ranges: &[Range<Anchor>],
15236        color_fetcher: fn(&App) -> Hsla,
15237        cx: &mut Context<Self>,
15238    ) {
15239        self.gutter_highlights
15240            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
15241        cx.notify();
15242    }
15243
15244    pub fn clear_gutter_highlights<T: 'static>(
15245        &mut self,
15246        cx: &mut Context<Self>,
15247    ) -> Option<GutterHighlight> {
15248        cx.notify();
15249        self.gutter_highlights.remove(&TypeId::of::<T>())
15250    }
15251
15252    #[cfg(feature = "test-support")]
15253    pub fn all_text_background_highlights(
15254        &self,
15255        window: &mut Window,
15256        cx: &mut Context<Self>,
15257    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15258        let snapshot = self.snapshot(window, cx);
15259        let buffer = &snapshot.buffer_snapshot;
15260        let start = buffer.anchor_before(0);
15261        let end = buffer.anchor_after(buffer.len());
15262        let theme = cx.theme().colors();
15263        self.background_highlights_in_range(start..end, &snapshot, theme)
15264    }
15265
15266    #[cfg(feature = "test-support")]
15267    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
15268        let snapshot = self.buffer().read(cx).snapshot(cx);
15269
15270        let highlights = self
15271            .background_highlights
15272            .get(&TypeId::of::<items::BufferSearchHighlights>());
15273
15274        if let Some((_color, ranges)) = highlights {
15275            ranges
15276                .iter()
15277                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
15278                .collect_vec()
15279        } else {
15280            vec![]
15281        }
15282    }
15283
15284    fn document_highlights_for_position<'a>(
15285        &'a self,
15286        position: Anchor,
15287        buffer: &'a MultiBufferSnapshot,
15288    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
15289        let read_highlights = self
15290            .background_highlights
15291            .get(&TypeId::of::<DocumentHighlightRead>())
15292            .map(|h| &h.1);
15293        let write_highlights = self
15294            .background_highlights
15295            .get(&TypeId::of::<DocumentHighlightWrite>())
15296            .map(|h| &h.1);
15297        let left_position = position.bias_left(buffer);
15298        let right_position = position.bias_right(buffer);
15299        read_highlights
15300            .into_iter()
15301            .chain(write_highlights)
15302            .flat_map(move |ranges| {
15303                let start_ix = match ranges.binary_search_by(|probe| {
15304                    let cmp = probe.end.cmp(&left_position, buffer);
15305                    if cmp.is_ge() {
15306                        Ordering::Greater
15307                    } else {
15308                        Ordering::Less
15309                    }
15310                }) {
15311                    Ok(i) | Err(i) => i,
15312                };
15313
15314                ranges[start_ix..]
15315                    .iter()
15316                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
15317            })
15318    }
15319
15320    pub fn has_background_highlights<T: 'static>(&self) -> bool {
15321        self.background_highlights
15322            .get(&TypeId::of::<T>())
15323            .map_or(false, |(_, highlights)| !highlights.is_empty())
15324    }
15325
15326    pub fn background_highlights_in_range(
15327        &self,
15328        search_range: Range<Anchor>,
15329        display_snapshot: &DisplaySnapshot,
15330        theme: &ThemeColors,
15331    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15332        let mut results = Vec::new();
15333        for (color_fetcher, ranges) in self.background_highlights.values() {
15334            let color = color_fetcher(theme);
15335            let start_ix = match ranges.binary_search_by(|probe| {
15336                let cmp = probe
15337                    .end
15338                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15339                if cmp.is_gt() {
15340                    Ordering::Greater
15341                } else {
15342                    Ordering::Less
15343                }
15344            }) {
15345                Ok(i) | Err(i) => i,
15346            };
15347            for range in &ranges[start_ix..] {
15348                if range
15349                    .start
15350                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15351                    .is_ge()
15352                {
15353                    break;
15354                }
15355
15356                let start = range.start.to_display_point(display_snapshot);
15357                let end = range.end.to_display_point(display_snapshot);
15358                results.push((start..end, color))
15359            }
15360        }
15361        results
15362    }
15363
15364    pub fn background_highlight_row_ranges<T: 'static>(
15365        &self,
15366        search_range: Range<Anchor>,
15367        display_snapshot: &DisplaySnapshot,
15368        count: usize,
15369    ) -> Vec<RangeInclusive<DisplayPoint>> {
15370        let mut results = Vec::new();
15371        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
15372            return vec![];
15373        };
15374
15375        let start_ix = match ranges.binary_search_by(|probe| {
15376            let cmp = probe
15377                .end
15378                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15379            if cmp.is_gt() {
15380                Ordering::Greater
15381            } else {
15382                Ordering::Less
15383            }
15384        }) {
15385            Ok(i) | Err(i) => i,
15386        };
15387        let mut push_region = |start: Option<Point>, end: Option<Point>| {
15388            if let (Some(start_display), Some(end_display)) = (start, end) {
15389                results.push(
15390                    start_display.to_display_point(display_snapshot)
15391                        ..=end_display.to_display_point(display_snapshot),
15392                );
15393            }
15394        };
15395        let mut start_row: Option<Point> = None;
15396        let mut end_row: Option<Point> = None;
15397        if ranges.len() > count {
15398            return Vec::new();
15399        }
15400        for range in &ranges[start_ix..] {
15401            if range
15402                .start
15403                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15404                .is_ge()
15405            {
15406                break;
15407            }
15408            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
15409            if let Some(current_row) = &end_row {
15410                if end.row == current_row.row {
15411                    continue;
15412                }
15413            }
15414            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
15415            if start_row.is_none() {
15416                assert_eq!(end_row, None);
15417                start_row = Some(start);
15418                end_row = Some(end);
15419                continue;
15420            }
15421            if let Some(current_end) = end_row.as_mut() {
15422                if start.row > current_end.row + 1 {
15423                    push_region(start_row, end_row);
15424                    start_row = Some(start);
15425                    end_row = Some(end);
15426                } else {
15427                    // Merge two hunks.
15428                    *current_end = end;
15429                }
15430            } else {
15431                unreachable!();
15432            }
15433        }
15434        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
15435        push_region(start_row, end_row);
15436        results
15437    }
15438
15439    pub fn gutter_highlights_in_range(
15440        &self,
15441        search_range: Range<Anchor>,
15442        display_snapshot: &DisplaySnapshot,
15443        cx: &App,
15444    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15445        let mut results = Vec::new();
15446        for (color_fetcher, ranges) in self.gutter_highlights.values() {
15447            let color = color_fetcher(cx);
15448            let start_ix = match ranges.binary_search_by(|probe| {
15449                let cmp = probe
15450                    .end
15451                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15452                if cmp.is_gt() {
15453                    Ordering::Greater
15454                } else {
15455                    Ordering::Less
15456                }
15457            }) {
15458                Ok(i) | Err(i) => i,
15459            };
15460            for range in &ranges[start_ix..] {
15461                if range
15462                    .start
15463                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15464                    .is_ge()
15465                {
15466                    break;
15467                }
15468
15469                let start = range.start.to_display_point(display_snapshot);
15470                let end = range.end.to_display_point(display_snapshot);
15471                results.push((start..end, color))
15472            }
15473        }
15474        results
15475    }
15476
15477    /// Get the text ranges corresponding to the redaction query
15478    pub fn redacted_ranges(
15479        &self,
15480        search_range: Range<Anchor>,
15481        display_snapshot: &DisplaySnapshot,
15482        cx: &App,
15483    ) -> Vec<Range<DisplayPoint>> {
15484        display_snapshot
15485            .buffer_snapshot
15486            .redacted_ranges(search_range, |file| {
15487                if let Some(file) = file {
15488                    file.is_private()
15489                        && EditorSettings::get(
15490                            Some(SettingsLocation {
15491                                worktree_id: file.worktree_id(cx),
15492                                path: file.path().as_ref(),
15493                            }),
15494                            cx,
15495                        )
15496                        .redact_private_values
15497                } else {
15498                    false
15499                }
15500            })
15501            .map(|range| {
15502                range.start.to_display_point(display_snapshot)
15503                    ..range.end.to_display_point(display_snapshot)
15504            })
15505            .collect()
15506    }
15507
15508    pub fn highlight_text<T: 'static>(
15509        &mut self,
15510        ranges: Vec<Range<Anchor>>,
15511        style: HighlightStyle,
15512        cx: &mut Context<Self>,
15513    ) {
15514        self.display_map.update(cx, |map, _| {
15515            map.highlight_text(TypeId::of::<T>(), ranges, style)
15516        });
15517        cx.notify();
15518    }
15519
15520    pub(crate) fn highlight_inlays<T: 'static>(
15521        &mut self,
15522        highlights: Vec<InlayHighlight>,
15523        style: HighlightStyle,
15524        cx: &mut Context<Self>,
15525    ) {
15526        self.display_map.update(cx, |map, _| {
15527            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
15528        });
15529        cx.notify();
15530    }
15531
15532    pub fn text_highlights<'a, T: 'static>(
15533        &'a self,
15534        cx: &'a App,
15535    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
15536        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
15537    }
15538
15539    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
15540        let cleared = self
15541            .display_map
15542            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
15543        if cleared {
15544            cx.notify();
15545        }
15546    }
15547
15548    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
15549        (self.read_only(cx) || self.blink_manager.read(cx).visible())
15550            && self.focus_handle.is_focused(window)
15551    }
15552
15553    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
15554        self.show_cursor_when_unfocused = is_enabled;
15555        cx.notify();
15556    }
15557
15558    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
15559        cx.notify();
15560    }
15561
15562    fn on_buffer_event(
15563        &mut self,
15564        multibuffer: &Entity<MultiBuffer>,
15565        event: &multi_buffer::Event,
15566        window: &mut Window,
15567        cx: &mut Context<Self>,
15568    ) {
15569        match event {
15570            multi_buffer::Event::Edited {
15571                singleton_buffer_edited,
15572                edited_buffer: buffer_edited,
15573            } => {
15574                self.scrollbar_marker_state.dirty = true;
15575                self.active_indent_guides_state.dirty = true;
15576                self.refresh_active_diagnostics(cx);
15577                self.refresh_code_actions(window, cx);
15578                if self.has_active_inline_completion() {
15579                    self.update_visible_inline_completion(window, cx);
15580                }
15581                if let Some(buffer) = buffer_edited {
15582                    let buffer_id = buffer.read(cx).remote_id();
15583                    if !self.registered_buffers.contains_key(&buffer_id) {
15584                        if let Some(project) = self.project.as_ref() {
15585                            project.update(cx, |project, cx| {
15586                                self.registered_buffers.insert(
15587                                    buffer_id,
15588                                    project.register_buffer_with_language_servers(&buffer, cx),
15589                                );
15590                            })
15591                        }
15592                    }
15593                }
15594                cx.emit(EditorEvent::BufferEdited);
15595                cx.emit(SearchEvent::MatchesInvalidated);
15596                if *singleton_buffer_edited {
15597                    if let Some(project) = &self.project {
15598                        #[allow(clippy::mutable_key_type)]
15599                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
15600                            multibuffer
15601                                .all_buffers()
15602                                .into_iter()
15603                                .filter_map(|buffer| {
15604                                    buffer.update(cx, |buffer, cx| {
15605                                        let language = buffer.language()?;
15606                                        let should_discard = project.update(cx, |project, cx| {
15607                                            project.is_local()
15608                                                && !project.has_language_servers_for(buffer, cx)
15609                                        });
15610                                        should_discard.not().then_some(language.clone())
15611                                    })
15612                                })
15613                                .collect::<HashSet<_>>()
15614                        });
15615                        if !languages_affected.is_empty() {
15616                            self.refresh_inlay_hints(
15617                                InlayHintRefreshReason::BufferEdited(languages_affected),
15618                                cx,
15619                            );
15620                        }
15621                    }
15622                }
15623
15624                let Some(project) = &self.project else { return };
15625                let (telemetry, is_via_ssh) = {
15626                    let project = project.read(cx);
15627                    let telemetry = project.client().telemetry().clone();
15628                    let is_via_ssh = project.is_via_ssh();
15629                    (telemetry, is_via_ssh)
15630                };
15631                refresh_linked_ranges(self, window, cx);
15632                telemetry.log_edit_event("editor", is_via_ssh);
15633            }
15634            multi_buffer::Event::ExcerptsAdded {
15635                buffer,
15636                predecessor,
15637                excerpts,
15638            } => {
15639                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15640                let buffer_id = buffer.read(cx).remote_id();
15641                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
15642                    if let Some(project) = &self.project {
15643                        get_uncommitted_diff_for_buffer(
15644                            project,
15645                            [buffer.clone()],
15646                            self.buffer.clone(),
15647                            cx,
15648                        )
15649                        .detach();
15650                    }
15651                }
15652                cx.emit(EditorEvent::ExcerptsAdded {
15653                    buffer: buffer.clone(),
15654                    predecessor: *predecessor,
15655                    excerpts: excerpts.clone(),
15656                });
15657                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15658            }
15659            multi_buffer::Event::ExcerptsRemoved { ids } => {
15660                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
15661                let buffer = self.buffer.read(cx);
15662                self.registered_buffers
15663                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
15664                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
15665                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
15666            }
15667            multi_buffer::Event::ExcerptsEdited {
15668                excerpt_ids,
15669                buffer_ids,
15670            } => {
15671                self.display_map.update(cx, |map, cx| {
15672                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
15673                });
15674                cx.emit(EditorEvent::ExcerptsEdited {
15675                    ids: excerpt_ids.clone(),
15676                })
15677            }
15678            multi_buffer::Event::ExcerptsExpanded { ids } => {
15679                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15680                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
15681            }
15682            multi_buffer::Event::Reparsed(buffer_id) => {
15683                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15684                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
15685
15686                cx.emit(EditorEvent::Reparsed(*buffer_id));
15687            }
15688            multi_buffer::Event::DiffHunksToggled => {
15689                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15690            }
15691            multi_buffer::Event::LanguageChanged(buffer_id) => {
15692                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
15693                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
15694                cx.emit(EditorEvent::Reparsed(*buffer_id));
15695                cx.notify();
15696            }
15697            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
15698            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
15699            multi_buffer::Event::FileHandleChanged
15700            | multi_buffer::Event::Reloaded
15701            | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
15702            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
15703            multi_buffer::Event::DiagnosticsUpdated => {
15704                self.refresh_active_diagnostics(cx);
15705                self.refresh_inline_diagnostics(true, window, cx);
15706                self.scrollbar_marker_state.dirty = true;
15707                cx.notify();
15708            }
15709            _ => {}
15710        };
15711    }
15712
15713    fn on_display_map_changed(
15714        &mut self,
15715        _: Entity<DisplayMap>,
15716        _: &mut Window,
15717        cx: &mut Context<Self>,
15718    ) {
15719        cx.notify();
15720    }
15721
15722    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15723        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15724        self.update_edit_prediction_settings(cx);
15725        self.refresh_inline_completion(true, false, window, cx);
15726        self.refresh_inlay_hints(
15727            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
15728                self.selections.newest_anchor().head(),
15729                &self.buffer.read(cx).snapshot(cx),
15730                cx,
15731            )),
15732            cx,
15733        );
15734
15735        let old_cursor_shape = self.cursor_shape;
15736
15737        {
15738            let editor_settings = EditorSettings::get_global(cx);
15739            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
15740            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
15741            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
15742        }
15743
15744        if old_cursor_shape != self.cursor_shape {
15745            cx.emit(EditorEvent::CursorShapeChanged);
15746        }
15747
15748        let project_settings = ProjectSettings::get_global(cx);
15749        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
15750
15751        if self.mode == EditorMode::Full {
15752            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
15753            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
15754            if self.show_inline_diagnostics != show_inline_diagnostics {
15755                self.show_inline_diagnostics = show_inline_diagnostics;
15756                self.refresh_inline_diagnostics(false, window, cx);
15757            }
15758
15759            if self.git_blame_inline_enabled != inline_blame_enabled {
15760                self.toggle_git_blame_inline_internal(false, window, cx);
15761            }
15762        }
15763
15764        cx.notify();
15765    }
15766
15767    pub fn set_searchable(&mut self, searchable: bool) {
15768        self.searchable = searchable;
15769    }
15770
15771    pub fn searchable(&self) -> bool {
15772        self.searchable
15773    }
15774
15775    fn open_proposed_changes_editor(
15776        &mut self,
15777        _: &OpenProposedChangesEditor,
15778        window: &mut Window,
15779        cx: &mut Context<Self>,
15780    ) {
15781        let Some(workspace) = self.workspace() else {
15782            cx.propagate();
15783            return;
15784        };
15785
15786        let selections = self.selections.all::<usize>(cx);
15787        let multi_buffer = self.buffer.read(cx);
15788        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15789        let mut new_selections_by_buffer = HashMap::default();
15790        for selection in selections {
15791            for (buffer, range, _) in
15792                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
15793            {
15794                let mut range = range.to_point(buffer);
15795                range.start.column = 0;
15796                range.end.column = buffer.line_len(range.end.row);
15797                new_selections_by_buffer
15798                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
15799                    .or_insert(Vec::new())
15800                    .push(range)
15801            }
15802        }
15803
15804        let proposed_changes_buffers = new_selections_by_buffer
15805            .into_iter()
15806            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
15807            .collect::<Vec<_>>();
15808        let proposed_changes_editor = cx.new(|cx| {
15809            ProposedChangesEditor::new(
15810                "Proposed changes",
15811                proposed_changes_buffers,
15812                self.project.clone(),
15813                window,
15814                cx,
15815            )
15816        });
15817
15818        window.defer(cx, move |window, cx| {
15819            workspace.update(cx, |workspace, cx| {
15820                workspace.active_pane().update(cx, |pane, cx| {
15821                    pane.add_item(
15822                        Box::new(proposed_changes_editor),
15823                        true,
15824                        true,
15825                        None,
15826                        window,
15827                        cx,
15828                    );
15829                });
15830            });
15831        });
15832    }
15833
15834    pub fn open_excerpts_in_split(
15835        &mut self,
15836        _: &OpenExcerptsSplit,
15837        window: &mut Window,
15838        cx: &mut Context<Self>,
15839    ) {
15840        self.open_excerpts_common(None, true, window, cx)
15841    }
15842
15843    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
15844        self.open_excerpts_common(None, false, window, cx)
15845    }
15846
15847    fn open_excerpts_common(
15848        &mut self,
15849        jump_data: Option<JumpData>,
15850        split: bool,
15851        window: &mut Window,
15852        cx: &mut Context<Self>,
15853    ) {
15854        let Some(workspace) = self.workspace() else {
15855            cx.propagate();
15856            return;
15857        };
15858
15859        if self.buffer.read(cx).is_singleton() {
15860            cx.propagate();
15861            return;
15862        }
15863
15864        let mut new_selections_by_buffer = HashMap::default();
15865        match &jump_data {
15866            Some(JumpData::MultiBufferPoint {
15867                excerpt_id,
15868                position,
15869                anchor,
15870                line_offset_from_top,
15871            }) => {
15872                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15873                if let Some(buffer) = multi_buffer_snapshot
15874                    .buffer_id_for_excerpt(*excerpt_id)
15875                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
15876                {
15877                    let buffer_snapshot = buffer.read(cx).snapshot();
15878                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
15879                        language::ToPoint::to_point(anchor, &buffer_snapshot)
15880                    } else {
15881                        buffer_snapshot.clip_point(*position, Bias::Left)
15882                    };
15883                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
15884                    new_selections_by_buffer.insert(
15885                        buffer,
15886                        (
15887                            vec![jump_to_offset..jump_to_offset],
15888                            Some(*line_offset_from_top),
15889                        ),
15890                    );
15891                }
15892            }
15893            Some(JumpData::MultiBufferRow {
15894                row,
15895                line_offset_from_top,
15896            }) => {
15897                let point = MultiBufferPoint::new(row.0, 0);
15898                if let Some((buffer, buffer_point, _)) =
15899                    self.buffer.read(cx).point_to_buffer_point(point, cx)
15900                {
15901                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
15902                    new_selections_by_buffer
15903                        .entry(buffer)
15904                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
15905                        .0
15906                        .push(buffer_offset..buffer_offset)
15907                }
15908            }
15909            None => {
15910                let selections = self.selections.all::<usize>(cx);
15911                let multi_buffer = self.buffer.read(cx);
15912                for selection in selections {
15913                    for (snapshot, range, _, anchor) in multi_buffer
15914                        .snapshot(cx)
15915                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
15916                    {
15917                        if let Some(anchor) = anchor {
15918                            // selection is in a deleted hunk
15919                            let Some(buffer_id) = anchor.buffer_id else {
15920                                continue;
15921                            };
15922                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
15923                                continue;
15924                            };
15925                            let offset = text::ToOffset::to_offset(
15926                                &anchor.text_anchor,
15927                                &buffer_handle.read(cx).snapshot(),
15928                            );
15929                            let range = offset..offset;
15930                            new_selections_by_buffer
15931                                .entry(buffer_handle)
15932                                .or_insert((Vec::new(), None))
15933                                .0
15934                                .push(range)
15935                        } else {
15936                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
15937                            else {
15938                                continue;
15939                            };
15940                            new_selections_by_buffer
15941                                .entry(buffer_handle)
15942                                .or_insert((Vec::new(), None))
15943                                .0
15944                                .push(range)
15945                        }
15946                    }
15947                }
15948            }
15949        }
15950
15951        if new_selections_by_buffer.is_empty() {
15952            return;
15953        }
15954
15955        // We defer the pane interaction because we ourselves are a workspace item
15956        // and activating a new item causes the pane to call a method on us reentrantly,
15957        // which panics if we're on the stack.
15958        window.defer(cx, move |window, cx| {
15959            workspace.update(cx, |workspace, cx| {
15960                let pane = if split {
15961                    workspace.adjacent_pane(window, cx)
15962                } else {
15963                    workspace.active_pane().clone()
15964                };
15965
15966                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
15967                    let editor = buffer
15968                        .read(cx)
15969                        .file()
15970                        .is_none()
15971                        .then(|| {
15972                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
15973                            // so `workspace.open_project_item` will never find them, always opening a new editor.
15974                            // Instead, we try to activate the existing editor in the pane first.
15975                            let (editor, pane_item_index) =
15976                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
15977                                    let editor = item.downcast::<Editor>()?;
15978                                    let singleton_buffer =
15979                                        editor.read(cx).buffer().read(cx).as_singleton()?;
15980                                    if singleton_buffer == buffer {
15981                                        Some((editor, i))
15982                                    } else {
15983                                        None
15984                                    }
15985                                })?;
15986                            pane.update(cx, |pane, cx| {
15987                                pane.activate_item(pane_item_index, true, true, window, cx)
15988                            });
15989                            Some(editor)
15990                        })
15991                        .flatten()
15992                        .unwrap_or_else(|| {
15993                            workspace.open_project_item::<Self>(
15994                                pane.clone(),
15995                                buffer,
15996                                true,
15997                                true,
15998                                window,
15999                                cx,
16000                            )
16001                        });
16002
16003                    editor.update(cx, |editor, cx| {
16004                        let autoscroll = match scroll_offset {
16005                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
16006                            None => Autoscroll::newest(),
16007                        };
16008                        let nav_history = editor.nav_history.take();
16009                        editor.change_selections(Some(autoscroll), window, cx, |s| {
16010                            s.select_ranges(ranges);
16011                        });
16012                        editor.nav_history = nav_history;
16013                    });
16014                }
16015            })
16016        });
16017    }
16018
16019    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
16020        let snapshot = self.buffer.read(cx).read(cx);
16021        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
16022        Some(
16023            ranges
16024                .iter()
16025                .map(move |range| {
16026                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
16027                })
16028                .collect(),
16029        )
16030    }
16031
16032    fn selection_replacement_ranges(
16033        &self,
16034        range: Range<OffsetUtf16>,
16035        cx: &mut App,
16036    ) -> Vec<Range<OffsetUtf16>> {
16037        let selections = self.selections.all::<OffsetUtf16>(cx);
16038        let newest_selection = selections
16039            .iter()
16040            .max_by_key(|selection| selection.id)
16041            .unwrap();
16042        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
16043        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
16044        let snapshot = self.buffer.read(cx).read(cx);
16045        selections
16046            .into_iter()
16047            .map(|mut selection| {
16048                selection.start.0 =
16049                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
16050                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
16051                snapshot.clip_offset_utf16(selection.start, Bias::Left)
16052                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
16053            })
16054            .collect()
16055    }
16056
16057    fn report_editor_event(
16058        &self,
16059        event_type: &'static str,
16060        file_extension: Option<String>,
16061        cx: &App,
16062    ) {
16063        if cfg!(any(test, feature = "test-support")) {
16064            return;
16065        }
16066
16067        let Some(project) = &self.project else { return };
16068
16069        // If None, we are in a file without an extension
16070        let file = self
16071            .buffer
16072            .read(cx)
16073            .as_singleton()
16074            .and_then(|b| b.read(cx).file());
16075        let file_extension = file_extension.or(file
16076            .as_ref()
16077            .and_then(|file| Path::new(file.file_name(cx)).extension())
16078            .and_then(|e| e.to_str())
16079            .map(|a| a.to_string()));
16080
16081        let vim_mode = cx
16082            .global::<SettingsStore>()
16083            .raw_user_settings()
16084            .get("vim_mode")
16085            == Some(&serde_json::Value::Bool(true));
16086
16087        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
16088        let copilot_enabled = edit_predictions_provider
16089            == language::language_settings::EditPredictionProvider::Copilot;
16090        let copilot_enabled_for_language = self
16091            .buffer
16092            .read(cx)
16093            .language_settings(cx)
16094            .show_edit_predictions;
16095
16096        let project = project.read(cx);
16097        telemetry::event!(
16098            event_type,
16099            file_extension,
16100            vim_mode,
16101            copilot_enabled,
16102            copilot_enabled_for_language,
16103            edit_predictions_provider,
16104            is_via_ssh = project.is_via_ssh(),
16105        );
16106    }
16107
16108    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
16109    /// with each line being an array of {text, highlight} objects.
16110    fn copy_highlight_json(
16111        &mut self,
16112        _: &CopyHighlightJson,
16113        window: &mut Window,
16114        cx: &mut Context<Self>,
16115    ) {
16116        #[derive(Serialize)]
16117        struct Chunk<'a> {
16118            text: String,
16119            highlight: Option<&'a str>,
16120        }
16121
16122        let snapshot = self.buffer.read(cx).snapshot(cx);
16123        let range = self
16124            .selected_text_range(false, window, cx)
16125            .and_then(|selection| {
16126                if selection.range.is_empty() {
16127                    None
16128                } else {
16129                    Some(selection.range)
16130                }
16131            })
16132            .unwrap_or_else(|| 0..snapshot.len());
16133
16134        let chunks = snapshot.chunks(range, true);
16135        let mut lines = Vec::new();
16136        let mut line: VecDeque<Chunk> = VecDeque::new();
16137
16138        let Some(style) = self.style.as_ref() else {
16139            return;
16140        };
16141
16142        for chunk in chunks {
16143            let highlight = chunk
16144                .syntax_highlight_id
16145                .and_then(|id| id.name(&style.syntax));
16146            let mut chunk_lines = chunk.text.split('\n').peekable();
16147            while let Some(text) = chunk_lines.next() {
16148                let mut merged_with_last_token = false;
16149                if let Some(last_token) = line.back_mut() {
16150                    if last_token.highlight == highlight {
16151                        last_token.text.push_str(text);
16152                        merged_with_last_token = true;
16153                    }
16154                }
16155
16156                if !merged_with_last_token {
16157                    line.push_back(Chunk {
16158                        text: text.into(),
16159                        highlight,
16160                    });
16161                }
16162
16163                if chunk_lines.peek().is_some() {
16164                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
16165                        line.pop_front();
16166                    }
16167                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
16168                        line.pop_back();
16169                    }
16170
16171                    lines.push(mem::take(&mut line));
16172                }
16173            }
16174        }
16175
16176        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
16177            return;
16178        };
16179        cx.write_to_clipboard(ClipboardItem::new_string(lines));
16180    }
16181
16182    pub fn open_context_menu(
16183        &mut self,
16184        _: &OpenContextMenu,
16185        window: &mut Window,
16186        cx: &mut Context<Self>,
16187    ) {
16188        self.request_autoscroll(Autoscroll::newest(), cx);
16189        let position = self.selections.newest_display(cx).start;
16190        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
16191    }
16192
16193    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
16194        &self.inlay_hint_cache
16195    }
16196
16197    pub fn replay_insert_event(
16198        &mut self,
16199        text: &str,
16200        relative_utf16_range: Option<Range<isize>>,
16201        window: &mut Window,
16202        cx: &mut Context<Self>,
16203    ) {
16204        if !self.input_enabled {
16205            cx.emit(EditorEvent::InputIgnored { text: text.into() });
16206            return;
16207        }
16208        if let Some(relative_utf16_range) = relative_utf16_range {
16209            let selections = self.selections.all::<OffsetUtf16>(cx);
16210            self.change_selections(None, window, cx, |s| {
16211                let new_ranges = selections.into_iter().map(|range| {
16212                    let start = OffsetUtf16(
16213                        range
16214                            .head()
16215                            .0
16216                            .saturating_add_signed(relative_utf16_range.start),
16217                    );
16218                    let end = OffsetUtf16(
16219                        range
16220                            .head()
16221                            .0
16222                            .saturating_add_signed(relative_utf16_range.end),
16223                    );
16224                    start..end
16225                });
16226                s.select_ranges(new_ranges);
16227            });
16228        }
16229
16230        self.handle_input(text, window, cx);
16231    }
16232
16233    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
16234        let Some(provider) = self.semantics_provider.as_ref() else {
16235            return false;
16236        };
16237
16238        let mut supports = false;
16239        self.buffer().update(cx, |this, cx| {
16240            this.for_each_buffer(|buffer| {
16241                supports |= provider.supports_inlay_hints(buffer, cx);
16242            });
16243        });
16244
16245        supports
16246    }
16247
16248    pub fn is_focused(&self, window: &Window) -> bool {
16249        self.focus_handle.is_focused(window)
16250    }
16251
16252    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16253        cx.emit(EditorEvent::Focused);
16254
16255        if let Some(descendant) = self
16256            .last_focused_descendant
16257            .take()
16258            .and_then(|descendant| descendant.upgrade())
16259        {
16260            window.focus(&descendant);
16261        } else {
16262            if let Some(blame) = self.blame.as_ref() {
16263                blame.update(cx, GitBlame::focus)
16264            }
16265
16266            self.blink_manager.update(cx, BlinkManager::enable);
16267            self.show_cursor_names(window, cx);
16268            self.buffer.update(cx, |buffer, cx| {
16269                buffer.finalize_last_transaction(cx);
16270                if self.leader_peer_id.is_none() {
16271                    buffer.set_active_selections(
16272                        &self.selections.disjoint_anchors(),
16273                        self.selections.line_mode,
16274                        self.cursor_shape,
16275                        cx,
16276                    );
16277                }
16278            });
16279        }
16280    }
16281
16282    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16283        cx.emit(EditorEvent::FocusedIn)
16284    }
16285
16286    fn handle_focus_out(
16287        &mut self,
16288        event: FocusOutEvent,
16289        _window: &mut Window,
16290        cx: &mut Context<Self>,
16291    ) {
16292        if event.blurred != self.focus_handle {
16293            self.last_focused_descendant = Some(event.blurred);
16294        }
16295        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
16296    }
16297
16298    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16299        self.blink_manager.update(cx, BlinkManager::disable);
16300        self.buffer
16301            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
16302
16303        if let Some(blame) = self.blame.as_ref() {
16304            blame.update(cx, GitBlame::blur)
16305        }
16306        if !self.hover_state.focused(window, cx) {
16307            hide_hover(self, cx);
16308        }
16309        if !self
16310            .context_menu
16311            .borrow()
16312            .as_ref()
16313            .is_some_and(|context_menu| context_menu.focused(window, cx))
16314        {
16315            self.hide_context_menu(window, cx);
16316        }
16317        self.discard_inline_completion(false, cx);
16318        cx.emit(EditorEvent::Blurred);
16319        cx.notify();
16320    }
16321
16322    pub fn register_action<A: Action>(
16323        &mut self,
16324        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
16325    ) -> Subscription {
16326        let id = self.next_editor_action_id.post_inc();
16327        let listener = Arc::new(listener);
16328        self.editor_actions.borrow_mut().insert(
16329            id,
16330            Box::new(move |window, _| {
16331                let listener = listener.clone();
16332                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
16333                    let action = action.downcast_ref().unwrap();
16334                    if phase == DispatchPhase::Bubble {
16335                        listener(action, window, cx)
16336                    }
16337                })
16338            }),
16339        );
16340
16341        let editor_actions = self.editor_actions.clone();
16342        Subscription::new(move || {
16343            editor_actions.borrow_mut().remove(&id);
16344        })
16345    }
16346
16347    pub fn file_header_size(&self) -> u32 {
16348        FILE_HEADER_HEIGHT
16349    }
16350
16351    pub fn restore(
16352        &mut self,
16353        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
16354        window: &mut Window,
16355        cx: &mut Context<Self>,
16356    ) {
16357        let workspace = self.workspace();
16358        let project = self.project.as_ref();
16359        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
16360            let mut tasks = Vec::new();
16361            for (buffer_id, changes) in revert_changes {
16362                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
16363                    buffer.update(cx, |buffer, cx| {
16364                        buffer.edit(
16365                            changes
16366                                .into_iter()
16367                                .map(|(range, text)| (range, text.to_string())),
16368                            None,
16369                            cx,
16370                        );
16371                    });
16372
16373                    if let Some(project) =
16374                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
16375                    {
16376                        project.update(cx, |project, cx| {
16377                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
16378                        })
16379                    }
16380                }
16381            }
16382            tasks
16383        });
16384        cx.spawn_in(window, |_, mut cx| async move {
16385            for (buffer, task) in save_tasks {
16386                let result = task.await;
16387                if result.is_err() {
16388                    let Some(path) = buffer
16389                        .read_with(&cx, |buffer, cx| buffer.project_path(cx))
16390                        .ok()
16391                    else {
16392                        continue;
16393                    };
16394                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
16395                        let Some(task) = cx
16396                            .update_window_entity(&workspace, |workspace, window, cx| {
16397                                workspace
16398                                    .open_path_preview(path, None, false, false, false, window, cx)
16399                            })
16400                            .ok()
16401                        else {
16402                            continue;
16403                        };
16404                        task.await.log_err();
16405                    }
16406                }
16407            }
16408        })
16409        .detach();
16410        self.change_selections(None, window, cx, |selections| selections.refresh());
16411    }
16412
16413    pub fn to_pixel_point(
16414        &self,
16415        source: multi_buffer::Anchor,
16416        editor_snapshot: &EditorSnapshot,
16417        window: &mut Window,
16418    ) -> Option<gpui::Point<Pixels>> {
16419        let source_point = source.to_display_point(editor_snapshot);
16420        self.display_to_pixel_point(source_point, editor_snapshot, window)
16421    }
16422
16423    pub fn display_to_pixel_point(
16424        &self,
16425        source: DisplayPoint,
16426        editor_snapshot: &EditorSnapshot,
16427        window: &mut Window,
16428    ) -> Option<gpui::Point<Pixels>> {
16429        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
16430        let text_layout_details = self.text_layout_details(window);
16431        let scroll_top = text_layout_details
16432            .scroll_anchor
16433            .scroll_position(editor_snapshot)
16434            .y;
16435
16436        if source.row().as_f32() < scroll_top.floor() {
16437            return None;
16438        }
16439        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
16440        let source_y = line_height * (source.row().as_f32() - scroll_top);
16441        Some(gpui::Point::new(source_x, source_y))
16442    }
16443
16444    pub fn has_visible_completions_menu(&self) -> bool {
16445        !self.edit_prediction_preview_is_active()
16446            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
16447                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
16448            })
16449    }
16450
16451    pub fn register_addon<T: Addon>(&mut self, instance: T) {
16452        self.addons
16453            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
16454    }
16455
16456    pub fn unregister_addon<T: Addon>(&mut self) {
16457        self.addons.remove(&std::any::TypeId::of::<T>());
16458    }
16459
16460    pub fn addon<T: Addon>(&self) -> Option<&T> {
16461        let type_id = std::any::TypeId::of::<T>();
16462        self.addons
16463            .get(&type_id)
16464            .and_then(|item| item.to_any().downcast_ref::<T>())
16465    }
16466
16467    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
16468        let text_layout_details = self.text_layout_details(window);
16469        let style = &text_layout_details.editor_style;
16470        let font_id = window.text_system().resolve_font(&style.text.font());
16471        let font_size = style.text.font_size.to_pixels(window.rem_size());
16472        let line_height = style.text.line_height_in_pixels(window.rem_size());
16473        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
16474
16475        gpui::Size::new(em_width, line_height)
16476    }
16477
16478    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
16479        self.load_diff_task.clone()
16480    }
16481
16482    fn read_selections_from_db(
16483        &mut self,
16484        item_id: u64,
16485        workspace_id: WorkspaceId,
16486        window: &mut Window,
16487        cx: &mut Context<Editor>,
16488    ) {
16489        if !self.is_singleton(cx)
16490            || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
16491        {
16492            return;
16493        }
16494        let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
16495            return;
16496        };
16497        if selections.is_empty() {
16498            return;
16499        }
16500
16501        let snapshot = self.buffer.read(cx).snapshot(cx);
16502        self.change_selections(None, window, cx, |s| {
16503            s.select_ranges(selections.into_iter().map(|(start, end)| {
16504                snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
16505            }));
16506        });
16507    }
16508}
16509
16510fn insert_extra_newline_brackets(
16511    buffer: &MultiBufferSnapshot,
16512    range: Range<usize>,
16513    language: &language::LanguageScope,
16514) -> bool {
16515    let leading_whitespace_len = buffer
16516        .reversed_chars_at(range.start)
16517        .take_while(|c| c.is_whitespace() && *c != '\n')
16518        .map(|c| c.len_utf8())
16519        .sum::<usize>();
16520    let trailing_whitespace_len = buffer
16521        .chars_at(range.end)
16522        .take_while(|c| c.is_whitespace() && *c != '\n')
16523        .map(|c| c.len_utf8())
16524        .sum::<usize>();
16525    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
16526
16527    language.brackets().any(|(pair, enabled)| {
16528        let pair_start = pair.start.trim_end();
16529        let pair_end = pair.end.trim_start();
16530
16531        enabled
16532            && pair.newline
16533            && buffer.contains_str_at(range.end, pair_end)
16534            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
16535    })
16536}
16537
16538fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
16539    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
16540        [(buffer, range, _)] => (*buffer, range.clone()),
16541        _ => return false,
16542    };
16543    let pair = {
16544        let mut result: Option<BracketMatch> = None;
16545
16546        for pair in buffer
16547            .all_bracket_ranges(range.clone())
16548            .filter(move |pair| {
16549                pair.open_range.start <= range.start && pair.close_range.end >= range.end
16550            })
16551        {
16552            let len = pair.close_range.end - pair.open_range.start;
16553
16554            if let Some(existing) = &result {
16555                let existing_len = existing.close_range.end - existing.open_range.start;
16556                if len > existing_len {
16557                    continue;
16558                }
16559            }
16560
16561            result = Some(pair);
16562        }
16563
16564        result
16565    };
16566    let Some(pair) = pair else {
16567        return false;
16568    };
16569    pair.newline_only
16570        && buffer
16571            .chars_for_range(pair.open_range.end..range.start)
16572            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
16573            .all(|c| c.is_whitespace() && c != '\n')
16574}
16575
16576fn get_uncommitted_diff_for_buffer(
16577    project: &Entity<Project>,
16578    buffers: impl IntoIterator<Item = Entity<Buffer>>,
16579    buffer: Entity<MultiBuffer>,
16580    cx: &mut App,
16581) -> Task<()> {
16582    let mut tasks = Vec::new();
16583    project.update(cx, |project, cx| {
16584        for buffer in buffers {
16585            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
16586        }
16587    });
16588    cx.spawn(|mut cx| async move {
16589        let diffs = future::join_all(tasks).await;
16590        buffer
16591            .update(&mut cx, |buffer, cx| {
16592                for diff in diffs.into_iter().flatten() {
16593                    buffer.add_diff(diff, cx);
16594                }
16595            })
16596            .ok();
16597    })
16598}
16599
16600fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
16601    let tab_size = tab_size.get() as usize;
16602    let mut width = offset;
16603
16604    for ch in text.chars() {
16605        width += if ch == '\t' {
16606            tab_size - (width % tab_size)
16607        } else {
16608            1
16609        };
16610    }
16611
16612    width - offset
16613}
16614
16615#[cfg(test)]
16616mod tests {
16617    use super::*;
16618
16619    #[test]
16620    fn test_string_size_with_expanded_tabs() {
16621        let nz = |val| NonZeroU32::new(val).unwrap();
16622        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
16623        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
16624        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
16625        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
16626        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
16627        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
16628        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
16629        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
16630    }
16631}
16632
16633/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
16634struct WordBreakingTokenizer<'a> {
16635    input: &'a str,
16636}
16637
16638impl<'a> WordBreakingTokenizer<'a> {
16639    fn new(input: &'a str) -> Self {
16640        Self { input }
16641    }
16642}
16643
16644fn is_char_ideographic(ch: char) -> bool {
16645    use unicode_script::Script::*;
16646    use unicode_script::UnicodeScript;
16647    matches!(ch.script(), Han | Tangut | Yi)
16648}
16649
16650fn is_grapheme_ideographic(text: &str) -> bool {
16651    text.chars().any(is_char_ideographic)
16652}
16653
16654fn is_grapheme_whitespace(text: &str) -> bool {
16655    text.chars().any(|x| x.is_whitespace())
16656}
16657
16658fn should_stay_with_preceding_ideograph(text: &str) -> bool {
16659    text.chars().next().map_or(false, |ch| {
16660        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
16661    })
16662}
16663
16664#[derive(PartialEq, Eq, Debug, Clone, Copy)]
16665struct WordBreakToken<'a> {
16666    token: &'a str,
16667    grapheme_len: usize,
16668    is_whitespace: bool,
16669}
16670
16671impl<'a> Iterator for WordBreakingTokenizer<'a> {
16672    /// Yields a span, the count of graphemes in the token, and whether it was
16673    /// whitespace. Note that it also breaks at word boundaries.
16674    type Item = WordBreakToken<'a>;
16675
16676    fn next(&mut self) -> Option<Self::Item> {
16677        use unicode_segmentation::UnicodeSegmentation;
16678        if self.input.is_empty() {
16679            return None;
16680        }
16681
16682        let mut iter = self.input.graphemes(true).peekable();
16683        let mut offset = 0;
16684        let mut graphemes = 0;
16685        if let Some(first_grapheme) = iter.next() {
16686            let is_whitespace = is_grapheme_whitespace(first_grapheme);
16687            offset += first_grapheme.len();
16688            graphemes += 1;
16689            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
16690                if let Some(grapheme) = iter.peek().copied() {
16691                    if should_stay_with_preceding_ideograph(grapheme) {
16692                        offset += grapheme.len();
16693                        graphemes += 1;
16694                    }
16695                }
16696            } else {
16697                let mut words = self.input[offset..].split_word_bound_indices().peekable();
16698                let mut next_word_bound = words.peek().copied();
16699                if next_word_bound.map_or(false, |(i, _)| i == 0) {
16700                    next_word_bound = words.next();
16701                }
16702                while let Some(grapheme) = iter.peek().copied() {
16703                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
16704                        break;
16705                    };
16706                    if is_grapheme_whitespace(grapheme) != is_whitespace {
16707                        break;
16708                    };
16709                    offset += grapheme.len();
16710                    graphemes += 1;
16711                    iter.next();
16712                }
16713            }
16714            let token = &self.input[..offset];
16715            self.input = &self.input[offset..];
16716            if is_whitespace {
16717                Some(WordBreakToken {
16718                    token: " ",
16719                    grapheme_len: 1,
16720                    is_whitespace: true,
16721                })
16722            } else {
16723                Some(WordBreakToken {
16724                    token,
16725                    grapheme_len: graphemes,
16726                    is_whitespace: false,
16727                })
16728            }
16729        } else {
16730            None
16731        }
16732    }
16733}
16734
16735#[test]
16736fn test_word_breaking_tokenizer() {
16737    let tests: &[(&str, &[(&str, usize, bool)])] = &[
16738        ("", &[]),
16739        ("  ", &[(" ", 1, true)]),
16740        ("Ʒ", &[("Ʒ", 1, false)]),
16741        ("Ǽ", &[("Ǽ", 1, false)]),
16742        ("", &[("", 1, false)]),
16743        ("⋑⋑", &[("⋑⋑", 2, false)]),
16744        (
16745            "原理,进而",
16746            &[
16747                ("", 1, false),
16748                ("理,", 2, false),
16749                ("", 1, false),
16750                ("", 1, false),
16751            ],
16752        ),
16753        (
16754            "hello world",
16755            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
16756        ),
16757        (
16758            "hello, world",
16759            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
16760        ),
16761        (
16762            "  hello world",
16763            &[
16764                (" ", 1, true),
16765                ("hello", 5, false),
16766                (" ", 1, true),
16767                ("world", 5, false),
16768            ],
16769        ),
16770        (
16771            "这是什么 \n 钢笔",
16772            &[
16773                ("", 1, false),
16774                ("", 1, false),
16775                ("", 1, false),
16776                ("", 1, false),
16777                (" ", 1, true),
16778                ("", 1, false),
16779                ("", 1, false),
16780            ],
16781        ),
16782        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
16783    ];
16784
16785    for (input, result) in tests {
16786        assert_eq!(
16787            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
16788            result
16789                .iter()
16790                .copied()
16791                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
16792                    token,
16793                    grapheme_len,
16794                    is_whitespace,
16795                })
16796                .collect::<Vec<_>>()
16797        );
16798    }
16799}
16800
16801fn wrap_with_prefix(
16802    line_prefix: String,
16803    unwrapped_text: String,
16804    wrap_column: usize,
16805    tab_size: NonZeroU32,
16806) -> String {
16807    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
16808    let mut wrapped_text = String::new();
16809    let mut current_line = line_prefix.clone();
16810
16811    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
16812    let mut current_line_len = line_prefix_len;
16813    for WordBreakToken {
16814        token,
16815        grapheme_len,
16816        is_whitespace,
16817    } in tokenizer
16818    {
16819        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
16820            wrapped_text.push_str(current_line.trim_end());
16821            wrapped_text.push('\n');
16822            current_line.truncate(line_prefix.len());
16823            current_line_len = line_prefix_len;
16824            if !is_whitespace {
16825                current_line.push_str(token);
16826                current_line_len += grapheme_len;
16827            }
16828        } else if !is_whitespace {
16829            current_line.push_str(token);
16830            current_line_len += grapheme_len;
16831        } else if current_line_len != line_prefix_len {
16832            current_line.push(' ');
16833            current_line_len += 1;
16834        }
16835    }
16836
16837    if !current_line.is_empty() {
16838        wrapped_text.push_str(&current_line);
16839    }
16840    wrapped_text
16841}
16842
16843#[test]
16844fn test_wrap_with_prefix() {
16845    assert_eq!(
16846        wrap_with_prefix(
16847            "# ".to_string(),
16848            "abcdefg".to_string(),
16849            4,
16850            NonZeroU32::new(4).unwrap()
16851        ),
16852        "# abcdefg"
16853    );
16854    assert_eq!(
16855        wrap_with_prefix(
16856            "".to_string(),
16857            "\thello world".to_string(),
16858            8,
16859            NonZeroU32::new(4).unwrap()
16860        ),
16861        "hello\nworld"
16862    );
16863    assert_eq!(
16864        wrap_with_prefix(
16865            "// ".to_string(),
16866            "xx \nyy zz aa bb cc".to_string(),
16867            12,
16868            NonZeroU32::new(4).unwrap()
16869        ),
16870        "// xx yy zz\n// aa bb cc"
16871    );
16872    assert_eq!(
16873        wrap_with_prefix(
16874            String::new(),
16875            "这是什么 \n 钢笔".to_string(),
16876            3,
16877            NonZeroU32::new(4).unwrap()
16878        ),
16879        "这是什\n么 钢\n"
16880    );
16881}
16882
16883pub trait CollaborationHub {
16884    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
16885    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
16886    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
16887}
16888
16889impl CollaborationHub for Entity<Project> {
16890    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
16891        self.read(cx).collaborators()
16892    }
16893
16894    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
16895        self.read(cx).user_store().read(cx).participant_indices()
16896    }
16897
16898    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
16899        let this = self.read(cx);
16900        let user_ids = this.collaborators().values().map(|c| c.user_id);
16901        this.user_store().read_with(cx, |user_store, cx| {
16902            user_store.participant_names(user_ids, cx)
16903        })
16904    }
16905}
16906
16907pub trait SemanticsProvider {
16908    fn hover(
16909        &self,
16910        buffer: &Entity<Buffer>,
16911        position: text::Anchor,
16912        cx: &mut App,
16913    ) -> Option<Task<Vec<project::Hover>>>;
16914
16915    fn inlay_hints(
16916        &self,
16917        buffer_handle: Entity<Buffer>,
16918        range: Range<text::Anchor>,
16919        cx: &mut App,
16920    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
16921
16922    fn resolve_inlay_hint(
16923        &self,
16924        hint: InlayHint,
16925        buffer_handle: Entity<Buffer>,
16926        server_id: LanguageServerId,
16927        cx: &mut App,
16928    ) -> Option<Task<anyhow::Result<InlayHint>>>;
16929
16930    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
16931
16932    fn document_highlights(
16933        &self,
16934        buffer: &Entity<Buffer>,
16935        position: text::Anchor,
16936        cx: &mut App,
16937    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
16938
16939    fn definitions(
16940        &self,
16941        buffer: &Entity<Buffer>,
16942        position: text::Anchor,
16943        kind: GotoDefinitionKind,
16944        cx: &mut App,
16945    ) -> Option<Task<Result<Vec<LocationLink>>>>;
16946
16947    fn range_for_rename(
16948        &self,
16949        buffer: &Entity<Buffer>,
16950        position: text::Anchor,
16951        cx: &mut App,
16952    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
16953
16954    fn perform_rename(
16955        &self,
16956        buffer: &Entity<Buffer>,
16957        position: text::Anchor,
16958        new_name: String,
16959        cx: &mut App,
16960    ) -> Option<Task<Result<ProjectTransaction>>>;
16961}
16962
16963pub trait CompletionProvider {
16964    fn completions(
16965        &self,
16966        buffer: &Entity<Buffer>,
16967        buffer_position: text::Anchor,
16968        trigger: CompletionContext,
16969        window: &mut Window,
16970        cx: &mut Context<Editor>,
16971    ) -> Task<Result<Option<Vec<Completion>>>>;
16972
16973    fn resolve_completions(
16974        &self,
16975        buffer: Entity<Buffer>,
16976        completion_indices: Vec<usize>,
16977        completions: Rc<RefCell<Box<[Completion]>>>,
16978        cx: &mut Context<Editor>,
16979    ) -> Task<Result<bool>>;
16980
16981    fn apply_additional_edits_for_completion(
16982        &self,
16983        _buffer: Entity<Buffer>,
16984        _completions: Rc<RefCell<Box<[Completion]>>>,
16985        _completion_index: usize,
16986        _push_to_history: bool,
16987        _cx: &mut Context<Editor>,
16988    ) -> Task<Result<Option<language::Transaction>>> {
16989        Task::ready(Ok(None))
16990    }
16991
16992    fn is_completion_trigger(
16993        &self,
16994        buffer: &Entity<Buffer>,
16995        position: language::Anchor,
16996        text: &str,
16997        trigger_in_words: bool,
16998        cx: &mut Context<Editor>,
16999    ) -> bool;
17000
17001    fn sort_completions(&self) -> bool {
17002        true
17003    }
17004}
17005
17006pub trait CodeActionProvider {
17007    fn id(&self) -> Arc<str>;
17008
17009    fn code_actions(
17010        &self,
17011        buffer: &Entity<Buffer>,
17012        range: Range<text::Anchor>,
17013        window: &mut Window,
17014        cx: &mut App,
17015    ) -> Task<Result<Vec<CodeAction>>>;
17016
17017    fn apply_code_action(
17018        &self,
17019        buffer_handle: Entity<Buffer>,
17020        action: CodeAction,
17021        excerpt_id: ExcerptId,
17022        push_to_history: bool,
17023        window: &mut Window,
17024        cx: &mut App,
17025    ) -> Task<Result<ProjectTransaction>>;
17026}
17027
17028impl CodeActionProvider for Entity<Project> {
17029    fn id(&self) -> Arc<str> {
17030        "project".into()
17031    }
17032
17033    fn code_actions(
17034        &self,
17035        buffer: &Entity<Buffer>,
17036        range: Range<text::Anchor>,
17037        _window: &mut Window,
17038        cx: &mut App,
17039    ) -> Task<Result<Vec<CodeAction>>> {
17040        self.update(cx, |project, cx| {
17041            let code_lens = project.code_lens(buffer, range.clone(), cx);
17042            let code_actions = project.code_actions(buffer, range, None, cx);
17043            cx.background_spawn(async move {
17044                let (code_lens, code_actions) = join(code_lens, code_actions).await;
17045                Ok(code_lens
17046                    .context("code lens fetch")?
17047                    .into_iter()
17048                    .chain(code_actions.context("code action fetch")?)
17049                    .collect())
17050            })
17051        })
17052    }
17053
17054    fn apply_code_action(
17055        &self,
17056        buffer_handle: Entity<Buffer>,
17057        action: CodeAction,
17058        _excerpt_id: ExcerptId,
17059        push_to_history: bool,
17060        _window: &mut Window,
17061        cx: &mut App,
17062    ) -> Task<Result<ProjectTransaction>> {
17063        self.update(cx, |project, cx| {
17064            project.apply_code_action(buffer_handle, action, push_to_history, cx)
17065        })
17066    }
17067}
17068
17069fn snippet_completions(
17070    project: &Project,
17071    buffer: &Entity<Buffer>,
17072    buffer_position: text::Anchor,
17073    cx: &mut App,
17074) -> Task<Result<Vec<Completion>>> {
17075    let language = buffer.read(cx).language_at(buffer_position);
17076    let language_name = language.as_ref().map(|language| language.lsp_id());
17077    let snippet_store = project.snippets().read(cx);
17078    let snippets = snippet_store.snippets_for(language_name, cx);
17079
17080    if snippets.is_empty() {
17081        return Task::ready(Ok(vec![]));
17082    }
17083    let snapshot = buffer.read(cx).text_snapshot();
17084    let chars: String = snapshot
17085        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
17086        .collect();
17087
17088    let scope = language.map(|language| language.default_scope());
17089    let executor = cx.background_executor().clone();
17090
17091    cx.background_spawn(async move {
17092        let classifier = CharClassifier::new(scope).for_completion(true);
17093        let mut last_word = chars
17094            .chars()
17095            .take_while(|c| classifier.is_word(*c))
17096            .collect::<String>();
17097        last_word = last_word.chars().rev().collect();
17098
17099        if last_word.is_empty() {
17100            return Ok(vec![]);
17101        }
17102
17103        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
17104        let to_lsp = |point: &text::Anchor| {
17105            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
17106            point_to_lsp(end)
17107        };
17108        let lsp_end = to_lsp(&buffer_position);
17109
17110        let candidates = snippets
17111            .iter()
17112            .enumerate()
17113            .flat_map(|(ix, snippet)| {
17114                snippet
17115                    .prefix
17116                    .iter()
17117                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
17118            })
17119            .collect::<Vec<StringMatchCandidate>>();
17120
17121        let mut matches = fuzzy::match_strings(
17122            &candidates,
17123            &last_word,
17124            last_word.chars().any(|c| c.is_uppercase()),
17125            100,
17126            &Default::default(),
17127            executor,
17128        )
17129        .await;
17130
17131        // Remove all candidates where the query's start does not match the start of any word in the candidate
17132        if let Some(query_start) = last_word.chars().next() {
17133            matches.retain(|string_match| {
17134                split_words(&string_match.string).any(|word| {
17135                    // Check that the first codepoint of the word as lowercase matches the first
17136                    // codepoint of the query as lowercase
17137                    word.chars()
17138                        .flat_map(|codepoint| codepoint.to_lowercase())
17139                        .zip(query_start.to_lowercase())
17140                        .all(|(word_cp, query_cp)| word_cp == query_cp)
17141                })
17142            });
17143        }
17144
17145        let matched_strings = matches
17146            .into_iter()
17147            .map(|m| m.string)
17148            .collect::<HashSet<_>>();
17149
17150        let result: Vec<Completion> = snippets
17151            .into_iter()
17152            .filter_map(|snippet| {
17153                let matching_prefix = snippet
17154                    .prefix
17155                    .iter()
17156                    .find(|prefix| matched_strings.contains(*prefix))?;
17157                let start = as_offset - last_word.len();
17158                let start = snapshot.anchor_before(start);
17159                let range = start..buffer_position;
17160                let lsp_start = to_lsp(&start);
17161                let lsp_range = lsp::Range {
17162                    start: lsp_start,
17163                    end: lsp_end,
17164                };
17165                Some(Completion {
17166                    old_range: range,
17167                    new_text: snippet.body.clone(),
17168                    source: CompletionSource::Lsp {
17169                        server_id: LanguageServerId(usize::MAX),
17170                        resolved: true,
17171                        lsp_completion: Box::new(lsp::CompletionItem {
17172                            label: snippet.prefix.first().unwrap().clone(),
17173                            kind: Some(CompletionItemKind::SNIPPET),
17174                            label_details: snippet.description.as_ref().map(|description| {
17175                                lsp::CompletionItemLabelDetails {
17176                                    detail: Some(description.clone()),
17177                                    description: None,
17178                                }
17179                            }),
17180                            insert_text_format: Some(InsertTextFormat::SNIPPET),
17181                            text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
17182                                lsp::InsertReplaceEdit {
17183                                    new_text: snippet.body.clone(),
17184                                    insert: lsp_range,
17185                                    replace: lsp_range,
17186                                },
17187                            )),
17188                            filter_text: Some(snippet.body.clone()),
17189                            sort_text: Some(char::MAX.to_string()),
17190                            ..lsp::CompletionItem::default()
17191                        }),
17192                        lsp_defaults: None,
17193                    },
17194                    label: CodeLabel {
17195                        text: matching_prefix.clone(),
17196                        runs: Vec::new(),
17197                        filter_range: 0..matching_prefix.len(),
17198                    },
17199                    documentation: snippet
17200                        .description
17201                        .clone()
17202                        .map(|description| CompletionDocumentation::SingleLine(description.into())),
17203                    confirm: None,
17204                })
17205            })
17206            .collect();
17207
17208        Ok(result)
17209    })
17210}
17211
17212impl CompletionProvider for Entity<Project> {
17213    fn completions(
17214        &self,
17215        buffer: &Entity<Buffer>,
17216        buffer_position: text::Anchor,
17217        options: CompletionContext,
17218        _window: &mut Window,
17219        cx: &mut Context<Editor>,
17220    ) -> Task<Result<Option<Vec<Completion>>>> {
17221        self.update(cx, |project, cx| {
17222            let snippets = snippet_completions(project, buffer, buffer_position, cx);
17223            let project_completions = project.completions(buffer, buffer_position, options, cx);
17224            cx.background_spawn(async move {
17225                let snippets_completions = snippets.await?;
17226                match project_completions.await? {
17227                    Some(mut completions) => {
17228                        completions.extend(snippets_completions);
17229                        Ok(Some(completions))
17230                    }
17231                    None => {
17232                        if snippets_completions.is_empty() {
17233                            Ok(None)
17234                        } else {
17235                            Ok(Some(snippets_completions))
17236                        }
17237                    }
17238                }
17239            })
17240        })
17241    }
17242
17243    fn resolve_completions(
17244        &self,
17245        buffer: Entity<Buffer>,
17246        completion_indices: Vec<usize>,
17247        completions: Rc<RefCell<Box<[Completion]>>>,
17248        cx: &mut Context<Editor>,
17249    ) -> Task<Result<bool>> {
17250        self.update(cx, |project, cx| {
17251            project.lsp_store().update(cx, |lsp_store, cx| {
17252                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
17253            })
17254        })
17255    }
17256
17257    fn apply_additional_edits_for_completion(
17258        &self,
17259        buffer: Entity<Buffer>,
17260        completions: Rc<RefCell<Box<[Completion]>>>,
17261        completion_index: usize,
17262        push_to_history: bool,
17263        cx: &mut Context<Editor>,
17264    ) -> Task<Result<Option<language::Transaction>>> {
17265        self.update(cx, |project, cx| {
17266            project.lsp_store().update(cx, |lsp_store, cx| {
17267                lsp_store.apply_additional_edits_for_completion(
17268                    buffer,
17269                    completions,
17270                    completion_index,
17271                    push_to_history,
17272                    cx,
17273                )
17274            })
17275        })
17276    }
17277
17278    fn is_completion_trigger(
17279        &self,
17280        buffer: &Entity<Buffer>,
17281        position: language::Anchor,
17282        text: &str,
17283        trigger_in_words: bool,
17284        cx: &mut Context<Editor>,
17285    ) -> bool {
17286        let mut chars = text.chars();
17287        let char = if let Some(char) = chars.next() {
17288            char
17289        } else {
17290            return false;
17291        };
17292        if chars.next().is_some() {
17293            return false;
17294        }
17295
17296        let buffer = buffer.read(cx);
17297        let snapshot = buffer.snapshot();
17298        if !snapshot.settings_at(position, cx).show_completions_on_input {
17299            return false;
17300        }
17301        let classifier = snapshot.char_classifier_at(position).for_completion(true);
17302        if trigger_in_words && classifier.is_word(char) {
17303            return true;
17304        }
17305
17306        buffer.completion_triggers().contains(text)
17307    }
17308}
17309
17310impl SemanticsProvider for Entity<Project> {
17311    fn hover(
17312        &self,
17313        buffer: &Entity<Buffer>,
17314        position: text::Anchor,
17315        cx: &mut App,
17316    ) -> Option<Task<Vec<project::Hover>>> {
17317        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
17318    }
17319
17320    fn document_highlights(
17321        &self,
17322        buffer: &Entity<Buffer>,
17323        position: text::Anchor,
17324        cx: &mut App,
17325    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
17326        Some(self.update(cx, |project, cx| {
17327            project.document_highlights(buffer, position, cx)
17328        }))
17329    }
17330
17331    fn definitions(
17332        &self,
17333        buffer: &Entity<Buffer>,
17334        position: text::Anchor,
17335        kind: GotoDefinitionKind,
17336        cx: &mut App,
17337    ) -> Option<Task<Result<Vec<LocationLink>>>> {
17338        Some(self.update(cx, |project, cx| match kind {
17339            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
17340            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
17341            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
17342            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
17343        }))
17344    }
17345
17346    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
17347        // TODO: make this work for remote projects
17348        self.update(cx, |this, cx| {
17349            buffer.update(cx, |buffer, cx| {
17350                this.any_language_server_supports_inlay_hints(buffer, cx)
17351            })
17352        })
17353    }
17354
17355    fn inlay_hints(
17356        &self,
17357        buffer_handle: Entity<Buffer>,
17358        range: Range<text::Anchor>,
17359        cx: &mut App,
17360    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
17361        Some(self.update(cx, |project, cx| {
17362            project.inlay_hints(buffer_handle, range, cx)
17363        }))
17364    }
17365
17366    fn resolve_inlay_hint(
17367        &self,
17368        hint: InlayHint,
17369        buffer_handle: Entity<Buffer>,
17370        server_id: LanguageServerId,
17371        cx: &mut App,
17372    ) -> Option<Task<anyhow::Result<InlayHint>>> {
17373        Some(self.update(cx, |project, cx| {
17374            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
17375        }))
17376    }
17377
17378    fn range_for_rename(
17379        &self,
17380        buffer: &Entity<Buffer>,
17381        position: text::Anchor,
17382        cx: &mut App,
17383    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
17384        Some(self.update(cx, |project, cx| {
17385            let buffer = buffer.clone();
17386            let task = project.prepare_rename(buffer.clone(), position, cx);
17387            cx.spawn(|_, mut cx| async move {
17388                Ok(match task.await? {
17389                    PrepareRenameResponse::Success(range) => Some(range),
17390                    PrepareRenameResponse::InvalidPosition => None,
17391                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
17392                        // Fallback on using TreeSitter info to determine identifier range
17393                        buffer.update(&mut cx, |buffer, _| {
17394                            let snapshot = buffer.snapshot();
17395                            let (range, kind) = snapshot.surrounding_word(position);
17396                            if kind != Some(CharKind::Word) {
17397                                return None;
17398                            }
17399                            Some(
17400                                snapshot.anchor_before(range.start)
17401                                    ..snapshot.anchor_after(range.end),
17402                            )
17403                        })?
17404                    }
17405                })
17406            })
17407        }))
17408    }
17409
17410    fn perform_rename(
17411        &self,
17412        buffer: &Entity<Buffer>,
17413        position: text::Anchor,
17414        new_name: String,
17415        cx: &mut App,
17416    ) -> Option<Task<Result<ProjectTransaction>>> {
17417        Some(self.update(cx, |project, cx| {
17418            project.perform_rename(buffer.clone(), position, new_name, cx)
17419        }))
17420    }
17421}
17422
17423fn inlay_hint_settings(
17424    location: Anchor,
17425    snapshot: &MultiBufferSnapshot,
17426    cx: &mut Context<Editor>,
17427) -> InlayHintSettings {
17428    let file = snapshot.file_at(location);
17429    let language = snapshot.language_at(location).map(|l| l.name());
17430    language_settings(language, file, cx).inlay_hints
17431}
17432
17433fn consume_contiguous_rows(
17434    contiguous_row_selections: &mut Vec<Selection<Point>>,
17435    selection: &Selection<Point>,
17436    display_map: &DisplaySnapshot,
17437    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
17438) -> (MultiBufferRow, MultiBufferRow) {
17439    contiguous_row_selections.push(selection.clone());
17440    let start_row = MultiBufferRow(selection.start.row);
17441    let mut end_row = ending_row(selection, display_map);
17442
17443    while let Some(next_selection) = selections.peek() {
17444        if next_selection.start.row <= end_row.0 {
17445            end_row = ending_row(next_selection, display_map);
17446            contiguous_row_selections.push(selections.next().unwrap().clone());
17447        } else {
17448            break;
17449        }
17450    }
17451    (start_row, end_row)
17452}
17453
17454fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
17455    if next_selection.end.column > 0 || next_selection.is_empty() {
17456        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
17457    } else {
17458        MultiBufferRow(next_selection.end.row)
17459    }
17460}
17461
17462impl EditorSnapshot {
17463    pub fn remote_selections_in_range<'a>(
17464        &'a self,
17465        range: &'a Range<Anchor>,
17466        collaboration_hub: &dyn CollaborationHub,
17467        cx: &'a App,
17468    ) -> impl 'a + Iterator<Item = RemoteSelection> {
17469        let participant_names = collaboration_hub.user_names(cx);
17470        let participant_indices = collaboration_hub.user_participant_indices(cx);
17471        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
17472        let collaborators_by_replica_id = collaborators_by_peer_id
17473            .iter()
17474            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
17475            .collect::<HashMap<_, _>>();
17476        self.buffer_snapshot
17477            .selections_in_range(range, false)
17478            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
17479                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
17480                let participant_index = participant_indices.get(&collaborator.user_id).copied();
17481                let user_name = participant_names.get(&collaborator.user_id).cloned();
17482                Some(RemoteSelection {
17483                    replica_id,
17484                    selection,
17485                    cursor_shape,
17486                    line_mode,
17487                    participant_index,
17488                    peer_id: collaborator.peer_id,
17489                    user_name,
17490                })
17491            })
17492    }
17493
17494    pub fn hunks_for_ranges(
17495        &self,
17496        ranges: impl IntoIterator<Item = Range<Point>>,
17497    ) -> Vec<MultiBufferDiffHunk> {
17498        let mut hunks = Vec::new();
17499        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
17500            HashMap::default();
17501        for query_range in ranges {
17502            let query_rows =
17503                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
17504            for hunk in self.buffer_snapshot.diff_hunks_in_range(
17505                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
17506            ) {
17507                // Include deleted hunks that are adjacent to the query range, because
17508                // otherwise they would be missed.
17509                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
17510                if hunk.status().is_deleted() {
17511                    intersects_range |= hunk.row_range.start == query_rows.end;
17512                    intersects_range |= hunk.row_range.end == query_rows.start;
17513                }
17514                if intersects_range {
17515                    if !processed_buffer_rows
17516                        .entry(hunk.buffer_id)
17517                        .or_default()
17518                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
17519                    {
17520                        continue;
17521                    }
17522                    hunks.push(hunk);
17523                }
17524            }
17525        }
17526
17527        hunks
17528    }
17529
17530    fn display_diff_hunks_for_rows<'a>(
17531        &'a self,
17532        display_rows: Range<DisplayRow>,
17533        folded_buffers: &'a HashSet<BufferId>,
17534    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
17535        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
17536        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
17537
17538        self.buffer_snapshot
17539            .diff_hunks_in_range(buffer_start..buffer_end)
17540            .filter_map(|hunk| {
17541                if folded_buffers.contains(&hunk.buffer_id) {
17542                    return None;
17543                }
17544
17545                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
17546                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
17547
17548                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
17549                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
17550
17551                let display_hunk = if hunk_display_start.column() != 0 {
17552                    DisplayDiffHunk::Folded {
17553                        display_row: hunk_display_start.row(),
17554                    }
17555                } else {
17556                    let mut end_row = hunk_display_end.row();
17557                    if hunk_display_end.column() > 0 {
17558                        end_row.0 += 1;
17559                    }
17560                    let is_created_file = hunk.is_created_file();
17561                    DisplayDiffHunk::Unfolded {
17562                        status: hunk.status(),
17563                        diff_base_byte_range: hunk.diff_base_byte_range,
17564                        display_row_range: hunk_display_start.row()..end_row,
17565                        multi_buffer_range: Anchor::range_in_buffer(
17566                            hunk.excerpt_id,
17567                            hunk.buffer_id,
17568                            hunk.buffer_range,
17569                        ),
17570                        is_created_file,
17571                    }
17572                };
17573
17574                Some(display_hunk)
17575            })
17576    }
17577
17578    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
17579        self.display_snapshot.buffer_snapshot.language_at(position)
17580    }
17581
17582    pub fn is_focused(&self) -> bool {
17583        self.is_focused
17584    }
17585
17586    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
17587        self.placeholder_text.as_ref()
17588    }
17589
17590    pub fn scroll_position(&self) -> gpui::Point<f32> {
17591        self.scroll_anchor.scroll_position(&self.display_snapshot)
17592    }
17593
17594    fn gutter_dimensions(
17595        &self,
17596        font_id: FontId,
17597        font_size: Pixels,
17598        max_line_number_width: Pixels,
17599        cx: &App,
17600    ) -> Option<GutterDimensions> {
17601        if !self.show_gutter {
17602            return None;
17603        }
17604
17605        let descent = cx.text_system().descent(font_id, font_size);
17606        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
17607        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
17608
17609        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
17610            matches!(
17611                ProjectSettings::get_global(cx).git.git_gutter,
17612                Some(GitGutterSetting::TrackedFiles)
17613            )
17614        });
17615        let gutter_settings = EditorSettings::get_global(cx).gutter;
17616        let show_line_numbers = self
17617            .show_line_numbers
17618            .unwrap_or(gutter_settings.line_numbers);
17619        let line_gutter_width = if show_line_numbers {
17620            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
17621            let min_width_for_number_on_gutter = em_advance * 4.0;
17622            max_line_number_width.max(min_width_for_number_on_gutter)
17623        } else {
17624            0.0.into()
17625        };
17626
17627        let show_code_actions = self
17628            .show_code_actions
17629            .unwrap_or(gutter_settings.code_actions);
17630
17631        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
17632
17633        let git_blame_entries_width =
17634            self.git_blame_gutter_max_author_length
17635                .map(|max_author_length| {
17636                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
17637
17638                    /// The number of characters to dedicate to gaps and margins.
17639                    const SPACING_WIDTH: usize = 4;
17640
17641                    let max_char_count = max_author_length
17642                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
17643                        + ::git::SHORT_SHA_LENGTH
17644                        + MAX_RELATIVE_TIMESTAMP.len()
17645                        + SPACING_WIDTH;
17646
17647                    em_advance * max_char_count
17648                });
17649
17650        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
17651        left_padding += if show_code_actions || show_runnables {
17652            em_width * 3.0
17653        } else if show_git_gutter && show_line_numbers {
17654            em_width * 2.0
17655        } else if show_git_gutter || show_line_numbers {
17656            em_width
17657        } else {
17658            px(0.)
17659        };
17660
17661        let right_padding = if gutter_settings.folds && show_line_numbers {
17662            em_width * 4.0
17663        } else if gutter_settings.folds {
17664            em_width * 3.0
17665        } else if show_line_numbers {
17666            em_width
17667        } else {
17668            px(0.)
17669        };
17670
17671        Some(GutterDimensions {
17672            left_padding,
17673            right_padding,
17674            width: line_gutter_width + left_padding + right_padding,
17675            margin: -descent,
17676            git_blame_entries_width,
17677        })
17678    }
17679
17680    pub fn render_crease_toggle(
17681        &self,
17682        buffer_row: MultiBufferRow,
17683        row_contains_cursor: bool,
17684        editor: Entity<Editor>,
17685        window: &mut Window,
17686        cx: &mut App,
17687    ) -> Option<AnyElement> {
17688        let folded = self.is_line_folded(buffer_row);
17689        let mut is_foldable = false;
17690
17691        if let Some(crease) = self
17692            .crease_snapshot
17693            .query_row(buffer_row, &self.buffer_snapshot)
17694        {
17695            is_foldable = true;
17696            match crease {
17697                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
17698                    if let Some(render_toggle) = render_toggle {
17699                        let toggle_callback =
17700                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
17701                                if folded {
17702                                    editor.update(cx, |editor, cx| {
17703                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
17704                                    });
17705                                } else {
17706                                    editor.update(cx, |editor, cx| {
17707                                        editor.unfold_at(
17708                                            &crate::UnfoldAt { buffer_row },
17709                                            window,
17710                                            cx,
17711                                        )
17712                                    });
17713                                }
17714                            });
17715                        return Some((render_toggle)(
17716                            buffer_row,
17717                            folded,
17718                            toggle_callback,
17719                            window,
17720                            cx,
17721                        ));
17722                    }
17723                }
17724            }
17725        }
17726
17727        is_foldable |= self.starts_indent(buffer_row);
17728
17729        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
17730            Some(
17731                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
17732                    .toggle_state(folded)
17733                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
17734                        if folded {
17735                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
17736                        } else {
17737                            this.fold_at(&FoldAt { buffer_row }, window, cx);
17738                        }
17739                    }))
17740                    .into_any_element(),
17741            )
17742        } else {
17743            None
17744        }
17745    }
17746
17747    pub fn render_crease_trailer(
17748        &self,
17749        buffer_row: MultiBufferRow,
17750        window: &mut Window,
17751        cx: &mut App,
17752    ) -> Option<AnyElement> {
17753        let folded = self.is_line_folded(buffer_row);
17754        if let Crease::Inline { render_trailer, .. } = self
17755            .crease_snapshot
17756            .query_row(buffer_row, &self.buffer_snapshot)?
17757        {
17758            let render_trailer = render_trailer.as_ref()?;
17759            Some(render_trailer(buffer_row, folded, window, cx))
17760        } else {
17761            None
17762        }
17763    }
17764}
17765
17766impl Deref for EditorSnapshot {
17767    type Target = DisplaySnapshot;
17768
17769    fn deref(&self) -> &Self::Target {
17770        &self.display_snapshot
17771    }
17772}
17773
17774#[derive(Clone, Debug, PartialEq, Eq)]
17775pub enum EditorEvent {
17776    InputIgnored {
17777        text: Arc<str>,
17778    },
17779    InputHandled {
17780        utf16_range_to_replace: Option<Range<isize>>,
17781        text: Arc<str>,
17782    },
17783    ExcerptsAdded {
17784        buffer: Entity<Buffer>,
17785        predecessor: ExcerptId,
17786        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
17787    },
17788    ExcerptsRemoved {
17789        ids: Vec<ExcerptId>,
17790    },
17791    BufferFoldToggled {
17792        ids: Vec<ExcerptId>,
17793        folded: bool,
17794    },
17795    ExcerptsEdited {
17796        ids: Vec<ExcerptId>,
17797    },
17798    ExcerptsExpanded {
17799        ids: Vec<ExcerptId>,
17800    },
17801    BufferEdited,
17802    Edited {
17803        transaction_id: clock::Lamport,
17804    },
17805    Reparsed(BufferId),
17806    Focused,
17807    FocusedIn,
17808    Blurred,
17809    DirtyChanged,
17810    Saved,
17811    TitleChanged,
17812    DiffBaseChanged,
17813    SelectionsChanged {
17814        local: bool,
17815    },
17816    ScrollPositionChanged {
17817        local: bool,
17818        autoscroll: bool,
17819    },
17820    Closed,
17821    TransactionUndone {
17822        transaction_id: clock::Lamport,
17823    },
17824    TransactionBegun {
17825        transaction_id: clock::Lamport,
17826    },
17827    Reloaded,
17828    CursorShapeChanged,
17829}
17830
17831impl EventEmitter<EditorEvent> for Editor {}
17832
17833impl Focusable for Editor {
17834    fn focus_handle(&self, _cx: &App) -> FocusHandle {
17835        self.focus_handle.clone()
17836    }
17837}
17838
17839impl Render for Editor {
17840    fn render(&mut self, _: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
17841        let settings = ThemeSettings::get_global(cx);
17842
17843        let mut text_style = match self.mode {
17844            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
17845                color: cx.theme().colors().editor_foreground,
17846                font_family: settings.ui_font.family.clone(),
17847                font_features: settings.ui_font.features.clone(),
17848                font_fallbacks: settings.ui_font.fallbacks.clone(),
17849                font_size: rems(0.875).into(),
17850                font_weight: settings.ui_font.weight,
17851                line_height: relative(settings.buffer_line_height.value()),
17852                ..Default::default()
17853            },
17854            EditorMode::Full => TextStyle {
17855                color: cx.theme().colors().editor_foreground,
17856                font_family: settings.buffer_font.family.clone(),
17857                font_features: settings.buffer_font.features.clone(),
17858                font_fallbacks: settings.buffer_font.fallbacks.clone(),
17859                font_size: settings.buffer_font_size(cx).into(),
17860                font_weight: settings.buffer_font.weight,
17861                line_height: relative(settings.buffer_line_height.value()),
17862                ..Default::default()
17863            },
17864        };
17865        if let Some(text_style_refinement) = &self.text_style_refinement {
17866            text_style.refine(text_style_refinement)
17867        }
17868
17869        let background = match self.mode {
17870            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
17871            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
17872            EditorMode::Full => cx.theme().colors().editor_background,
17873        };
17874
17875        EditorElement::new(
17876            &cx.entity(),
17877            EditorStyle {
17878                background,
17879                local_player: cx.theme().players().local(),
17880                text: text_style,
17881                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
17882                syntax: cx.theme().syntax().clone(),
17883                status: cx.theme().status().clone(),
17884                inlay_hints_style: make_inlay_hints_style(cx),
17885                inline_completion_styles: make_suggestion_styles(cx),
17886                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
17887            },
17888        )
17889    }
17890}
17891
17892impl EntityInputHandler for Editor {
17893    fn text_for_range(
17894        &mut self,
17895        range_utf16: Range<usize>,
17896        adjusted_range: &mut Option<Range<usize>>,
17897        _: &mut Window,
17898        cx: &mut Context<Self>,
17899    ) -> Option<String> {
17900        let snapshot = self.buffer.read(cx).read(cx);
17901        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
17902        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
17903        if (start.0..end.0) != range_utf16 {
17904            adjusted_range.replace(start.0..end.0);
17905        }
17906        Some(snapshot.text_for_range(start..end).collect())
17907    }
17908
17909    fn selected_text_range(
17910        &mut self,
17911        ignore_disabled_input: bool,
17912        _: &mut Window,
17913        cx: &mut Context<Self>,
17914    ) -> Option<UTF16Selection> {
17915        // Prevent the IME menu from appearing when holding down an alphabetic key
17916        // while input is disabled.
17917        if !ignore_disabled_input && !self.input_enabled {
17918            return None;
17919        }
17920
17921        let selection = self.selections.newest::<OffsetUtf16>(cx);
17922        let range = selection.range();
17923
17924        Some(UTF16Selection {
17925            range: range.start.0..range.end.0,
17926            reversed: selection.reversed,
17927        })
17928    }
17929
17930    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
17931        let snapshot = self.buffer.read(cx).read(cx);
17932        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
17933        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
17934    }
17935
17936    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17937        self.clear_highlights::<InputComposition>(cx);
17938        self.ime_transaction.take();
17939    }
17940
17941    fn replace_text_in_range(
17942        &mut self,
17943        range_utf16: Option<Range<usize>>,
17944        text: &str,
17945        window: &mut Window,
17946        cx: &mut Context<Self>,
17947    ) {
17948        if !self.input_enabled {
17949            cx.emit(EditorEvent::InputIgnored { text: text.into() });
17950            return;
17951        }
17952
17953        self.transact(window, cx, |this, window, cx| {
17954            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
17955                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17956                Some(this.selection_replacement_ranges(range_utf16, cx))
17957            } else {
17958                this.marked_text_ranges(cx)
17959            };
17960
17961            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
17962                let newest_selection_id = this.selections.newest_anchor().id;
17963                this.selections
17964                    .all::<OffsetUtf16>(cx)
17965                    .iter()
17966                    .zip(ranges_to_replace.iter())
17967                    .find_map(|(selection, range)| {
17968                        if selection.id == newest_selection_id {
17969                            Some(
17970                                (range.start.0 as isize - selection.head().0 as isize)
17971                                    ..(range.end.0 as isize - selection.head().0 as isize),
17972                            )
17973                        } else {
17974                            None
17975                        }
17976                    })
17977            });
17978
17979            cx.emit(EditorEvent::InputHandled {
17980                utf16_range_to_replace: range_to_replace,
17981                text: text.into(),
17982            });
17983
17984            if let Some(new_selected_ranges) = new_selected_ranges {
17985                this.change_selections(None, window, cx, |selections| {
17986                    selections.select_ranges(new_selected_ranges)
17987                });
17988                this.backspace(&Default::default(), window, cx);
17989            }
17990
17991            this.handle_input(text, window, cx);
17992        });
17993
17994        if let Some(transaction) = self.ime_transaction {
17995            self.buffer.update(cx, |buffer, cx| {
17996                buffer.group_until_transaction(transaction, cx);
17997            });
17998        }
17999
18000        self.unmark_text(window, cx);
18001    }
18002
18003    fn replace_and_mark_text_in_range(
18004        &mut self,
18005        range_utf16: Option<Range<usize>>,
18006        text: &str,
18007        new_selected_range_utf16: Option<Range<usize>>,
18008        window: &mut Window,
18009        cx: &mut Context<Self>,
18010    ) {
18011        if !self.input_enabled {
18012            return;
18013        }
18014
18015        let transaction = self.transact(window, cx, |this, window, cx| {
18016            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
18017                let snapshot = this.buffer.read(cx).read(cx);
18018                if let Some(relative_range_utf16) = range_utf16.as_ref() {
18019                    for marked_range in &mut marked_ranges {
18020                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
18021                        marked_range.start.0 += relative_range_utf16.start;
18022                        marked_range.start =
18023                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
18024                        marked_range.end =
18025                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
18026                    }
18027                }
18028                Some(marked_ranges)
18029            } else if let Some(range_utf16) = range_utf16 {
18030                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
18031                Some(this.selection_replacement_ranges(range_utf16, cx))
18032            } else {
18033                None
18034            };
18035
18036            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
18037                let newest_selection_id = this.selections.newest_anchor().id;
18038                this.selections
18039                    .all::<OffsetUtf16>(cx)
18040                    .iter()
18041                    .zip(ranges_to_replace.iter())
18042                    .find_map(|(selection, range)| {
18043                        if selection.id == newest_selection_id {
18044                            Some(
18045                                (range.start.0 as isize - selection.head().0 as isize)
18046                                    ..(range.end.0 as isize - selection.head().0 as isize),
18047                            )
18048                        } else {
18049                            None
18050                        }
18051                    })
18052            });
18053
18054            cx.emit(EditorEvent::InputHandled {
18055                utf16_range_to_replace: range_to_replace,
18056                text: text.into(),
18057            });
18058
18059            if let Some(ranges) = ranges_to_replace {
18060                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
18061            }
18062
18063            let marked_ranges = {
18064                let snapshot = this.buffer.read(cx).read(cx);
18065                this.selections
18066                    .disjoint_anchors()
18067                    .iter()
18068                    .map(|selection| {
18069                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
18070                    })
18071                    .collect::<Vec<_>>()
18072            };
18073
18074            if text.is_empty() {
18075                this.unmark_text(window, cx);
18076            } else {
18077                this.highlight_text::<InputComposition>(
18078                    marked_ranges.clone(),
18079                    HighlightStyle {
18080                        underline: Some(UnderlineStyle {
18081                            thickness: px(1.),
18082                            color: None,
18083                            wavy: false,
18084                        }),
18085                        ..Default::default()
18086                    },
18087                    cx,
18088                );
18089            }
18090
18091            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
18092            let use_autoclose = this.use_autoclose;
18093            let use_auto_surround = this.use_auto_surround;
18094            this.set_use_autoclose(false);
18095            this.set_use_auto_surround(false);
18096            this.handle_input(text, window, cx);
18097            this.set_use_autoclose(use_autoclose);
18098            this.set_use_auto_surround(use_auto_surround);
18099
18100            if let Some(new_selected_range) = new_selected_range_utf16 {
18101                let snapshot = this.buffer.read(cx).read(cx);
18102                let new_selected_ranges = marked_ranges
18103                    .into_iter()
18104                    .map(|marked_range| {
18105                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
18106                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
18107                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
18108                        snapshot.clip_offset_utf16(new_start, Bias::Left)
18109                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
18110                    })
18111                    .collect::<Vec<_>>();
18112
18113                drop(snapshot);
18114                this.change_selections(None, window, cx, |selections| {
18115                    selections.select_ranges(new_selected_ranges)
18116                });
18117            }
18118        });
18119
18120        self.ime_transaction = self.ime_transaction.or(transaction);
18121        if let Some(transaction) = self.ime_transaction {
18122            self.buffer.update(cx, |buffer, cx| {
18123                buffer.group_until_transaction(transaction, cx);
18124            });
18125        }
18126
18127        if self.text_highlights::<InputComposition>(cx).is_none() {
18128            self.ime_transaction.take();
18129        }
18130    }
18131
18132    fn bounds_for_range(
18133        &mut self,
18134        range_utf16: Range<usize>,
18135        element_bounds: gpui::Bounds<Pixels>,
18136        window: &mut Window,
18137        cx: &mut Context<Self>,
18138    ) -> Option<gpui::Bounds<Pixels>> {
18139        let text_layout_details = self.text_layout_details(window);
18140        let gpui::Size {
18141            width: em_width,
18142            height: line_height,
18143        } = self.character_size(window);
18144
18145        let snapshot = self.snapshot(window, cx);
18146        let scroll_position = snapshot.scroll_position();
18147        let scroll_left = scroll_position.x * em_width;
18148
18149        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
18150        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
18151            + self.gutter_dimensions.width
18152            + self.gutter_dimensions.margin;
18153        let y = line_height * (start.row().as_f32() - scroll_position.y);
18154
18155        Some(Bounds {
18156            origin: element_bounds.origin + point(x, y),
18157            size: size(em_width, line_height),
18158        })
18159    }
18160
18161    fn character_index_for_point(
18162        &mut self,
18163        point: gpui::Point<Pixels>,
18164        _window: &mut Window,
18165        _cx: &mut Context<Self>,
18166    ) -> Option<usize> {
18167        let position_map = self.last_position_map.as_ref()?;
18168        if !position_map.text_hitbox.contains(&point) {
18169            return None;
18170        }
18171        let display_point = position_map.point_for_position(point).previous_valid;
18172        let anchor = position_map
18173            .snapshot
18174            .display_point_to_anchor(display_point, Bias::Left);
18175        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
18176        Some(utf16_offset.0)
18177    }
18178}
18179
18180trait SelectionExt {
18181    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
18182    fn spanned_rows(
18183        &self,
18184        include_end_if_at_line_start: bool,
18185        map: &DisplaySnapshot,
18186    ) -> Range<MultiBufferRow>;
18187}
18188
18189impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
18190    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
18191        let start = self
18192            .start
18193            .to_point(&map.buffer_snapshot)
18194            .to_display_point(map);
18195        let end = self
18196            .end
18197            .to_point(&map.buffer_snapshot)
18198            .to_display_point(map);
18199        if self.reversed {
18200            end..start
18201        } else {
18202            start..end
18203        }
18204    }
18205
18206    fn spanned_rows(
18207        &self,
18208        include_end_if_at_line_start: bool,
18209        map: &DisplaySnapshot,
18210    ) -> Range<MultiBufferRow> {
18211        let start = self.start.to_point(&map.buffer_snapshot);
18212        let mut end = self.end.to_point(&map.buffer_snapshot);
18213        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
18214            end.row -= 1;
18215        }
18216
18217        let buffer_start = map.prev_line_boundary(start).0;
18218        let buffer_end = map.next_line_boundary(end).0;
18219        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
18220    }
18221}
18222
18223impl<T: InvalidationRegion> InvalidationStack<T> {
18224    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
18225    where
18226        S: Clone + ToOffset,
18227    {
18228        while let Some(region) = self.last() {
18229            let all_selections_inside_invalidation_ranges =
18230                if selections.len() == region.ranges().len() {
18231                    selections
18232                        .iter()
18233                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
18234                        .all(|(selection, invalidation_range)| {
18235                            let head = selection.head().to_offset(buffer);
18236                            invalidation_range.start <= head && invalidation_range.end >= head
18237                        })
18238                } else {
18239                    false
18240                };
18241
18242            if all_selections_inside_invalidation_ranges {
18243                break;
18244            } else {
18245                self.pop();
18246            }
18247        }
18248    }
18249}
18250
18251impl<T> Default for InvalidationStack<T> {
18252    fn default() -> Self {
18253        Self(Default::default())
18254    }
18255}
18256
18257impl<T> Deref for InvalidationStack<T> {
18258    type Target = Vec<T>;
18259
18260    fn deref(&self) -> &Self::Target {
18261        &self.0
18262    }
18263}
18264
18265impl<T> DerefMut for InvalidationStack<T> {
18266    fn deref_mut(&mut self) -> &mut Self::Target {
18267        &mut self.0
18268    }
18269}
18270
18271impl InvalidationRegion for SnippetState {
18272    fn ranges(&self) -> &[Range<Anchor>] {
18273        &self.ranges[self.active_index]
18274    }
18275}
18276
18277pub fn diagnostic_block_renderer(
18278    diagnostic: Diagnostic,
18279    max_message_rows: Option<u8>,
18280    allow_closing: bool,
18281) -> RenderBlock {
18282    let (text_without_backticks, code_ranges) =
18283        highlight_diagnostic_message(&diagnostic, max_message_rows);
18284
18285    Arc::new(move |cx: &mut BlockContext| {
18286        let group_id: SharedString = cx.block_id.to_string().into();
18287
18288        let mut text_style = cx.window.text_style().clone();
18289        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
18290        let theme_settings = ThemeSettings::get_global(cx);
18291        text_style.font_family = theme_settings.buffer_font.family.clone();
18292        text_style.font_style = theme_settings.buffer_font.style;
18293        text_style.font_features = theme_settings.buffer_font.features.clone();
18294        text_style.font_weight = theme_settings.buffer_font.weight;
18295
18296        let multi_line_diagnostic = diagnostic.message.contains('\n');
18297
18298        let buttons = |diagnostic: &Diagnostic| {
18299            if multi_line_diagnostic {
18300                v_flex()
18301            } else {
18302                h_flex()
18303            }
18304            .when(allow_closing, |div| {
18305                div.children(diagnostic.is_primary.then(|| {
18306                    IconButton::new("close-block", IconName::XCircle)
18307                        .icon_color(Color::Muted)
18308                        .size(ButtonSize::Compact)
18309                        .style(ButtonStyle::Transparent)
18310                        .visible_on_hover(group_id.clone())
18311                        .on_click(move |_click, window, cx| {
18312                            window.dispatch_action(Box::new(Cancel), cx)
18313                        })
18314                        .tooltip(|window, cx| {
18315                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
18316                        })
18317                }))
18318            })
18319            .child(
18320                IconButton::new("copy-block", IconName::Copy)
18321                    .icon_color(Color::Muted)
18322                    .size(ButtonSize::Compact)
18323                    .style(ButtonStyle::Transparent)
18324                    .visible_on_hover(group_id.clone())
18325                    .on_click({
18326                        let message = diagnostic.message.clone();
18327                        move |_click, _, cx| {
18328                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
18329                        }
18330                    })
18331                    .tooltip(Tooltip::text("Copy diagnostic message")),
18332            )
18333        };
18334
18335        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
18336            AvailableSpace::min_size(),
18337            cx.window,
18338            cx.app,
18339        );
18340
18341        h_flex()
18342            .id(cx.block_id)
18343            .group(group_id.clone())
18344            .relative()
18345            .size_full()
18346            .block_mouse_down()
18347            .pl(cx.gutter_dimensions.width)
18348            .w(cx.max_width - cx.gutter_dimensions.full_width())
18349            .child(
18350                div()
18351                    .flex()
18352                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
18353                    .flex_shrink(),
18354            )
18355            .child(buttons(&diagnostic))
18356            .child(div().flex().flex_shrink_0().child(
18357                StyledText::new(text_without_backticks.clone()).with_default_highlights(
18358                    &text_style,
18359                    code_ranges.iter().map(|range| {
18360                        (
18361                            range.clone(),
18362                            HighlightStyle {
18363                                font_weight: Some(FontWeight::BOLD),
18364                                ..Default::default()
18365                            },
18366                        )
18367                    }),
18368                ),
18369            ))
18370            .into_any_element()
18371    })
18372}
18373
18374fn inline_completion_edit_text(
18375    current_snapshot: &BufferSnapshot,
18376    edits: &[(Range<Anchor>, String)],
18377    edit_preview: &EditPreview,
18378    include_deletions: bool,
18379    cx: &App,
18380) -> HighlightedText {
18381    let edits = edits
18382        .iter()
18383        .map(|(anchor, text)| {
18384            (
18385                anchor.start.text_anchor..anchor.end.text_anchor,
18386                text.clone(),
18387            )
18388        })
18389        .collect::<Vec<_>>();
18390
18391    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
18392}
18393
18394pub fn highlight_diagnostic_message(
18395    diagnostic: &Diagnostic,
18396    mut max_message_rows: Option<u8>,
18397) -> (SharedString, Vec<Range<usize>>) {
18398    let mut text_without_backticks = String::new();
18399    let mut code_ranges = Vec::new();
18400
18401    if let Some(source) = &diagnostic.source {
18402        text_without_backticks.push_str(source);
18403        code_ranges.push(0..source.len());
18404        text_without_backticks.push_str(": ");
18405    }
18406
18407    let mut prev_offset = 0;
18408    let mut in_code_block = false;
18409    let has_row_limit = max_message_rows.is_some();
18410    let mut newline_indices = diagnostic
18411        .message
18412        .match_indices('\n')
18413        .filter(|_| has_row_limit)
18414        .map(|(ix, _)| ix)
18415        .fuse()
18416        .peekable();
18417
18418    for (quote_ix, _) in diagnostic
18419        .message
18420        .match_indices('`')
18421        .chain([(diagnostic.message.len(), "")])
18422    {
18423        let mut first_newline_ix = None;
18424        let mut last_newline_ix = None;
18425        while let Some(newline_ix) = newline_indices.peek() {
18426            if *newline_ix < quote_ix {
18427                if first_newline_ix.is_none() {
18428                    first_newline_ix = Some(*newline_ix);
18429                }
18430                last_newline_ix = Some(*newline_ix);
18431
18432                if let Some(rows_left) = &mut max_message_rows {
18433                    if *rows_left == 0 {
18434                        break;
18435                    } else {
18436                        *rows_left -= 1;
18437                    }
18438                }
18439                let _ = newline_indices.next();
18440            } else {
18441                break;
18442            }
18443        }
18444        let prev_len = text_without_backticks.len();
18445        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
18446        text_without_backticks.push_str(new_text);
18447        if in_code_block {
18448            code_ranges.push(prev_len..text_without_backticks.len());
18449        }
18450        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
18451        in_code_block = !in_code_block;
18452        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
18453            text_without_backticks.push_str("...");
18454            break;
18455        }
18456    }
18457
18458    (text_without_backticks.into(), code_ranges)
18459}
18460
18461fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
18462    match severity {
18463        DiagnosticSeverity::ERROR => colors.error,
18464        DiagnosticSeverity::WARNING => colors.warning,
18465        DiagnosticSeverity::INFORMATION => colors.info,
18466        DiagnosticSeverity::HINT => colors.info,
18467        _ => colors.ignored,
18468    }
18469}
18470
18471pub fn styled_runs_for_code_label<'a>(
18472    label: &'a CodeLabel,
18473    syntax_theme: &'a theme::SyntaxTheme,
18474) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
18475    let fade_out = HighlightStyle {
18476        fade_out: Some(0.35),
18477        ..Default::default()
18478    };
18479
18480    let mut prev_end = label.filter_range.end;
18481    label
18482        .runs
18483        .iter()
18484        .enumerate()
18485        .flat_map(move |(ix, (range, highlight_id))| {
18486            let style = if let Some(style) = highlight_id.style(syntax_theme) {
18487                style
18488            } else {
18489                return Default::default();
18490            };
18491            let mut muted_style = style;
18492            muted_style.highlight(fade_out);
18493
18494            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
18495            if range.start >= label.filter_range.end {
18496                if range.start > prev_end {
18497                    runs.push((prev_end..range.start, fade_out));
18498                }
18499                runs.push((range.clone(), muted_style));
18500            } else if range.end <= label.filter_range.end {
18501                runs.push((range.clone(), style));
18502            } else {
18503                runs.push((range.start..label.filter_range.end, style));
18504                runs.push((label.filter_range.end..range.end, muted_style));
18505            }
18506            prev_end = cmp::max(prev_end, range.end);
18507
18508            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
18509                runs.push((prev_end..label.text.len(), fade_out));
18510            }
18511
18512            runs
18513        })
18514}
18515
18516pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
18517    let mut prev_index = 0;
18518    let mut prev_codepoint: Option<char> = None;
18519    text.char_indices()
18520        .chain([(text.len(), '\0')])
18521        .filter_map(move |(index, codepoint)| {
18522            let prev_codepoint = prev_codepoint.replace(codepoint)?;
18523            let is_boundary = index == text.len()
18524                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
18525                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
18526            if is_boundary {
18527                let chunk = &text[prev_index..index];
18528                prev_index = index;
18529                Some(chunk)
18530            } else {
18531                None
18532            }
18533        })
18534}
18535
18536pub trait RangeToAnchorExt: Sized {
18537    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
18538
18539    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
18540        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
18541        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
18542    }
18543}
18544
18545impl<T: ToOffset> RangeToAnchorExt for Range<T> {
18546    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
18547        let start_offset = self.start.to_offset(snapshot);
18548        let end_offset = self.end.to_offset(snapshot);
18549        if start_offset == end_offset {
18550            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
18551        } else {
18552            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
18553        }
18554    }
18555}
18556
18557pub trait RowExt {
18558    fn as_f32(&self) -> f32;
18559
18560    fn next_row(&self) -> Self;
18561
18562    fn previous_row(&self) -> Self;
18563
18564    fn minus(&self, other: Self) -> u32;
18565}
18566
18567impl RowExt for DisplayRow {
18568    fn as_f32(&self) -> f32 {
18569        self.0 as f32
18570    }
18571
18572    fn next_row(&self) -> Self {
18573        Self(self.0 + 1)
18574    }
18575
18576    fn previous_row(&self) -> Self {
18577        Self(self.0.saturating_sub(1))
18578    }
18579
18580    fn minus(&self, other: Self) -> u32 {
18581        self.0 - other.0
18582    }
18583}
18584
18585impl RowExt for MultiBufferRow {
18586    fn as_f32(&self) -> f32 {
18587        self.0 as f32
18588    }
18589
18590    fn next_row(&self) -> Self {
18591        Self(self.0 + 1)
18592    }
18593
18594    fn previous_row(&self) -> Self {
18595        Self(self.0.saturating_sub(1))
18596    }
18597
18598    fn minus(&self, other: Self) -> u32 {
18599        self.0 - other.0
18600    }
18601}
18602
18603trait RowRangeExt {
18604    type Row;
18605
18606    fn len(&self) -> usize;
18607
18608    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
18609}
18610
18611impl RowRangeExt for Range<MultiBufferRow> {
18612    type Row = MultiBufferRow;
18613
18614    fn len(&self) -> usize {
18615        (self.end.0 - self.start.0) as usize
18616    }
18617
18618    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
18619        (self.start.0..self.end.0).map(MultiBufferRow)
18620    }
18621}
18622
18623impl RowRangeExt for Range<DisplayRow> {
18624    type Row = DisplayRow;
18625
18626    fn len(&self) -> usize {
18627        (self.end.0 - self.start.0) as usize
18628    }
18629
18630    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
18631        (self.start.0..self.end.0).map(DisplayRow)
18632    }
18633}
18634
18635/// If select range has more than one line, we
18636/// just point the cursor to range.start.
18637fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
18638    if range.start.row == range.end.row {
18639        range
18640    } else {
18641        range.start..range.start
18642    }
18643}
18644pub struct KillRing(ClipboardItem);
18645impl Global for KillRing {}
18646
18647const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
18648
18649fn all_edits_insertions_or_deletions(
18650    edits: &Vec<(Range<Anchor>, String)>,
18651    snapshot: &MultiBufferSnapshot,
18652) -> bool {
18653    let mut all_insertions = true;
18654    let mut all_deletions = true;
18655
18656    for (range, new_text) in edits.iter() {
18657        let range_is_empty = range.to_offset(&snapshot).is_empty();
18658        let text_is_empty = new_text.is_empty();
18659
18660        if range_is_empty != text_is_empty {
18661            if range_is_empty {
18662                all_deletions = false;
18663            } else {
18664                all_insertions = false;
18665            }
18666        } else {
18667            return false;
18668        }
18669
18670        if !all_insertions && !all_deletions {
18671            return false;
18672        }
18673    }
18674    all_insertions || all_deletions
18675}
18676
18677struct MissingEditPredictionKeybindingTooltip;
18678
18679impl Render for MissingEditPredictionKeybindingTooltip {
18680    fn render(&mut self, window: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
18681        ui::tooltip_container(window, cx, |container, _, cx| {
18682            container
18683                .flex_shrink_0()
18684                .max_w_80()
18685                .min_h(rems_from_px(124.))
18686                .justify_between()
18687                .child(
18688                    v_flex()
18689                        .flex_1()
18690                        .text_ui_sm(cx)
18691                        .child(Label::new("Conflict with Accept Keybinding"))
18692                        .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
18693                )
18694                .child(
18695                    h_flex()
18696                        .pb_1()
18697                        .gap_1()
18698                        .items_end()
18699                        .w_full()
18700                        .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
18701                            window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
18702                        }))
18703                        .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
18704                            cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
18705                        })),
18706                )
18707        })
18708    }
18709}
18710
18711#[derive(Debug, Clone, Copy, PartialEq)]
18712pub struct LineHighlight {
18713    pub background: Background,
18714    pub border: Option<gpui::Hsla>,
18715}
18716
18717impl From<Hsla> for LineHighlight {
18718    fn from(hsla: Hsla) -> Self {
18719        Self {
18720            background: hsla.into(),
18721            border: None,
18722        }
18723    }
18724}
18725
18726impl From<Background> for LineHighlight {
18727    fn from(background: Background) -> Self {
18728        Self {
18729            background,
18730            border: None,
18731        }
18732    }
18733}