editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blink_manager;
   17mod clangd_ext;
   18mod code_context_menus;
   19pub mod display_map;
   20mod editor_settings;
   21mod editor_settings_controls;
   22mod element;
   23mod git;
   24mod highlight_matching_bracket;
   25mod hover_links;
   26mod hover_popover;
   27mod indent_guides;
   28mod inlay_hint_cache;
   29pub mod items;
   30mod jsx_tag_auto_close;
   31mod linked_editing_ranges;
   32mod lsp_ext;
   33mod mouse_context_menu;
   34pub mod movement;
   35mod persistence;
   36mod proposed_changes_editor;
   37mod rust_analyzer_ext;
   38pub mod scroll;
   39mod selections_collection;
   40pub mod tasks;
   41
   42#[cfg(test)]
   43mod editor_tests;
   44#[cfg(test)]
   45mod inline_completion_tests;
   46mod signature_help;
   47#[cfg(any(test, feature = "test-support"))]
   48pub mod test;
   49
   50pub(crate) use actions::*;
   51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   52use aho_corasick::AhoCorasick;
   53use anyhow::{Context as _, Result, anyhow};
   54use blink_manager::BlinkManager;
   55use buffer_diff::DiffHunkStatus;
   56use client::{Collaborator, ParticipantIndex};
   57use clock::ReplicaId;
   58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   59use convert_case::{Case, Casing};
   60use display_map::*;
   61pub use display_map::{ChunkRenderer, ChunkRendererContext, DisplayPoint, FoldPlaceholder};
   62use editor_settings::GoToDefinitionFallback;
   63pub use editor_settings::{
   64    CurrentLineHighlight, EditorSettings, HideMouseMode, ScrollBeyondLastLine, SearchSettings,
   65    ShowScrollbar,
   66};
   67pub use editor_settings_controls::*;
   68use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap, layout_line};
   69pub use element::{
   70    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   71};
   72use feature_flags::{Debugger, FeatureFlagAppExt};
   73use futures::{
   74    FutureExt,
   75    future::{self, Shared, join},
   76};
   77use fuzzy::StringMatchCandidate;
   78
   79use ::git::Restore;
   80use code_context_menus::{
   81    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   82    CompletionsMenu, ContextMenuOrigin,
   83};
   84use git::blame::{GitBlame, GlobalBlameRenderer};
   85use gpui::{
   86    Action, Animation, AnimationExt, AnyElement, AnyWeakEntity, App, AppContext,
   87    AsyncWindowContext, AvailableSpace, Background, Bounds, ClickEvent, ClipboardEntry,
   88    ClipboardItem, Context, DispatchPhase, Edges, Entity, EntityInputHandler, EventEmitter,
   89    FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global, HighlightStyle, Hsla,
   90    KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad, ParentElement, Pixels, Render,
   91    SharedString, Size, Stateful, Styled, StyledText, Subscription, Task, TextStyle,
   92    TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle, WeakEntity,
   93    WeakFocusHandle, Window, div, impl_actions, point, prelude::*, pulsating_between, px, relative,
   94    size,
   95};
   96use highlight_matching_bracket::refresh_matching_bracket_highlights;
   97use hover_links::{HoverLink, HoveredLinkState, InlayHighlight, find_file};
   98pub use hover_popover::hover_markdown_style;
   99use hover_popover::{HoverState, hide_hover};
  100use indent_guides::ActiveIndentGuidesState;
  101use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
  102pub use inline_completion::Direction;
  103use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
  104pub use items::MAX_TAB_TITLE_LEN;
  105use itertools::Itertools;
  106use language::{
  107    AutoindentMode, BracketMatch, BracketPair, Buffer, Capability, CharKind, CodeLabel,
  108    CursorShape, Diagnostic, DiffOptions, EditPredictionsMode, EditPreview, HighlightedText,
  109    IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
  110    TransactionId, TreeSitterOptions, WordsQuery,
  111    language_settings::{
  112        self, InlayHintSettings, LspInsertMode, RewrapBehavior, WordsCompletionMode,
  113        all_language_settings, language_settings,
  114    },
  115    point_from_lsp, text_diff_with_options,
  116};
  117use language::{BufferRow, CharClassifier, Runnable, RunnableRange, point_to_lsp};
  118use linked_editing_ranges::refresh_linked_ranges;
  119use mouse_context_menu::MouseContextMenu;
  120use persistence::DB;
  121use project::{
  122    ProjectPath,
  123    debugger::breakpoint_store::{
  124        BreakpointEditAction, BreakpointState, BreakpointStore, BreakpointStoreEvent,
  125    },
  126};
  127
  128pub use git::blame::BlameRenderer;
  129pub use proposed_changes_editor::{
  130    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  131};
  132use smallvec::smallvec;
  133use std::{cell::OnceCell, iter::Peekable};
  134use task::{ResolvedTask, RunnableTag, TaskTemplate, TaskVariables};
  135
  136pub use lsp::CompletionContext;
  137use lsp::{
  138    CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
  139    InsertTextFormat, InsertTextMode, LanguageServerId, LanguageServerName,
  140};
  141
  142use language::BufferSnapshot;
  143pub use lsp_ext::lsp_tasks;
  144use movement::TextLayoutDetails;
  145pub use multi_buffer::{
  146    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  147    ToOffset, ToPoint,
  148};
  149use multi_buffer::{
  150    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  151    MultiOrSingleBufferOffsetRange, PathKey, ToOffsetUtf16,
  152};
  153use parking_lot::Mutex;
  154use project::{
  155    CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
  156    Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
  157    TaskSourceKind,
  158    debugger::breakpoint_store::Breakpoint,
  159    lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  160    project_settings::{GitGutterSetting, ProjectSettings},
  161};
  162use rand::prelude::*;
  163use rpc::{ErrorExt, proto::*};
  164use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  165use selections_collection::{
  166    MutableSelectionsCollection, SelectionsCollection, resolve_selections,
  167};
  168use serde::{Deserialize, Serialize};
  169use settings::{Settings, SettingsLocation, SettingsStore, update_settings_file};
  170use smallvec::SmallVec;
  171use snippet::Snippet;
  172use std::sync::Arc;
  173use std::{
  174    any::TypeId,
  175    borrow::Cow,
  176    cell::RefCell,
  177    cmp::{self, Ordering, Reverse},
  178    mem,
  179    num::NonZeroU32,
  180    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  181    path::{Path, PathBuf},
  182    rc::Rc,
  183    time::{Duration, Instant},
  184};
  185pub use sum_tree::Bias;
  186use sum_tree::TreeMap;
  187use text::{BufferId, FromAnchor, OffsetUtf16, Rope};
  188use theme::{
  189    ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings,
  190    observe_buffer_font_size_adjustment,
  191};
  192use ui::{
  193    ButtonSize, ButtonStyle, ContextMenu, Disclosure, IconButton, IconButtonShape, IconName,
  194    IconSize, Key, Tooltip, h_flex, prelude::*,
  195};
  196use util::{RangeExt, ResultExt, TryFutureExt, maybe, post_inc};
  197use workspace::{
  198    Item as WorkspaceItem, ItemId, ItemNavHistory, OpenInTerminal, OpenTerminal,
  199    RestoreOnStartupBehavior, SERIALIZATION_THROTTLE_TIME, SplitDirection, TabBarSettings, Toast,
  200    ViewId, Workspace, WorkspaceId, WorkspaceSettings,
  201    item::{ItemHandle, PreviewTabsSettings},
  202    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  203    searchable::SearchEvent,
  204};
  205
  206use crate::hover_links::{find_url, find_url_from_range};
  207use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  208
  209pub const FILE_HEADER_HEIGHT: u32 = 2;
  210pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  211pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  212const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  213const MAX_LINE_LEN: usize = 1024;
  214const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  215const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  216pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  217#[doc(hidden)]
  218pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  219
  220pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
  221pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
  222pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  223
  224pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  225pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  226pub(crate) const MIN_LINE_NUMBER_DIGITS: u32 = 4;
  227
  228pub type RenderDiffHunkControlsFn = Arc<
  229    dyn Fn(
  230        u32,
  231        &DiffHunkStatus,
  232        Range<Anchor>,
  233        bool,
  234        Pixels,
  235        &Entity<Editor>,
  236        &mut Window,
  237        &mut App,
  238    ) -> AnyElement,
  239>;
  240
  241const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  242    alt: true,
  243    shift: true,
  244    control: false,
  245    platform: false,
  246    function: false,
  247};
  248
  249#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  250pub enum InlayId {
  251    InlineCompletion(usize),
  252    Hint(usize),
  253}
  254
  255impl InlayId {
  256    fn id(&self) -> usize {
  257        match self {
  258            Self::InlineCompletion(id) => *id,
  259            Self::Hint(id) => *id,
  260        }
  261    }
  262}
  263
  264pub enum DebugCurrentRowHighlight {}
  265enum DocumentHighlightRead {}
  266enum DocumentHighlightWrite {}
  267enum InputComposition {}
  268enum SelectedTextHighlight {}
  269
  270#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  271pub enum Navigated {
  272    Yes,
  273    No,
  274}
  275
  276impl Navigated {
  277    pub fn from_bool(yes: bool) -> Navigated {
  278        if yes { Navigated::Yes } else { Navigated::No }
  279    }
  280}
  281
  282#[derive(Debug, Clone, PartialEq, Eq)]
  283enum DisplayDiffHunk {
  284    Folded {
  285        display_row: DisplayRow,
  286    },
  287    Unfolded {
  288        is_created_file: bool,
  289        diff_base_byte_range: Range<usize>,
  290        display_row_range: Range<DisplayRow>,
  291        multi_buffer_range: Range<Anchor>,
  292        status: DiffHunkStatus,
  293    },
  294}
  295
  296pub enum HideMouseCursorOrigin {
  297    TypingAction,
  298    MovementAction,
  299}
  300
  301pub fn init_settings(cx: &mut App) {
  302    EditorSettings::register(cx);
  303}
  304
  305pub fn init(cx: &mut App) {
  306    init_settings(cx);
  307
  308    cx.set_global(GlobalBlameRenderer(Arc::new(())));
  309
  310    workspace::register_project_item::<Editor>(cx);
  311    workspace::FollowableViewRegistry::register::<Editor>(cx);
  312    workspace::register_serializable_item::<Editor>(cx);
  313
  314    cx.observe_new(
  315        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  316            workspace.register_action(Editor::new_file);
  317            workspace.register_action(Editor::new_file_vertical);
  318            workspace.register_action(Editor::new_file_horizontal);
  319            workspace.register_action(Editor::cancel_language_server_work);
  320        },
  321    )
  322    .detach();
  323
  324    cx.on_action(move |_: &workspace::NewFile, cx| {
  325        let app_state = workspace::AppState::global(cx);
  326        if let Some(app_state) = app_state.upgrade() {
  327            workspace::open_new(
  328                Default::default(),
  329                app_state,
  330                cx,
  331                |workspace, window, cx| {
  332                    Editor::new_file(workspace, &Default::default(), window, cx)
  333                },
  334            )
  335            .detach();
  336        }
  337    });
  338    cx.on_action(move |_: &workspace::NewWindow, cx| {
  339        let app_state = workspace::AppState::global(cx);
  340        if let Some(app_state) = app_state.upgrade() {
  341            workspace::open_new(
  342                Default::default(),
  343                app_state,
  344                cx,
  345                |workspace, window, cx| {
  346                    cx.activate(true);
  347                    Editor::new_file(workspace, &Default::default(), window, cx)
  348                },
  349            )
  350            .detach();
  351        }
  352    });
  353}
  354
  355pub fn set_blame_renderer(renderer: impl BlameRenderer + 'static, cx: &mut App) {
  356    cx.set_global(GlobalBlameRenderer(Arc::new(renderer)));
  357}
  358
  359pub struct SearchWithinRange;
  360
  361trait InvalidationRegion {
  362    fn ranges(&self) -> &[Range<Anchor>];
  363}
  364
  365#[derive(Clone, Debug, PartialEq)]
  366pub enum SelectPhase {
  367    Begin {
  368        position: DisplayPoint,
  369        add: bool,
  370        click_count: usize,
  371    },
  372    BeginColumnar {
  373        position: DisplayPoint,
  374        reset: bool,
  375        goal_column: u32,
  376    },
  377    Extend {
  378        position: DisplayPoint,
  379        click_count: usize,
  380    },
  381    Update {
  382        position: DisplayPoint,
  383        goal_column: u32,
  384        scroll_delta: gpui::Point<f32>,
  385    },
  386    End,
  387}
  388
  389#[derive(Clone, Debug)]
  390pub enum SelectMode {
  391    Character,
  392    Word(Range<Anchor>),
  393    Line(Range<Anchor>),
  394    All,
  395}
  396
  397#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  398pub enum EditorMode {
  399    SingleLine {
  400        auto_width: bool,
  401    },
  402    AutoHeight {
  403        max_lines: usize,
  404    },
  405    Full {
  406        /// When set to `true`, the editor will scale its UI elements with the buffer font size.
  407        scale_ui_elements_with_buffer_font_size: bool,
  408        /// When set to `true`, the editor will render a background for the active line.
  409        show_active_line_background: bool,
  410    },
  411}
  412
  413impl EditorMode {
  414    pub fn full() -> Self {
  415        Self::Full {
  416            scale_ui_elements_with_buffer_font_size: true,
  417            show_active_line_background: true,
  418        }
  419    }
  420
  421    pub fn is_full(&self) -> bool {
  422        matches!(self, Self::Full { .. })
  423    }
  424}
  425
  426#[derive(Copy, Clone, Debug)]
  427pub enum SoftWrap {
  428    /// Prefer not to wrap at all.
  429    ///
  430    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  431    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  432    GitDiff,
  433    /// Prefer a single line generally, unless an overly long line is encountered.
  434    None,
  435    /// Soft wrap lines that exceed the editor width.
  436    EditorWidth,
  437    /// Soft wrap lines at the preferred line length.
  438    Column(u32),
  439    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  440    Bounded(u32),
  441}
  442
  443#[derive(Clone)]
  444pub struct EditorStyle {
  445    pub background: Hsla,
  446    pub local_player: PlayerColor,
  447    pub text: TextStyle,
  448    pub scrollbar_width: Pixels,
  449    pub syntax: Arc<SyntaxTheme>,
  450    pub status: StatusColors,
  451    pub inlay_hints_style: HighlightStyle,
  452    pub inline_completion_styles: InlineCompletionStyles,
  453    pub unnecessary_code_fade: f32,
  454}
  455
  456impl Default for EditorStyle {
  457    fn default() -> Self {
  458        Self {
  459            background: Hsla::default(),
  460            local_player: PlayerColor::default(),
  461            text: TextStyle::default(),
  462            scrollbar_width: Pixels::default(),
  463            syntax: Default::default(),
  464            // HACK: Status colors don't have a real default.
  465            // We should look into removing the status colors from the editor
  466            // style and retrieve them directly from the theme.
  467            status: StatusColors::dark(),
  468            inlay_hints_style: HighlightStyle::default(),
  469            inline_completion_styles: InlineCompletionStyles {
  470                insertion: HighlightStyle::default(),
  471                whitespace: HighlightStyle::default(),
  472            },
  473            unnecessary_code_fade: Default::default(),
  474        }
  475    }
  476}
  477
  478pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  479    let show_background = language_settings::language_settings(None, None, cx)
  480        .inlay_hints
  481        .show_background;
  482
  483    HighlightStyle {
  484        color: Some(cx.theme().status().hint),
  485        background_color: show_background.then(|| cx.theme().status().hint_background),
  486        ..HighlightStyle::default()
  487    }
  488}
  489
  490pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  491    InlineCompletionStyles {
  492        insertion: HighlightStyle {
  493            color: Some(cx.theme().status().predictive),
  494            ..HighlightStyle::default()
  495        },
  496        whitespace: HighlightStyle {
  497            background_color: Some(cx.theme().status().created_background),
  498            ..HighlightStyle::default()
  499        },
  500    }
  501}
  502
  503type CompletionId = usize;
  504
  505pub(crate) enum EditDisplayMode {
  506    TabAccept,
  507    DiffPopover,
  508    Inline,
  509}
  510
  511enum InlineCompletion {
  512    Edit {
  513        edits: Vec<(Range<Anchor>, String)>,
  514        edit_preview: Option<EditPreview>,
  515        display_mode: EditDisplayMode,
  516        snapshot: BufferSnapshot,
  517    },
  518    Move {
  519        target: Anchor,
  520        snapshot: BufferSnapshot,
  521    },
  522}
  523
  524struct InlineCompletionState {
  525    inlay_ids: Vec<InlayId>,
  526    completion: InlineCompletion,
  527    completion_id: Option<SharedString>,
  528    invalidation_range: Range<Anchor>,
  529}
  530
  531enum EditPredictionSettings {
  532    Disabled,
  533    Enabled {
  534        show_in_menu: bool,
  535        preview_requires_modifier: bool,
  536    },
  537}
  538
  539enum InlineCompletionHighlight {}
  540
  541#[derive(Debug, Clone)]
  542struct InlineDiagnostic {
  543    message: SharedString,
  544    group_id: usize,
  545    is_primary: bool,
  546    start: Point,
  547    severity: DiagnosticSeverity,
  548}
  549
  550pub enum MenuInlineCompletionsPolicy {
  551    Never,
  552    ByProvider,
  553}
  554
  555pub enum EditPredictionPreview {
  556    /// Modifier is not pressed
  557    Inactive { released_too_fast: bool },
  558    /// Modifier pressed
  559    Active {
  560        since: Instant,
  561        previous_scroll_position: Option<ScrollAnchor>,
  562    },
  563}
  564
  565impl EditPredictionPreview {
  566    pub fn released_too_fast(&self) -> bool {
  567        match self {
  568            EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
  569            EditPredictionPreview::Active { .. } => false,
  570        }
  571    }
  572
  573    pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
  574        if let EditPredictionPreview::Active {
  575            previous_scroll_position,
  576            ..
  577        } = self
  578        {
  579            *previous_scroll_position = scroll_position;
  580        }
  581    }
  582}
  583
  584pub struct ContextMenuOptions {
  585    pub min_entries_visible: usize,
  586    pub max_entries_visible: usize,
  587    pub placement: Option<ContextMenuPlacement>,
  588}
  589
  590#[derive(Debug, Clone, PartialEq, Eq)]
  591pub enum ContextMenuPlacement {
  592    Above,
  593    Below,
  594}
  595
  596#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  597struct EditorActionId(usize);
  598
  599impl EditorActionId {
  600    pub fn post_inc(&mut self) -> Self {
  601        let answer = self.0;
  602
  603        *self = Self(answer + 1);
  604
  605        Self(answer)
  606    }
  607}
  608
  609// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  610// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  611
  612type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  613type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  614
  615#[derive(Default)]
  616struct ScrollbarMarkerState {
  617    scrollbar_size: Size<Pixels>,
  618    dirty: bool,
  619    markers: Arc<[PaintQuad]>,
  620    pending_refresh: Option<Task<Result<()>>>,
  621}
  622
  623impl ScrollbarMarkerState {
  624    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  625        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  626    }
  627}
  628
  629#[derive(Clone, Debug)]
  630struct RunnableTasks {
  631    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  632    offset: multi_buffer::Anchor,
  633    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  634    column: u32,
  635    // Values of all named captures, including those starting with '_'
  636    extra_variables: HashMap<String, String>,
  637    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  638    context_range: Range<BufferOffset>,
  639}
  640
  641impl RunnableTasks {
  642    fn resolve<'a>(
  643        &'a self,
  644        cx: &'a task::TaskContext,
  645    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  646        self.templates.iter().filter_map(|(kind, template)| {
  647            template
  648                .resolve_task(&kind.to_id_base(), cx)
  649                .map(|task| (kind.clone(), task))
  650        })
  651    }
  652}
  653
  654#[derive(Clone)]
  655struct ResolvedTasks {
  656    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  657    position: Anchor,
  658}
  659
  660#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  661struct BufferOffset(usize);
  662
  663// Addons allow storing per-editor state in other crates (e.g. Vim)
  664pub trait Addon: 'static {
  665    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  666
  667    fn render_buffer_header_controls(
  668        &self,
  669        _: &ExcerptInfo,
  670        _: &Window,
  671        _: &App,
  672    ) -> Option<AnyElement> {
  673        None
  674    }
  675
  676    fn to_any(&self) -> &dyn std::any::Any;
  677}
  678
  679/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  680///
  681/// See the [module level documentation](self) for more information.
  682pub struct Editor {
  683    focus_handle: FocusHandle,
  684    last_focused_descendant: Option<WeakFocusHandle>,
  685    /// The text buffer being edited
  686    buffer: Entity<MultiBuffer>,
  687    /// Map of how text in the buffer should be displayed.
  688    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  689    pub display_map: Entity<DisplayMap>,
  690    pub selections: SelectionsCollection,
  691    pub scroll_manager: ScrollManager,
  692    /// When inline assist editors are linked, they all render cursors because
  693    /// typing enters text into each of them, even the ones that aren't focused.
  694    pub(crate) show_cursor_when_unfocused: bool,
  695    columnar_selection_tail: Option<Anchor>,
  696    add_selections_state: Option<AddSelectionsState>,
  697    select_next_state: Option<SelectNextState>,
  698    select_prev_state: Option<SelectNextState>,
  699    selection_history: SelectionHistory,
  700    autoclose_regions: Vec<AutocloseRegion>,
  701    snippet_stack: InvalidationStack<SnippetState>,
  702    select_syntax_node_history: SelectSyntaxNodeHistory,
  703    ime_transaction: Option<TransactionId>,
  704    active_diagnostics: Option<ActiveDiagnosticGroup>,
  705    show_inline_diagnostics: bool,
  706    inline_diagnostics_update: Task<()>,
  707    inline_diagnostics_enabled: bool,
  708    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  709    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  710    hard_wrap: Option<usize>,
  711
  712    // TODO: make this a access method
  713    pub project: Option<Entity<Project>>,
  714    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  715    completion_provider: Option<Box<dyn CompletionProvider>>,
  716    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  717    blink_manager: Entity<BlinkManager>,
  718    show_cursor_names: bool,
  719    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  720    pub show_local_selections: bool,
  721    mode: EditorMode,
  722    show_breadcrumbs: bool,
  723    show_gutter: bool,
  724    show_scrollbars: bool,
  725    show_line_numbers: Option<bool>,
  726    use_relative_line_numbers: Option<bool>,
  727    show_git_diff_gutter: Option<bool>,
  728    show_code_actions: Option<bool>,
  729    show_runnables: Option<bool>,
  730    show_breakpoints: Option<bool>,
  731    show_wrap_guides: Option<bool>,
  732    show_indent_guides: Option<bool>,
  733    placeholder_text: Option<Arc<str>>,
  734    highlight_order: usize,
  735    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  736    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  737    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  738    scrollbar_marker_state: ScrollbarMarkerState,
  739    active_indent_guides_state: ActiveIndentGuidesState,
  740    nav_history: Option<ItemNavHistory>,
  741    context_menu: RefCell<Option<CodeContextMenu>>,
  742    context_menu_options: Option<ContextMenuOptions>,
  743    mouse_context_menu: Option<MouseContextMenu>,
  744    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  745    signature_help_state: SignatureHelpState,
  746    auto_signature_help: Option<bool>,
  747    find_all_references_task_sources: Vec<Anchor>,
  748    next_completion_id: CompletionId,
  749    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  750    code_actions_task: Option<Task<Result<()>>>,
  751    selection_highlight_task: Option<Task<()>>,
  752    document_highlights_task: Option<Task<()>>,
  753    linked_editing_range_task: Option<Task<Option<()>>>,
  754    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  755    pending_rename: Option<RenameState>,
  756    searchable: bool,
  757    cursor_shape: CursorShape,
  758    current_line_highlight: Option<CurrentLineHighlight>,
  759    collapse_matches: bool,
  760    autoindent_mode: Option<AutoindentMode>,
  761    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  762    input_enabled: bool,
  763    use_modal_editing: bool,
  764    read_only: bool,
  765    leader_peer_id: Option<PeerId>,
  766    remote_id: Option<ViewId>,
  767    hover_state: HoverState,
  768    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  769    gutter_hovered: bool,
  770    hovered_link_state: Option<HoveredLinkState>,
  771    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  772    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  773    active_inline_completion: Option<InlineCompletionState>,
  774    /// Used to prevent flickering as the user types while the menu is open
  775    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  776    edit_prediction_settings: EditPredictionSettings,
  777    inline_completions_hidden_for_vim_mode: bool,
  778    show_inline_completions_override: Option<bool>,
  779    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  780    edit_prediction_preview: EditPredictionPreview,
  781    edit_prediction_indent_conflict: bool,
  782    edit_prediction_requires_modifier_in_indent_conflict: bool,
  783    inlay_hint_cache: InlayHintCache,
  784    next_inlay_id: usize,
  785    _subscriptions: Vec<Subscription>,
  786    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  787    gutter_dimensions: GutterDimensions,
  788    style: Option<EditorStyle>,
  789    text_style_refinement: Option<TextStyleRefinement>,
  790    next_editor_action_id: EditorActionId,
  791    editor_actions:
  792        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  793    use_autoclose: bool,
  794    use_auto_surround: bool,
  795    auto_replace_emoji_shortcode: bool,
  796    jsx_tag_auto_close_enabled_in_any_buffer: bool,
  797    show_git_blame_gutter: bool,
  798    show_git_blame_inline: bool,
  799    show_git_blame_inline_delay_task: Option<Task<()>>,
  800    pub git_blame_inline_tooltip: Option<AnyWeakEntity>,
  801    git_blame_inline_enabled: bool,
  802    render_diff_hunk_controls: RenderDiffHunkControlsFn,
  803    serialize_dirty_buffers: bool,
  804    show_selection_menu: Option<bool>,
  805    blame: Option<Entity<GitBlame>>,
  806    blame_subscription: Option<Subscription>,
  807    custom_context_menu: Option<
  808        Box<
  809            dyn 'static
  810                + Fn(
  811                    &mut Self,
  812                    DisplayPoint,
  813                    &mut Window,
  814                    &mut Context<Self>,
  815                ) -> Option<Entity<ui::ContextMenu>>,
  816        >,
  817    >,
  818    last_bounds: Option<Bounds<Pixels>>,
  819    last_position_map: Option<Rc<PositionMap>>,
  820    expect_bounds_change: Option<Bounds<Pixels>>,
  821    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  822    tasks_update_task: Option<Task<()>>,
  823    breakpoint_store: Option<Entity<BreakpointStore>>,
  824    /// Allow's a user to create a breakpoint by selecting this indicator
  825    /// It should be None while a user is not hovering over the gutter
  826    /// Otherwise it represents the point that the breakpoint will be shown
  827    gutter_breakpoint_indicator: (Option<(DisplayPoint, bool)>, Option<Task<()>>),
  828    in_project_search: bool,
  829    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  830    breadcrumb_header: Option<String>,
  831    focused_block: Option<FocusedBlock>,
  832    next_scroll_position: NextScrollCursorCenterTopBottom,
  833    addons: HashMap<TypeId, Box<dyn Addon>>,
  834    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  835    load_diff_task: Option<Shared<Task<()>>>,
  836    selection_mark_mode: bool,
  837    toggle_fold_multiple_buffers: Task<()>,
  838    _scroll_cursor_center_top_bottom_task: Task<()>,
  839    serialize_selections: Task<()>,
  840    serialize_folds: Task<()>,
  841    mouse_cursor_hidden: bool,
  842    hide_mouse_mode: HideMouseMode,
  843}
  844
  845#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  846enum NextScrollCursorCenterTopBottom {
  847    #[default]
  848    Center,
  849    Top,
  850    Bottom,
  851}
  852
  853impl NextScrollCursorCenterTopBottom {
  854    fn next(&self) -> Self {
  855        match self {
  856            Self::Center => Self::Top,
  857            Self::Top => Self::Bottom,
  858            Self::Bottom => Self::Center,
  859        }
  860    }
  861}
  862
  863#[derive(Clone)]
  864pub struct EditorSnapshot {
  865    pub mode: EditorMode,
  866    show_gutter: bool,
  867    show_line_numbers: Option<bool>,
  868    show_git_diff_gutter: Option<bool>,
  869    show_code_actions: Option<bool>,
  870    show_runnables: Option<bool>,
  871    show_breakpoints: Option<bool>,
  872    git_blame_gutter_max_author_length: Option<usize>,
  873    pub display_snapshot: DisplaySnapshot,
  874    pub placeholder_text: Option<Arc<str>>,
  875    is_focused: bool,
  876    scroll_anchor: ScrollAnchor,
  877    ongoing_scroll: OngoingScroll,
  878    current_line_highlight: CurrentLineHighlight,
  879    gutter_hovered: bool,
  880}
  881
  882#[derive(Default, Debug, Clone, Copy)]
  883pub struct GutterDimensions {
  884    pub left_padding: Pixels,
  885    pub right_padding: Pixels,
  886    pub width: Pixels,
  887    pub margin: Pixels,
  888    pub git_blame_entries_width: Option<Pixels>,
  889}
  890
  891impl GutterDimensions {
  892    /// The full width of the space taken up by the gutter.
  893    pub fn full_width(&self) -> Pixels {
  894        self.margin + self.width
  895    }
  896
  897    /// The width of the space reserved for the fold indicators,
  898    /// use alongside 'justify_end' and `gutter_width` to
  899    /// right align content with the line numbers
  900    pub fn fold_area_width(&self) -> Pixels {
  901        self.margin + self.right_padding
  902    }
  903}
  904
  905#[derive(Debug)]
  906pub struct RemoteSelection {
  907    pub replica_id: ReplicaId,
  908    pub selection: Selection<Anchor>,
  909    pub cursor_shape: CursorShape,
  910    pub peer_id: PeerId,
  911    pub line_mode: bool,
  912    pub participant_index: Option<ParticipantIndex>,
  913    pub user_name: Option<SharedString>,
  914}
  915
  916#[derive(Clone, Debug)]
  917struct SelectionHistoryEntry {
  918    selections: Arc<[Selection<Anchor>]>,
  919    select_next_state: Option<SelectNextState>,
  920    select_prev_state: Option<SelectNextState>,
  921    add_selections_state: Option<AddSelectionsState>,
  922}
  923
  924enum SelectionHistoryMode {
  925    Normal,
  926    Undoing,
  927    Redoing,
  928}
  929
  930#[derive(Clone, PartialEq, Eq, Hash)]
  931struct HoveredCursor {
  932    replica_id: u16,
  933    selection_id: usize,
  934}
  935
  936impl Default for SelectionHistoryMode {
  937    fn default() -> Self {
  938        Self::Normal
  939    }
  940}
  941
  942#[derive(Default)]
  943struct SelectionHistory {
  944    #[allow(clippy::type_complexity)]
  945    selections_by_transaction:
  946        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  947    mode: SelectionHistoryMode,
  948    undo_stack: VecDeque<SelectionHistoryEntry>,
  949    redo_stack: VecDeque<SelectionHistoryEntry>,
  950}
  951
  952impl SelectionHistory {
  953    fn insert_transaction(
  954        &mut self,
  955        transaction_id: TransactionId,
  956        selections: Arc<[Selection<Anchor>]>,
  957    ) {
  958        self.selections_by_transaction
  959            .insert(transaction_id, (selections, None));
  960    }
  961
  962    #[allow(clippy::type_complexity)]
  963    fn transaction(
  964        &self,
  965        transaction_id: TransactionId,
  966    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  967        self.selections_by_transaction.get(&transaction_id)
  968    }
  969
  970    #[allow(clippy::type_complexity)]
  971    fn transaction_mut(
  972        &mut self,
  973        transaction_id: TransactionId,
  974    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  975        self.selections_by_transaction.get_mut(&transaction_id)
  976    }
  977
  978    fn push(&mut self, entry: SelectionHistoryEntry) {
  979        if !entry.selections.is_empty() {
  980            match self.mode {
  981                SelectionHistoryMode::Normal => {
  982                    self.push_undo(entry);
  983                    self.redo_stack.clear();
  984                }
  985                SelectionHistoryMode::Undoing => self.push_redo(entry),
  986                SelectionHistoryMode::Redoing => self.push_undo(entry),
  987            }
  988        }
  989    }
  990
  991    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  992        if self
  993            .undo_stack
  994            .back()
  995            .map_or(true, |e| e.selections != entry.selections)
  996        {
  997            self.undo_stack.push_back(entry);
  998            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  999                self.undo_stack.pop_front();
 1000            }
 1001        }
 1002    }
 1003
 1004    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
 1005        if self
 1006            .redo_stack
 1007            .back()
 1008            .map_or(true, |e| e.selections != entry.selections)
 1009        {
 1010            self.redo_stack.push_back(entry);
 1011            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 1012                self.redo_stack.pop_front();
 1013            }
 1014        }
 1015    }
 1016}
 1017
 1018struct RowHighlight {
 1019    index: usize,
 1020    range: Range<Anchor>,
 1021    color: Hsla,
 1022    should_autoscroll: bool,
 1023}
 1024
 1025#[derive(Clone, Debug)]
 1026struct AddSelectionsState {
 1027    above: bool,
 1028    stack: Vec<usize>,
 1029}
 1030
 1031#[derive(Clone)]
 1032struct SelectNextState {
 1033    query: AhoCorasick,
 1034    wordwise: bool,
 1035    done: bool,
 1036}
 1037
 1038impl std::fmt::Debug for SelectNextState {
 1039    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 1040        f.debug_struct(std::any::type_name::<Self>())
 1041            .field("wordwise", &self.wordwise)
 1042            .field("done", &self.done)
 1043            .finish()
 1044    }
 1045}
 1046
 1047#[derive(Debug)]
 1048struct AutocloseRegion {
 1049    selection_id: usize,
 1050    range: Range<Anchor>,
 1051    pair: BracketPair,
 1052}
 1053
 1054#[derive(Debug)]
 1055struct SnippetState {
 1056    ranges: Vec<Vec<Range<Anchor>>>,
 1057    active_index: usize,
 1058    choices: Vec<Option<Vec<String>>>,
 1059}
 1060
 1061#[doc(hidden)]
 1062pub struct RenameState {
 1063    pub range: Range<Anchor>,
 1064    pub old_name: Arc<str>,
 1065    pub editor: Entity<Editor>,
 1066    block_id: CustomBlockId,
 1067}
 1068
 1069struct InvalidationStack<T>(Vec<T>);
 1070
 1071struct RegisteredInlineCompletionProvider {
 1072    provider: Arc<dyn InlineCompletionProviderHandle>,
 1073    _subscription: Subscription,
 1074}
 1075
 1076#[derive(Debug, PartialEq, Eq)]
 1077struct ActiveDiagnosticGroup {
 1078    primary_range: Range<Anchor>,
 1079    primary_message: String,
 1080    group_id: usize,
 1081    blocks: HashMap<CustomBlockId, Diagnostic>,
 1082    is_valid: bool,
 1083}
 1084
 1085#[derive(Serialize, Deserialize, Clone, Debug)]
 1086pub struct ClipboardSelection {
 1087    /// The number of bytes in this selection.
 1088    pub len: usize,
 1089    /// Whether this was a full-line selection.
 1090    pub is_entire_line: bool,
 1091    /// The indentation of the first line when this content was originally copied.
 1092    pub first_line_indent: u32,
 1093}
 1094
 1095// selections, scroll behavior, was newest selection reversed
 1096type SelectSyntaxNodeHistoryState = (
 1097    Box<[Selection<usize>]>,
 1098    SelectSyntaxNodeScrollBehavior,
 1099    bool,
 1100);
 1101
 1102#[derive(Default)]
 1103struct SelectSyntaxNodeHistory {
 1104    stack: Vec<SelectSyntaxNodeHistoryState>,
 1105    // disable temporarily to allow changing selections without losing the stack
 1106    pub disable_clearing: bool,
 1107}
 1108
 1109impl SelectSyntaxNodeHistory {
 1110    pub fn try_clear(&mut self) {
 1111        if !self.disable_clearing {
 1112            self.stack.clear();
 1113        }
 1114    }
 1115
 1116    pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
 1117        self.stack.push(selection);
 1118    }
 1119
 1120    pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
 1121        self.stack.pop()
 1122    }
 1123}
 1124
 1125enum SelectSyntaxNodeScrollBehavior {
 1126    CursorTop,
 1127    FitSelection,
 1128    CursorBottom,
 1129}
 1130
 1131#[derive(Debug)]
 1132pub(crate) struct NavigationData {
 1133    cursor_anchor: Anchor,
 1134    cursor_position: Point,
 1135    scroll_anchor: ScrollAnchor,
 1136    scroll_top_row: u32,
 1137}
 1138
 1139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1140pub enum GotoDefinitionKind {
 1141    Symbol,
 1142    Declaration,
 1143    Type,
 1144    Implementation,
 1145}
 1146
 1147#[derive(Debug, Clone)]
 1148enum InlayHintRefreshReason {
 1149    ModifiersChanged(bool),
 1150    Toggle(bool),
 1151    SettingsChange(InlayHintSettings),
 1152    NewLinesShown,
 1153    BufferEdited(HashSet<Arc<Language>>),
 1154    RefreshRequested,
 1155    ExcerptsRemoved(Vec<ExcerptId>),
 1156}
 1157
 1158impl InlayHintRefreshReason {
 1159    fn description(&self) -> &'static str {
 1160        match self {
 1161            Self::ModifiersChanged(_) => "modifiers changed",
 1162            Self::Toggle(_) => "toggle",
 1163            Self::SettingsChange(_) => "settings change",
 1164            Self::NewLinesShown => "new lines shown",
 1165            Self::BufferEdited(_) => "buffer edited",
 1166            Self::RefreshRequested => "refresh requested",
 1167            Self::ExcerptsRemoved(_) => "excerpts removed",
 1168        }
 1169    }
 1170}
 1171
 1172pub enum FormatTarget {
 1173    Buffers,
 1174    Ranges(Vec<Range<MultiBufferPoint>>),
 1175}
 1176
 1177pub(crate) struct FocusedBlock {
 1178    id: BlockId,
 1179    focus_handle: WeakFocusHandle,
 1180}
 1181
 1182#[derive(Clone)]
 1183enum JumpData {
 1184    MultiBufferRow {
 1185        row: MultiBufferRow,
 1186        line_offset_from_top: u32,
 1187    },
 1188    MultiBufferPoint {
 1189        excerpt_id: ExcerptId,
 1190        position: Point,
 1191        anchor: text::Anchor,
 1192        line_offset_from_top: u32,
 1193    },
 1194}
 1195
 1196pub enum MultibufferSelectionMode {
 1197    First,
 1198    All,
 1199}
 1200
 1201#[derive(Clone, Copy, Debug, Default)]
 1202pub struct RewrapOptions {
 1203    pub override_language_settings: bool,
 1204    pub preserve_existing_whitespace: bool,
 1205}
 1206
 1207impl Editor {
 1208    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1209        let buffer = cx.new(|cx| Buffer::local("", cx));
 1210        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1211        Self::new(
 1212            EditorMode::SingleLine { auto_width: false },
 1213            buffer,
 1214            None,
 1215            window,
 1216            cx,
 1217        )
 1218    }
 1219
 1220    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1221        let buffer = cx.new(|cx| Buffer::local("", cx));
 1222        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1223        Self::new(EditorMode::full(), buffer, None, window, cx)
 1224    }
 1225
 1226    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1227        let buffer = cx.new(|cx| Buffer::local("", cx));
 1228        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1229        Self::new(
 1230            EditorMode::SingleLine { auto_width: true },
 1231            buffer,
 1232            None,
 1233            window,
 1234            cx,
 1235        )
 1236    }
 1237
 1238    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1239        let buffer = cx.new(|cx| Buffer::local("", cx));
 1240        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1241        Self::new(
 1242            EditorMode::AutoHeight { max_lines },
 1243            buffer,
 1244            None,
 1245            window,
 1246            cx,
 1247        )
 1248    }
 1249
 1250    pub fn for_buffer(
 1251        buffer: Entity<Buffer>,
 1252        project: Option<Entity<Project>>,
 1253        window: &mut Window,
 1254        cx: &mut Context<Self>,
 1255    ) -> Self {
 1256        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1257        Self::new(EditorMode::full(), buffer, project, window, cx)
 1258    }
 1259
 1260    pub fn for_multibuffer(
 1261        buffer: Entity<MultiBuffer>,
 1262        project: Option<Entity<Project>>,
 1263        window: &mut Window,
 1264        cx: &mut Context<Self>,
 1265    ) -> Self {
 1266        Self::new(EditorMode::full(), buffer, project, window, cx)
 1267    }
 1268
 1269    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1270        let mut clone = Self::new(
 1271            self.mode,
 1272            self.buffer.clone(),
 1273            self.project.clone(),
 1274            window,
 1275            cx,
 1276        );
 1277        self.display_map.update(cx, |display_map, cx| {
 1278            let snapshot = display_map.snapshot(cx);
 1279            clone.display_map.update(cx, |display_map, cx| {
 1280                display_map.set_state(&snapshot, cx);
 1281            });
 1282        });
 1283        clone.folds_did_change(cx);
 1284        clone.selections.clone_state(&self.selections);
 1285        clone.scroll_manager.clone_state(&self.scroll_manager);
 1286        clone.searchable = self.searchable;
 1287        clone.read_only = self.read_only;
 1288        clone
 1289    }
 1290
 1291    pub fn new(
 1292        mode: EditorMode,
 1293        buffer: Entity<MultiBuffer>,
 1294        project: Option<Entity<Project>>,
 1295        window: &mut Window,
 1296        cx: &mut Context<Self>,
 1297    ) -> Self {
 1298        let style = window.text_style();
 1299        let font_size = style.font_size.to_pixels(window.rem_size());
 1300        let editor = cx.entity().downgrade();
 1301        let fold_placeholder = FoldPlaceholder {
 1302            constrain_width: true,
 1303            render: Arc::new(move |fold_id, fold_range, cx| {
 1304                let editor = editor.clone();
 1305                div()
 1306                    .id(fold_id)
 1307                    .bg(cx.theme().colors().ghost_element_background)
 1308                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1309                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1310                    .rounded_xs()
 1311                    .size_full()
 1312                    .cursor_pointer()
 1313                    .child("")
 1314                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1315                    .on_click(move |_, _window, cx| {
 1316                        editor
 1317                            .update(cx, |editor, cx| {
 1318                                editor.unfold_ranges(
 1319                                    &[fold_range.start..fold_range.end],
 1320                                    true,
 1321                                    false,
 1322                                    cx,
 1323                                );
 1324                                cx.stop_propagation();
 1325                            })
 1326                            .ok();
 1327                    })
 1328                    .into_any()
 1329            }),
 1330            merge_adjacent: true,
 1331            ..Default::default()
 1332        };
 1333        let display_map = cx.new(|cx| {
 1334            DisplayMap::new(
 1335                buffer.clone(),
 1336                style.font(),
 1337                font_size,
 1338                None,
 1339                FILE_HEADER_HEIGHT,
 1340                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1341                fold_placeholder,
 1342                cx,
 1343            )
 1344        });
 1345
 1346        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1347
 1348        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1349
 1350        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1351            .then(|| language_settings::SoftWrap::None);
 1352
 1353        let mut project_subscriptions = Vec::new();
 1354        if mode.is_full() {
 1355            if let Some(project) = project.as_ref() {
 1356                project_subscriptions.push(cx.subscribe_in(
 1357                    project,
 1358                    window,
 1359                    |editor, _, event, window, cx| match event {
 1360                        project::Event::RefreshCodeLens => {
 1361                            // we always query lens with actions, without storing them, always refreshing them
 1362                        }
 1363                        project::Event::RefreshInlayHints => {
 1364                            editor
 1365                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1366                        }
 1367                        project::Event::SnippetEdit(id, snippet_edits) => {
 1368                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1369                                let focus_handle = editor.focus_handle(cx);
 1370                                if focus_handle.is_focused(window) {
 1371                                    let snapshot = buffer.read(cx).snapshot();
 1372                                    for (range, snippet) in snippet_edits {
 1373                                        let editor_range =
 1374                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1375                                        editor
 1376                                            .insert_snippet(
 1377                                                &[editor_range],
 1378                                                snippet.clone(),
 1379                                                window,
 1380                                                cx,
 1381                                            )
 1382                                            .ok();
 1383                                    }
 1384                                }
 1385                            }
 1386                        }
 1387                        _ => {}
 1388                    },
 1389                ));
 1390                if let Some(task_inventory) = project
 1391                    .read(cx)
 1392                    .task_store()
 1393                    .read(cx)
 1394                    .task_inventory()
 1395                    .cloned()
 1396                {
 1397                    project_subscriptions.push(cx.observe_in(
 1398                        &task_inventory,
 1399                        window,
 1400                        |editor, _, window, cx| {
 1401                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1402                        },
 1403                    ));
 1404                };
 1405
 1406                project_subscriptions.push(cx.subscribe_in(
 1407                    &project.read(cx).breakpoint_store(),
 1408                    window,
 1409                    |editor, _, event, window, cx| match event {
 1410                        BreakpointStoreEvent::ActiveDebugLineChanged => {
 1411                            if editor.go_to_active_debug_line(window, cx) {
 1412                                cx.stop_propagation();
 1413                            }
 1414                        }
 1415                        _ => {}
 1416                    },
 1417                ));
 1418            }
 1419        }
 1420
 1421        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1422
 1423        let inlay_hint_settings =
 1424            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1425        let focus_handle = cx.focus_handle();
 1426        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1427            .detach();
 1428        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1429            .detach();
 1430        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1431            .detach();
 1432        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1433            .detach();
 1434
 1435        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1436            Some(false)
 1437        } else {
 1438            None
 1439        };
 1440
 1441        let breakpoint_store = match (mode, project.as_ref()) {
 1442            (EditorMode::Full { .. }, Some(project)) => Some(project.read(cx).breakpoint_store()),
 1443            _ => None,
 1444        };
 1445
 1446        let mut code_action_providers = Vec::new();
 1447        let mut load_uncommitted_diff = None;
 1448        if let Some(project) = project.clone() {
 1449            load_uncommitted_diff = Some(
 1450                get_uncommitted_diff_for_buffer(
 1451                    &project,
 1452                    buffer.read(cx).all_buffers(),
 1453                    buffer.clone(),
 1454                    cx,
 1455                )
 1456                .shared(),
 1457            );
 1458            code_action_providers.push(Rc::new(project) as Rc<_>);
 1459        }
 1460
 1461        let mut this = Self {
 1462            focus_handle,
 1463            show_cursor_when_unfocused: false,
 1464            last_focused_descendant: None,
 1465            buffer: buffer.clone(),
 1466            display_map: display_map.clone(),
 1467            selections,
 1468            scroll_manager: ScrollManager::new(cx),
 1469            columnar_selection_tail: None,
 1470            add_selections_state: None,
 1471            select_next_state: None,
 1472            select_prev_state: None,
 1473            selection_history: Default::default(),
 1474            autoclose_regions: Default::default(),
 1475            snippet_stack: Default::default(),
 1476            select_syntax_node_history: SelectSyntaxNodeHistory::default(),
 1477            ime_transaction: Default::default(),
 1478            active_diagnostics: None,
 1479            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1480            inline_diagnostics_update: Task::ready(()),
 1481            inline_diagnostics: Vec::new(),
 1482            soft_wrap_mode_override,
 1483            hard_wrap: None,
 1484            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1485            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1486            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1487            project,
 1488            blink_manager: blink_manager.clone(),
 1489            show_local_selections: true,
 1490            show_scrollbars: true,
 1491            mode,
 1492            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1493            show_gutter: mode.is_full(),
 1494            show_line_numbers: None,
 1495            use_relative_line_numbers: None,
 1496            show_git_diff_gutter: None,
 1497            show_code_actions: None,
 1498            show_runnables: None,
 1499            show_breakpoints: None,
 1500            show_wrap_guides: None,
 1501            show_indent_guides,
 1502            placeholder_text: None,
 1503            highlight_order: 0,
 1504            highlighted_rows: HashMap::default(),
 1505            background_highlights: Default::default(),
 1506            gutter_highlights: TreeMap::default(),
 1507            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1508            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1509            nav_history: None,
 1510            context_menu: RefCell::new(None),
 1511            context_menu_options: None,
 1512            mouse_context_menu: None,
 1513            completion_tasks: Default::default(),
 1514            signature_help_state: SignatureHelpState::default(),
 1515            auto_signature_help: None,
 1516            find_all_references_task_sources: Vec::new(),
 1517            next_completion_id: 0,
 1518            next_inlay_id: 0,
 1519            code_action_providers,
 1520            available_code_actions: Default::default(),
 1521            code_actions_task: Default::default(),
 1522            selection_highlight_task: Default::default(),
 1523            document_highlights_task: Default::default(),
 1524            linked_editing_range_task: Default::default(),
 1525            pending_rename: Default::default(),
 1526            searchable: true,
 1527            cursor_shape: EditorSettings::get_global(cx)
 1528                .cursor_shape
 1529                .unwrap_or_default(),
 1530            current_line_highlight: None,
 1531            autoindent_mode: Some(AutoindentMode::EachLine),
 1532            collapse_matches: false,
 1533            workspace: None,
 1534            input_enabled: true,
 1535            use_modal_editing: mode.is_full(),
 1536            read_only: false,
 1537            use_autoclose: true,
 1538            use_auto_surround: true,
 1539            auto_replace_emoji_shortcode: false,
 1540            jsx_tag_auto_close_enabled_in_any_buffer: false,
 1541            leader_peer_id: None,
 1542            remote_id: None,
 1543            hover_state: Default::default(),
 1544            pending_mouse_down: None,
 1545            hovered_link_state: Default::default(),
 1546            edit_prediction_provider: None,
 1547            active_inline_completion: None,
 1548            stale_inline_completion_in_menu: None,
 1549            edit_prediction_preview: EditPredictionPreview::Inactive {
 1550                released_too_fast: false,
 1551            },
 1552            inline_diagnostics_enabled: mode.is_full(),
 1553            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1554
 1555            gutter_hovered: false,
 1556            pixel_position_of_newest_cursor: None,
 1557            last_bounds: None,
 1558            last_position_map: None,
 1559            expect_bounds_change: None,
 1560            gutter_dimensions: GutterDimensions::default(),
 1561            style: None,
 1562            show_cursor_names: false,
 1563            hovered_cursors: Default::default(),
 1564            next_editor_action_id: EditorActionId::default(),
 1565            editor_actions: Rc::default(),
 1566            inline_completions_hidden_for_vim_mode: false,
 1567            show_inline_completions_override: None,
 1568            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1569            edit_prediction_settings: EditPredictionSettings::Disabled,
 1570            edit_prediction_indent_conflict: false,
 1571            edit_prediction_requires_modifier_in_indent_conflict: true,
 1572            custom_context_menu: None,
 1573            show_git_blame_gutter: false,
 1574            show_git_blame_inline: false,
 1575            show_selection_menu: None,
 1576            show_git_blame_inline_delay_task: None,
 1577            git_blame_inline_tooltip: None,
 1578            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1579            render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
 1580            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1581                .session
 1582                .restore_unsaved_buffers,
 1583            blame: None,
 1584            blame_subscription: None,
 1585            tasks: Default::default(),
 1586
 1587            breakpoint_store,
 1588            gutter_breakpoint_indicator: (None, None),
 1589            _subscriptions: vec![
 1590                cx.observe(&buffer, Self::on_buffer_changed),
 1591                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1592                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1593                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1594                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1595                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1596                cx.observe_window_activation(window, |editor, window, cx| {
 1597                    let active = window.is_window_active();
 1598                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1599                        if active {
 1600                            blink_manager.enable(cx);
 1601                        } else {
 1602                            blink_manager.disable(cx);
 1603                        }
 1604                    });
 1605                }),
 1606            ],
 1607            tasks_update_task: None,
 1608            linked_edit_ranges: Default::default(),
 1609            in_project_search: false,
 1610            previous_search_ranges: None,
 1611            breadcrumb_header: None,
 1612            focused_block: None,
 1613            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1614            addons: HashMap::default(),
 1615            registered_buffers: HashMap::default(),
 1616            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1617            selection_mark_mode: false,
 1618            toggle_fold_multiple_buffers: Task::ready(()),
 1619            serialize_selections: Task::ready(()),
 1620            serialize_folds: Task::ready(()),
 1621            text_style_refinement: None,
 1622            load_diff_task: load_uncommitted_diff,
 1623            mouse_cursor_hidden: false,
 1624            hide_mouse_mode: EditorSettings::get_global(cx)
 1625                .hide_mouse
 1626                .unwrap_or_default(),
 1627        };
 1628        if let Some(breakpoints) = this.breakpoint_store.as_ref() {
 1629            this._subscriptions
 1630                .push(cx.observe(breakpoints, |_, _, cx| {
 1631                    cx.notify();
 1632                }));
 1633        }
 1634        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1635        this._subscriptions.extend(project_subscriptions);
 1636
 1637        this._subscriptions.push(cx.subscribe_in(
 1638            &cx.entity(),
 1639            window,
 1640            |editor, _, e: &EditorEvent, window, cx| {
 1641                if let EditorEvent::SelectionsChanged { local } = e {
 1642                    if *local {
 1643                        let new_anchor = editor.scroll_manager.anchor();
 1644                        let snapshot = editor.snapshot(window, cx);
 1645                        editor.update_restoration_data(cx, move |data| {
 1646                            data.scroll_position = (
 1647                                new_anchor.top_row(&snapshot.buffer_snapshot),
 1648                                new_anchor.offset,
 1649                            );
 1650                        });
 1651                    }
 1652                }
 1653            },
 1654        ));
 1655
 1656        this.end_selection(window, cx);
 1657        this.scroll_manager.show_scrollbars(window, cx);
 1658        jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
 1659
 1660        if mode.is_full() {
 1661            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1662            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1663
 1664            if this.git_blame_inline_enabled {
 1665                this.git_blame_inline_enabled = true;
 1666                this.start_git_blame_inline(false, window, cx);
 1667            }
 1668
 1669            this.go_to_active_debug_line(window, cx);
 1670
 1671            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1672                if let Some(project) = this.project.as_ref() {
 1673                    let handle = project.update(cx, |project, cx| {
 1674                        project.register_buffer_with_language_servers(&buffer, cx)
 1675                    });
 1676                    this.registered_buffers
 1677                        .insert(buffer.read(cx).remote_id(), handle);
 1678                }
 1679            }
 1680        }
 1681
 1682        this.report_editor_event("Editor Opened", None, cx);
 1683        this
 1684    }
 1685
 1686    pub fn deploy_mouse_context_menu(
 1687        &mut self,
 1688        position: gpui::Point<Pixels>,
 1689        context_menu: Entity<ContextMenu>,
 1690        window: &mut Window,
 1691        cx: &mut Context<Self>,
 1692    ) {
 1693        self.mouse_context_menu = Some(MouseContextMenu::new(
 1694            crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
 1695            context_menu,
 1696            window,
 1697            cx,
 1698        ));
 1699    }
 1700
 1701    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1702        self.mouse_context_menu
 1703            .as_ref()
 1704            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1705    }
 1706
 1707    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1708        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1709    }
 1710
 1711    fn key_context_internal(
 1712        &self,
 1713        has_active_edit_prediction: bool,
 1714        window: &Window,
 1715        cx: &App,
 1716    ) -> KeyContext {
 1717        let mut key_context = KeyContext::new_with_defaults();
 1718        key_context.add("Editor");
 1719        let mode = match self.mode {
 1720            EditorMode::SingleLine { .. } => "single_line",
 1721            EditorMode::AutoHeight { .. } => "auto_height",
 1722            EditorMode::Full { .. } => "full",
 1723        };
 1724
 1725        if EditorSettings::jupyter_enabled(cx) {
 1726            key_context.add("jupyter");
 1727        }
 1728
 1729        key_context.set("mode", mode);
 1730        if self.pending_rename.is_some() {
 1731            key_context.add("renaming");
 1732        }
 1733
 1734        match self.context_menu.borrow().as_ref() {
 1735            Some(CodeContextMenu::Completions(_)) => {
 1736                key_context.add("menu");
 1737                key_context.add("showing_completions");
 1738            }
 1739            Some(CodeContextMenu::CodeActions(_)) => {
 1740                key_context.add("menu");
 1741                key_context.add("showing_code_actions")
 1742            }
 1743            None => {}
 1744        }
 1745
 1746        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1747        if !self.focus_handle(cx).contains_focused(window, cx)
 1748            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1749        {
 1750            for addon in self.addons.values() {
 1751                addon.extend_key_context(&mut key_context, cx)
 1752            }
 1753        }
 1754
 1755        if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
 1756            if let Some(extension) = singleton_buffer
 1757                .read(cx)
 1758                .file()
 1759                .and_then(|file| file.path().extension()?.to_str())
 1760            {
 1761                key_context.set("extension", extension.to_string());
 1762            }
 1763        } else {
 1764            key_context.add("multibuffer");
 1765        }
 1766
 1767        if has_active_edit_prediction {
 1768            if self.edit_prediction_in_conflict() {
 1769                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1770            } else {
 1771                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1772                key_context.add("copilot_suggestion");
 1773            }
 1774        }
 1775
 1776        if self.selection_mark_mode {
 1777            key_context.add("selection_mode");
 1778        }
 1779
 1780        key_context
 1781    }
 1782
 1783    pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
 1784        self.mouse_cursor_hidden = match origin {
 1785            HideMouseCursorOrigin::TypingAction => {
 1786                matches!(
 1787                    self.hide_mouse_mode,
 1788                    HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
 1789                )
 1790            }
 1791            HideMouseCursorOrigin::MovementAction => {
 1792                matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
 1793            }
 1794        };
 1795    }
 1796
 1797    pub fn edit_prediction_in_conflict(&self) -> bool {
 1798        if !self.show_edit_predictions_in_menu() {
 1799            return false;
 1800        }
 1801
 1802        let showing_completions = self
 1803            .context_menu
 1804            .borrow()
 1805            .as_ref()
 1806            .map_or(false, |context| {
 1807                matches!(context, CodeContextMenu::Completions(_))
 1808            });
 1809
 1810        showing_completions
 1811            || self.edit_prediction_requires_modifier()
 1812            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1813            // bindings to insert tab characters.
 1814            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 1815    }
 1816
 1817    pub fn accept_edit_prediction_keybind(
 1818        &self,
 1819        window: &Window,
 1820        cx: &App,
 1821    ) -> AcceptEditPredictionBinding {
 1822        let key_context = self.key_context_internal(true, window, cx);
 1823        let in_conflict = self.edit_prediction_in_conflict();
 1824
 1825        AcceptEditPredictionBinding(
 1826            window
 1827                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1828                .into_iter()
 1829                .filter(|binding| {
 1830                    !in_conflict
 1831                        || binding
 1832                            .keystrokes()
 1833                            .first()
 1834                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1835                })
 1836                .rev()
 1837                .min_by_key(|binding| {
 1838                    binding
 1839                        .keystrokes()
 1840                        .first()
 1841                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1842                }),
 1843        )
 1844    }
 1845
 1846    pub fn new_file(
 1847        workspace: &mut Workspace,
 1848        _: &workspace::NewFile,
 1849        window: &mut Window,
 1850        cx: &mut Context<Workspace>,
 1851    ) {
 1852        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1853            "Failed to create buffer",
 1854            window,
 1855            cx,
 1856            |e, _, _| match e.error_code() {
 1857                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1858                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1859                e.error_tag("required").unwrap_or("the latest version")
 1860            )),
 1861                _ => None,
 1862            },
 1863        );
 1864    }
 1865
 1866    pub fn new_in_workspace(
 1867        workspace: &mut Workspace,
 1868        window: &mut Window,
 1869        cx: &mut Context<Workspace>,
 1870    ) -> Task<Result<Entity<Editor>>> {
 1871        let project = workspace.project().clone();
 1872        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1873
 1874        cx.spawn_in(window, async move |workspace, cx| {
 1875            let buffer = create.await?;
 1876            workspace.update_in(cx, |workspace, window, cx| {
 1877                let editor =
 1878                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1879                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1880                editor
 1881            })
 1882        })
 1883    }
 1884
 1885    fn new_file_vertical(
 1886        workspace: &mut Workspace,
 1887        _: &workspace::NewFileSplitVertical,
 1888        window: &mut Window,
 1889        cx: &mut Context<Workspace>,
 1890    ) {
 1891        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1892    }
 1893
 1894    fn new_file_horizontal(
 1895        workspace: &mut Workspace,
 1896        _: &workspace::NewFileSplitHorizontal,
 1897        window: &mut Window,
 1898        cx: &mut Context<Workspace>,
 1899    ) {
 1900        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1901    }
 1902
 1903    fn new_file_in_direction(
 1904        workspace: &mut Workspace,
 1905        direction: SplitDirection,
 1906        window: &mut Window,
 1907        cx: &mut Context<Workspace>,
 1908    ) {
 1909        let project = workspace.project().clone();
 1910        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1911
 1912        cx.spawn_in(window, async move |workspace, cx| {
 1913            let buffer = create.await?;
 1914            workspace.update_in(cx, move |workspace, window, cx| {
 1915                workspace.split_item(
 1916                    direction,
 1917                    Box::new(
 1918                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1919                    ),
 1920                    window,
 1921                    cx,
 1922                )
 1923            })?;
 1924            anyhow::Ok(())
 1925        })
 1926        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1927            match e.error_code() {
 1928                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1929                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1930                e.error_tag("required").unwrap_or("the latest version")
 1931            )),
 1932                _ => None,
 1933            }
 1934        });
 1935    }
 1936
 1937    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1938        self.leader_peer_id
 1939    }
 1940
 1941    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1942        &self.buffer
 1943    }
 1944
 1945    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1946        self.workspace.as_ref()?.0.upgrade()
 1947    }
 1948
 1949    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1950        self.buffer().read(cx).title(cx)
 1951    }
 1952
 1953    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1954        let git_blame_gutter_max_author_length = self
 1955            .render_git_blame_gutter(cx)
 1956            .then(|| {
 1957                if let Some(blame) = self.blame.as_ref() {
 1958                    let max_author_length =
 1959                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1960                    Some(max_author_length)
 1961                } else {
 1962                    None
 1963                }
 1964            })
 1965            .flatten();
 1966
 1967        EditorSnapshot {
 1968            mode: self.mode,
 1969            show_gutter: self.show_gutter,
 1970            show_line_numbers: self.show_line_numbers,
 1971            show_git_diff_gutter: self.show_git_diff_gutter,
 1972            show_code_actions: self.show_code_actions,
 1973            show_runnables: self.show_runnables,
 1974            show_breakpoints: self.show_breakpoints,
 1975            git_blame_gutter_max_author_length,
 1976            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1977            scroll_anchor: self.scroll_manager.anchor(),
 1978            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1979            placeholder_text: self.placeholder_text.clone(),
 1980            is_focused: self.focus_handle.is_focused(window),
 1981            current_line_highlight: self
 1982                .current_line_highlight
 1983                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1984            gutter_hovered: self.gutter_hovered,
 1985        }
 1986    }
 1987
 1988    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1989        self.buffer.read(cx).language_at(point, cx)
 1990    }
 1991
 1992    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1993        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1994    }
 1995
 1996    pub fn active_excerpt(
 1997        &self,
 1998        cx: &App,
 1999    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 2000        self.buffer
 2001            .read(cx)
 2002            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2003    }
 2004
 2005    pub fn mode(&self) -> EditorMode {
 2006        self.mode
 2007    }
 2008
 2009    pub fn set_mode(&mut self, mode: EditorMode) {
 2010        self.mode = mode;
 2011    }
 2012
 2013    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2014        self.collaboration_hub.as_deref()
 2015    }
 2016
 2017    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2018        self.collaboration_hub = Some(hub);
 2019    }
 2020
 2021    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 2022        self.in_project_search = in_project_search;
 2023    }
 2024
 2025    pub fn set_custom_context_menu(
 2026        &mut self,
 2027        f: impl 'static
 2028        + Fn(
 2029            &mut Self,
 2030            DisplayPoint,
 2031            &mut Window,
 2032            &mut Context<Self>,
 2033        ) -> Option<Entity<ui::ContextMenu>>,
 2034    ) {
 2035        self.custom_context_menu = Some(Box::new(f))
 2036    }
 2037
 2038    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2039        self.completion_provider = provider;
 2040    }
 2041
 2042    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2043        self.semantics_provider.clone()
 2044    }
 2045
 2046    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2047        self.semantics_provider = provider;
 2048    }
 2049
 2050    pub fn set_edit_prediction_provider<T>(
 2051        &mut self,
 2052        provider: Option<Entity<T>>,
 2053        window: &mut Window,
 2054        cx: &mut Context<Self>,
 2055    ) where
 2056        T: EditPredictionProvider,
 2057    {
 2058        self.edit_prediction_provider =
 2059            provider.map(|provider| RegisteredInlineCompletionProvider {
 2060                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 2061                    if this.focus_handle.is_focused(window) {
 2062                        this.update_visible_inline_completion(window, cx);
 2063                    }
 2064                }),
 2065                provider: Arc::new(provider),
 2066            });
 2067        self.update_edit_prediction_settings(cx);
 2068        self.refresh_inline_completion(false, false, window, cx);
 2069    }
 2070
 2071    pub fn placeholder_text(&self) -> Option<&str> {
 2072        self.placeholder_text.as_deref()
 2073    }
 2074
 2075    pub fn set_placeholder_text(
 2076        &mut self,
 2077        placeholder_text: impl Into<Arc<str>>,
 2078        cx: &mut Context<Self>,
 2079    ) {
 2080        let placeholder_text = Some(placeholder_text.into());
 2081        if self.placeholder_text != placeholder_text {
 2082            self.placeholder_text = placeholder_text;
 2083            cx.notify();
 2084        }
 2085    }
 2086
 2087    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 2088        self.cursor_shape = cursor_shape;
 2089
 2090        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2091        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2092
 2093        cx.notify();
 2094    }
 2095
 2096    pub fn set_current_line_highlight(
 2097        &mut self,
 2098        current_line_highlight: Option<CurrentLineHighlight>,
 2099    ) {
 2100        self.current_line_highlight = current_line_highlight;
 2101    }
 2102
 2103    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2104        self.collapse_matches = collapse_matches;
 2105    }
 2106
 2107    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 2108        let buffers = self.buffer.read(cx).all_buffers();
 2109        let Some(project) = self.project.as_ref() else {
 2110            return;
 2111        };
 2112        project.update(cx, |project, cx| {
 2113            for buffer in buffers {
 2114                self.registered_buffers
 2115                    .entry(buffer.read(cx).remote_id())
 2116                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 2117            }
 2118        })
 2119    }
 2120
 2121    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2122        if self.collapse_matches {
 2123            return range.start..range.start;
 2124        }
 2125        range.clone()
 2126    }
 2127
 2128    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 2129        if self.display_map.read(cx).clip_at_line_ends != clip {
 2130            self.display_map
 2131                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2132        }
 2133    }
 2134
 2135    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2136        self.input_enabled = input_enabled;
 2137    }
 2138
 2139    pub fn set_inline_completions_hidden_for_vim_mode(
 2140        &mut self,
 2141        hidden: bool,
 2142        window: &mut Window,
 2143        cx: &mut Context<Self>,
 2144    ) {
 2145        if hidden != self.inline_completions_hidden_for_vim_mode {
 2146            self.inline_completions_hidden_for_vim_mode = hidden;
 2147            if hidden {
 2148                self.update_visible_inline_completion(window, cx);
 2149            } else {
 2150                self.refresh_inline_completion(true, false, window, cx);
 2151            }
 2152        }
 2153    }
 2154
 2155    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 2156        self.menu_inline_completions_policy = value;
 2157    }
 2158
 2159    pub fn set_autoindent(&mut self, autoindent: bool) {
 2160        if autoindent {
 2161            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2162        } else {
 2163            self.autoindent_mode = None;
 2164        }
 2165    }
 2166
 2167    pub fn read_only(&self, cx: &App) -> bool {
 2168        self.read_only || self.buffer.read(cx).read_only()
 2169    }
 2170
 2171    pub fn set_read_only(&mut self, read_only: bool) {
 2172        self.read_only = read_only;
 2173    }
 2174
 2175    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2176        self.use_autoclose = autoclose;
 2177    }
 2178
 2179    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2180        self.use_auto_surround = auto_surround;
 2181    }
 2182
 2183    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2184        self.auto_replace_emoji_shortcode = auto_replace;
 2185    }
 2186
 2187    pub fn toggle_edit_predictions(
 2188        &mut self,
 2189        _: &ToggleEditPrediction,
 2190        window: &mut Window,
 2191        cx: &mut Context<Self>,
 2192    ) {
 2193        if self.show_inline_completions_override.is_some() {
 2194            self.set_show_edit_predictions(None, window, cx);
 2195        } else {
 2196            let show_edit_predictions = !self.edit_predictions_enabled();
 2197            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 2198        }
 2199    }
 2200
 2201    pub fn set_show_edit_predictions(
 2202        &mut self,
 2203        show_edit_predictions: Option<bool>,
 2204        window: &mut Window,
 2205        cx: &mut Context<Self>,
 2206    ) {
 2207        self.show_inline_completions_override = show_edit_predictions;
 2208        self.update_edit_prediction_settings(cx);
 2209
 2210        if let Some(false) = show_edit_predictions {
 2211            self.discard_inline_completion(false, cx);
 2212        } else {
 2213            self.refresh_inline_completion(false, true, window, cx);
 2214        }
 2215    }
 2216
 2217    fn inline_completions_disabled_in_scope(
 2218        &self,
 2219        buffer: &Entity<Buffer>,
 2220        buffer_position: language::Anchor,
 2221        cx: &App,
 2222    ) -> bool {
 2223        let snapshot = buffer.read(cx).snapshot();
 2224        let settings = snapshot.settings_at(buffer_position, cx);
 2225
 2226        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2227            return false;
 2228        };
 2229
 2230        scope.override_name().map_or(false, |scope_name| {
 2231            settings
 2232                .edit_predictions_disabled_in
 2233                .iter()
 2234                .any(|s| s == scope_name)
 2235        })
 2236    }
 2237
 2238    pub fn set_use_modal_editing(&mut self, to: bool) {
 2239        self.use_modal_editing = to;
 2240    }
 2241
 2242    pub fn use_modal_editing(&self) -> bool {
 2243        self.use_modal_editing
 2244    }
 2245
 2246    fn selections_did_change(
 2247        &mut self,
 2248        local: bool,
 2249        old_cursor_position: &Anchor,
 2250        show_completions: bool,
 2251        window: &mut Window,
 2252        cx: &mut Context<Self>,
 2253    ) {
 2254        window.invalidate_character_coordinates();
 2255
 2256        // Copy selections to primary selection buffer
 2257        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2258        if local {
 2259            let selections = self.selections.all::<usize>(cx);
 2260            let buffer_handle = self.buffer.read(cx).read(cx);
 2261
 2262            let mut text = String::new();
 2263            for (index, selection) in selections.iter().enumerate() {
 2264                let text_for_selection = buffer_handle
 2265                    .text_for_range(selection.start..selection.end)
 2266                    .collect::<String>();
 2267
 2268                text.push_str(&text_for_selection);
 2269                if index != selections.len() - 1 {
 2270                    text.push('\n');
 2271                }
 2272            }
 2273
 2274            if !text.is_empty() {
 2275                cx.write_to_primary(ClipboardItem::new_string(text));
 2276            }
 2277        }
 2278
 2279        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2280            self.buffer.update(cx, |buffer, cx| {
 2281                buffer.set_active_selections(
 2282                    &self.selections.disjoint_anchors(),
 2283                    self.selections.line_mode,
 2284                    self.cursor_shape,
 2285                    cx,
 2286                )
 2287            });
 2288        }
 2289        let display_map = self
 2290            .display_map
 2291            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2292        let buffer = &display_map.buffer_snapshot;
 2293        self.add_selections_state = None;
 2294        self.select_next_state = None;
 2295        self.select_prev_state = None;
 2296        self.select_syntax_node_history.try_clear();
 2297        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2298        self.snippet_stack
 2299            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2300        self.take_rename(false, window, cx);
 2301
 2302        let new_cursor_position = self.selections.newest_anchor().head();
 2303
 2304        self.push_to_nav_history(
 2305            *old_cursor_position,
 2306            Some(new_cursor_position.to_point(buffer)),
 2307            false,
 2308            cx,
 2309        );
 2310
 2311        if local {
 2312            let new_cursor_position = self.selections.newest_anchor().head();
 2313            let mut context_menu = self.context_menu.borrow_mut();
 2314            let completion_menu = match context_menu.as_ref() {
 2315                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2316                _ => {
 2317                    *context_menu = None;
 2318                    None
 2319                }
 2320            };
 2321            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2322                if !self.registered_buffers.contains_key(&buffer_id) {
 2323                    if let Some(project) = self.project.as_ref() {
 2324                        project.update(cx, |project, cx| {
 2325                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2326                                return;
 2327                            };
 2328                            self.registered_buffers.insert(
 2329                                buffer_id,
 2330                                project.register_buffer_with_language_servers(&buffer, cx),
 2331                            );
 2332                        })
 2333                    }
 2334                }
 2335            }
 2336
 2337            if let Some(completion_menu) = completion_menu {
 2338                let cursor_position = new_cursor_position.to_offset(buffer);
 2339                let (word_range, kind) =
 2340                    buffer.surrounding_word(completion_menu.initial_position, true);
 2341                if kind == Some(CharKind::Word)
 2342                    && word_range.to_inclusive().contains(&cursor_position)
 2343                {
 2344                    let mut completion_menu = completion_menu.clone();
 2345                    drop(context_menu);
 2346
 2347                    let query = Self::completion_query(buffer, cursor_position);
 2348                    cx.spawn(async move |this, cx| {
 2349                        completion_menu
 2350                            .filter(query.as_deref(), cx.background_executor().clone())
 2351                            .await;
 2352
 2353                        this.update(cx, |this, cx| {
 2354                            let mut context_menu = this.context_menu.borrow_mut();
 2355                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2356                            else {
 2357                                return;
 2358                            };
 2359
 2360                            if menu.id > completion_menu.id {
 2361                                return;
 2362                            }
 2363
 2364                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2365                            drop(context_menu);
 2366                            cx.notify();
 2367                        })
 2368                    })
 2369                    .detach();
 2370
 2371                    if show_completions {
 2372                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2373                    }
 2374                } else {
 2375                    drop(context_menu);
 2376                    self.hide_context_menu(window, cx);
 2377                }
 2378            } else {
 2379                drop(context_menu);
 2380            }
 2381
 2382            hide_hover(self, cx);
 2383
 2384            if old_cursor_position.to_display_point(&display_map).row()
 2385                != new_cursor_position.to_display_point(&display_map).row()
 2386            {
 2387                self.available_code_actions.take();
 2388            }
 2389            self.refresh_code_actions(window, cx);
 2390            self.refresh_document_highlights(cx);
 2391            self.refresh_selected_text_highlights(window, cx);
 2392            refresh_matching_bracket_highlights(self, window, cx);
 2393            self.update_visible_inline_completion(window, cx);
 2394            self.edit_prediction_requires_modifier_in_indent_conflict = true;
 2395            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2396            if self.git_blame_inline_enabled {
 2397                self.start_inline_blame_timer(window, cx);
 2398            }
 2399        }
 2400
 2401        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2402        cx.emit(EditorEvent::SelectionsChanged { local });
 2403
 2404        let selections = &self.selections.disjoint;
 2405        if selections.len() == 1 {
 2406            cx.emit(SearchEvent::ActiveMatchChanged)
 2407        }
 2408        if local {
 2409            if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
 2410                let inmemory_selections = selections
 2411                    .iter()
 2412                    .map(|s| {
 2413                        text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
 2414                            ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
 2415                    })
 2416                    .collect();
 2417                self.update_restoration_data(cx, |data| {
 2418                    data.selections = inmemory_selections;
 2419                });
 2420
 2421                if WorkspaceSettings::get(None, cx).restore_on_startup
 2422                    != RestoreOnStartupBehavior::None
 2423                {
 2424                    if let Some(workspace_id) =
 2425                        self.workspace.as_ref().and_then(|workspace| workspace.1)
 2426                    {
 2427                        let snapshot = self.buffer().read(cx).snapshot(cx);
 2428                        let selections = selections.clone();
 2429                        let background_executor = cx.background_executor().clone();
 2430                        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2431                        self.serialize_selections = cx.background_spawn(async move {
 2432                    background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2433                    let db_selections = selections
 2434                        .iter()
 2435                        .map(|selection| {
 2436                            (
 2437                                selection.start.to_offset(&snapshot),
 2438                                selection.end.to_offset(&snapshot),
 2439                            )
 2440                        })
 2441                        .collect();
 2442
 2443                    DB.save_editor_selections(editor_id, workspace_id, db_selections)
 2444                        .await
 2445                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2446                        .log_err();
 2447                });
 2448                    }
 2449                }
 2450            }
 2451        }
 2452
 2453        cx.notify();
 2454    }
 2455
 2456    fn folds_did_change(&mut self, cx: &mut Context<Self>) {
 2457        use text::ToOffset as _;
 2458        use text::ToPoint as _;
 2459
 2460        if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
 2461            return;
 2462        }
 2463
 2464        let Some(singleton) = self.buffer().read(cx).as_singleton() else {
 2465            return;
 2466        };
 2467
 2468        let snapshot = singleton.read(cx).snapshot();
 2469        let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
 2470            let display_snapshot = display_map.snapshot(cx);
 2471
 2472            display_snapshot
 2473                .folds_in_range(0..display_snapshot.buffer_snapshot.len())
 2474                .map(|fold| {
 2475                    fold.range.start.text_anchor.to_point(&snapshot)
 2476                        ..fold.range.end.text_anchor.to_point(&snapshot)
 2477                })
 2478                .collect()
 2479        });
 2480        self.update_restoration_data(cx, |data| {
 2481            data.folds = inmemory_folds;
 2482        });
 2483
 2484        let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
 2485            return;
 2486        };
 2487        let background_executor = cx.background_executor().clone();
 2488        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2489        let db_folds = self.display_map.update(cx, |display_map, cx| {
 2490            display_map
 2491                .snapshot(cx)
 2492                .folds_in_range(0..snapshot.len())
 2493                .map(|fold| {
 2494                    (
 2495                        fold.range.start.text_anchor.to_offset(&snapshot),
 2496                        fold.range.end.text_anchor.to_offset(&snapshot),
 2497                    )
 2498                })
 2499                .collect()
 2500        });
 2501        self.serialize_folds = cx.background_spawn(async move {
 2502            background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2503            DB.save_editor_folds(editor_id, workspace_id, db_folds)
 2504                .await
 2505                .with_context(|| {
 2506                    format!(
 2507                        "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
 2508                    )
 2509                })
 2510                .log_err();
 2511        });
 2512    }
 2513
 2514    pub fn sync_selections(
 2515        &mut self,
 2516        other: Entity<Editor>,
 2517        cx: &mut Context<Self>,
 2518    ) -> gpui::Subscription {
 2519        let other_selections = other.read(cx).selections.disjoint.to_vec();
 2520        self.selections.change_with(cx, |selections| {
 2521            selections.select_anchors(other_selections);
 2522        });
 2523
 2524        let other_subscription =
 2525            cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
 2526                EditorEvent::SelectionsChanged { local: true } => {
 2527                    let other_selections = other.read(cx).selections.disjoint.to_vec();
 2528                    if other_selections.is_empty() {
 2529                        return;
 2530                    }
 2531                    this.selections.change_with(cx, |selections| {
 2532                        selections.select_anchors(other_selections);
 2533                    });
 2534                }
 2535                _ => {}
 2536            });
 2537
 2538        let this_subscription =
 2539            cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
 2540                EditorEvent::SelectionsChanged { local: true } => {
 2541                    let these_selections = this.selections.disjoint.to_vec();
 2542                    if these_selections.is_empty() {
 2543                        return;
 2544                    }
 2545                    other.update(cx, |other_editor, cx| {
 2546                        other_editor.selections.change_with(cx, |selections| {
 2547                            selections.select_anchors(these_selections);
 2548                        })
 2549                    });
 2550                }
 2551                _ => {}
 2552            });
 2553
 2554        Subscription::join(other_subscription, this_subscription)
 2555    }
 2556
 2557    pub fn change_selections<R>(
 2558        &mut self,
 2559        autoscroll: Option<Autoscroll>,
 2560        window: &mut Window,
 2561        cx: &mut Context<Self>,
 2562        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2563    ) -> R {
 2564        self.change_selections_inner(autoscroll, true, window, cx, change)
 2565    }
 2566
 2567    fn change_selections_inner<R>(
 2568        &mut self,
 2569        autoscroll: Option<Autoscroll>,
 2570        request_completions: bool,
 2571        window: &mut Window,
 2572        cx: &mut Context<Self>,
 2573        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2574    ) -> R {
 2575        let old_cursor_position = self.selections.newest_anchor().head();
 2576        self.push_to_selection_history();
 2577
 2578        let (changed, result) = self.selections.change_with(cx, change);
 2579
 2580        if changed {
 2581            if let Some(autoscroll) = autoscroll {
 2582                self.request_autoscroll(autoscroll, cx);
 2583            }
 2584            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2585
 2586            if self.should_open_signature_help_automatically(
 2587                &old_cursor_position,
 2588                self.signature_help_state.backspace_pressed(),
 2589                cx,
 2590            ) {
 2591                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2592            }
 2593            self.signature_help_state.set_backspace_pressed(false);
 2594        }
 2595
 2596        result
 2597    }
 2598
 2599    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2600    where
 2601        I: IntoIterator<Item = (Range<S>, T)>,
 2602        S: ToOffset,
 2603        T: Into<Arc<str>>,
 2604    {
 2605        if self.read_only(cx) {
 2606            return;
 2607        }
 2608
 2609        self.buffer
 2610            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2611    }
 2612
 2613    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2614    where
 2615        I: IntoIterator<Item = (Range<S>, T)>,
 2616        S: ToOffset,
 2617        T: Into<Arc<str>>,
 2618    {
 2619        if self.read_only(cx) {
 2620            return;
 2621        }
 2622
 2623        self.buffer.update(cx, |buffer, cx| {
 2624            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2625        });
 2626    }
 2627
 2628    pub fn edit_with_block_indent<I, S, T>(
 2629        &mut self,
 2630        edits: I,
 2631        original_indent_columns: Vec<Option<u32>>,
 2632        cx: &mut Context<Self>,
 2633    ) where
 2634        I: IntoIterator<Item = (Range<S>, T)>,
 2635        S: ToOffset,
 2636        T: Into<Arc<str>>,
 2637    {
 2638        if self.read_only(cx) {
 2639            return;
 2640        }
 2641
 2642        self.buffer.update(cx, |buffer, cx| {
 2643            buffer.edit(
 2644                edits,
 2645                Some(AutoindentMode::Block {
 2646                    original_indent_columns,
 2647                }),
 2648                cx,
 2649            )
 2650        });
 2651    }
 2652
 2653    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2654        self.hide_context_menu(window, cx);
 2655
 2656        match phase {
 2657            SelectPhase::Begin {
 2658                position,
 2659                add,
 2660                click_count,
 2661            } => self.begin_selection(position, add, click_count, window, cx),
 2662            SelectPhase::BeginColumnar {
 2663                position,
 2664                goal_column,
 2665                reset,
 2666            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2667            SelectPhase::Extend {
 2668                position,
 2669                click_count,
 2670            } => self.extend_selection(position, click_count, window, cx),
 2671            SelectPhase::Update {
 2672                position,
 2673                goal_column,
 2674                scroll_delta,
 2675            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2676            SelectPhase::End => self.end_selection(window, cx),
 2677        }
 2678    }
 2679
 2680    fn extend_selection(
 2681        &mut self,
 2682        position: DisplayPoint,
 2683        click_count: usize,
 2684        window: &mut Window,
 2685        cx: &mut Context<Self>,
 2686    ) {
 2687        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2688        let tail = self.selections.newest::<usize>(cx).tail();
 2689        self.begin_selection(position, false, click_count, window, cx);
 2690
 2691        let position = position.to_offset(&display_map, Bias::Left);
 2692        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2693
 2694        let mut pending_selection = self
 2695            .selections
 2696            .pending_anchor()
 2697            .expect("extend_selection not called with pending selection");
 2698        if position >= tail {
 2699            pending_selection.start = tail_anchor;
 2700        } else {
 2701            pending_selection.end = tail_anchor;
 2702            pending_selection.reversed = true;
 2703        }
 2704
 2705        let mut pending_mode = self.selections.pending_mode().unwrap();
 2706        match &mut pending_mode {
 2707            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2708            _ => {}
 2709        }
 2710
 2711        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2712            s.set_pending(pending_selection, pending_mode)
 2713        });
 2714    }
 2715
 2716    fn begin_selection(
 2717        &mut self,
 2718        position: DisplayPoint,
 2719        add: bool,
 2720        click_count: usize,
 2721        window: &mut Window,
 2722        cx: &mut Context<Self>,
 2723    ) {
 2724        if !self.focus_handle.is_focused(window) {
 2725            self.last_focused_descendant = None;
 2726            window.focus(&self.focus_handle);
 2727        }
 2728
 2729        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2730        let buffer = &display_map.buffer_snapshot;
 2731        let newest_selection = self.selections.newest_anchor().clone();
 2732        let position = display_map.clip_point(position, Bias::Left);
 2733
 2734        let start;
 2735        let end;
 2736        let mode;
 2737        let mut auto_scroll;
 2738        match click_count {
 2739            1 => {
 2740                start = buffer.anchor_before(position.to_point(&display_map));
 2741                end = start;
 2742                mode = SelectMode::Character;
 2743                auto_scroll = true;
 2744            }
 2745            2 => {
 2746                let range = movement::surrounding_word(&display_map, position);
 2747                start = buffer.anchor_before(range.start.to_point(&display_map));
 2748                end = buffer.anchor_before(range.end.to_point(&display_map));
 2749                mode = SelectMode::Word(start..end);
 2750                auto_scroll = true;
 2751            }
 2752            3 => {
 2753                let position = display_map
 2754                    .clip_point(position, Bias::Left)
 2755                    .to_point(&display_map);
 2756                let line_start = display_map.prev_line_boundary(position).0;
 2757                let next_line_start = buffer.clip_point(
 2758                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2759                    Bias::Left,
 2760                );
 2761                start = buffer.anchor_before(line_start);
 2762                end = buffer.anchor_before(next_line_start);
 2763                mode = SelectMode::Line(start..end);
 2764                auto_scroll = true;
 2765            }
 2766            _ => {
 2767                start = buffer.anchor_before(0);
 2768                end = buffer.anchor_before(buffer.len());
 2769                mode = SelectMode::All;
 2770                auto_scroll = false;
 2771            }
 2772        }
 2773        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2774
 2775        let point_to_delete: Option<usize> = {
 2776            let selected_points: Vec<Selection<Point>> =
 2777                self.selections.disjoint_in_range(start..end, cx);
 2778
 2779            if !add || click_count > 1 {
 2780                None
 2781            } else if !selected_points.is_empty() {
 2782                Some(selected_points[0].id)
 2783            } else {
 2784                let clicked_point_already_selected =
 2785                    self.selections.disjoint.iter().find(|selection| {
 2786                        selection.start.to_point(buffer) == start.to_point(buffer)
 2787                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2788                    });
 2789
 2790                clicked_point_already_selected.map(|selection| selection.id)
 2791            }
 2792        };
 2793
 2794        let selections_count = self.selections.count();
 2795
 2796        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2797            if let Some(point_to_delete) = point_to_delete {
 2798                s.delete(point_to_delete);
 2799
 2800                if selections_count == 1 {
 2801                    s.set_pending_anchor_range(start..end, mode);
 2802                }
 2803            } else {
 2804                if !add {
 2805                    s.clear_disjoint();
 2806                } else if click_count > 1 {
 2807                    s.delete(newest_selection.id)
 2808                }
 2809
 2810                s.set_pending_anchor_range(start..end, mode);
 2811            }
 2812        });
 2813    }
 2814
 2815    fn begin_columnar_selection(
 2816        &mut self,
 2817        position: DisplayPoint,
 2818        goal_column: u32,
 2819        reset: bool,
 2820        window: &mut Window,
 2821        cx: &mut Context<Self>,
 2822    ) {
 2823        if !self.focus_handle.is_focused(window) {
 2824            self.last_focused_descendant = None;
 2825            window.focus(&self.focus_handle);
 2826        }
 2827
 2828        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2829
 2830        if reset {
 2831            let pointer_position = display_map
 2832                .buffer_snapshot
 2833                .anchor_before(position.to_point(&display_map));
 2834
 2835            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2836                s.clear_disjoint();
 2837                s.set_pending_anchor_range(
 2838                    pointer_position..pointer_position,
 2839                    SelectMode::Character,
 2840                );
 2841            });
 2842        }
 2843
 2844        let tail = self.selections.newest::<Point>(cx).tail();
 2845        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2846
 2847        if !reset {
 2848            self.select_columns(
 2849                tail.to_display_point(&display_map),
 2850                position,
 2851                goal_column,
 2852                &display_map,
 2853                window,
 2854                cx,
 2855            );
 2856        }
 2857    }
 2858
 2859    fn update_selection(
 2860        &mut self,
 2861        position: DisplayPoint,
 2862        goal_column: u32,
 2863        scroll_delta: gpui::Point<f32>,
 2864        window: &mut Window,
 2865        cx: &mut Context<Self>,
 2866    ) {
 2867        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2868
 2869        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2870            let tail = tail.to_display_point(&display_map);
 2871            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2872        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2873            let buffer = self.buffer.read(cx).snapshot(cx);
 2874            let head;
 2875            let tail;
 2876            let mode = self.selections.pending_mode().unwrap();
 2877            match &mode {
 2878                SelectMode::Character => {
 2879                    head = position.to_point(&display_map);
 2880                    tail = pending.tail().to_point(&buffer);
 2881                }
 2882                SelectMode::Word(original_range) => {
 2883                    let original_display_range = original_range.start.to_display_point(&display_map)
 2884                        ..original_range.end.to_display_point(&display_map);
 2885                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2886                        ..original_display_range.end.to_point(&display_map);
 2887                    if movement::is_inside_word(&display_map, position)
 2888                        || original_display_range.contains(&position)
 2889                    {
 2890                        let word_range = movement::surrounding_word(&display_map, position);
 2891                        if word_range.start < original_display_range.start {
 2892                            head = word_range.start.to_point(&display_map);
 2893                        } else {
 2894                            head = word_range.end.to_point(&display_map);
 2895                        }
 2896                    } else {
 2897                        head = position.to_point(&display_map);
 2898                    }
 2899
 2900                    if head <= original_buffer_range.start {
 2901                        tail = original_buffer_range.end;
 2902                    } else {
 2903                        tail = original_buffer_range.start;
 2904                    }
 2905                }
 2906                SelectMode::Line(original_range) => {
 2907                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2908
 2909                    let position = display_map
 2910                        .clip_point(position, Bias::Left)
 2911                        .to_point(&display_map);
 2912                    let line_start = display_map.prev_line_boundary(position).0;
 2913                    let next_line_start = buffer.clip_point(
 2914                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2915                        Bias::Left,
 2916                    );
 2917
 2918                    if line_start < original_range.start {
 2919                        head = line_start
 2920                    } else {
 2921                        head = next_line_start
 2922                    }
 2923
 2924                    if head <= original_range.start {
 2925                        tail = original_range.end;
 2926                    } else {
 2927                        tail = original_range.start;
 2928                    }
 2929                }
 2930                SelectMode::All => {
 2931                    return;
 2932                }
 2933            };
 2934
 2935            if head < tail {
 2936                pending.start = buffer.anchor_before(head);
 2937                pending.end = buffer.anchor_before(tail);
 2938                pending.reversed = true;
 2939            } else {
 2940                pending.start = buffer.anchor_before(tail);
 2941                pending.end = buffer.anchor_before(head);
 2942                pending.reversed = false;
 2943            }
 2944
 2945            self.change_selections(None, window, cx, |s| {
 2946                s.set_pending(pending, mode);
 2947            });
 2948        } else {
 2949            log::error!("update_selection dispatched with no pending selection");
 2950            return;
 2951        }
 2952
 2953        self.apply_scroll_delta(scroll_delta, window, cx);
 2954        cx.notify();
 2955    }
 2956
 2957    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2958        self.columnar_selection_tail.take();
 2959        if self.selections.pending_anchor().is_some() {
 2960            let selections = self.selections.all::<usize>(cx);
 2961            self.change_selections(None, window, cx, |s| {
 2962                s.select(selections);
 2963                s.clear_pending();
 2964            });
 2965        }
 2966    }
 2967
 2968    fn select_columns(
 2969        &mut self,
 2970        tail: DisplayPoint,
 2971        head: DisplayPoint,
 2972        goal_column: u32,
 2973        display_map: &DisplaySnapshot,
 2974        window: &mut Window,
 2975        cx: &mut Context<Self>,
 2976    ) {
 2977        let start_row = cmp::min(tail.row(), head.row());
 2978        let end_row = cmp::max(tail.row(), head.row());
 2979        let start_column = cmp::min(tail.column(), goal_column);
 2980        let end_column = cmp::max(tail.column(), goal_column);
 2981        let reversed = start_column < tail.column();
 2982
 2983        let selection_ranges = (start_row.0..=end_row.0)
 2984            .map(DisplayRow)
 2985            .filter_map(|row| {
 2986                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2987                    let start = display_map
 2988                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2989                        .to_point(display_map);
 2990                    let end = display_map
 2991                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2992                        .to_point(display_map);
 2993                    if reversed {
 2994                        Some(end..start)
 2995                    } else {
 2996                        Some(start..end)
 2997                    }
 2998                } else {
 2999                    None
 3000                }
 3001            })
 3002            .collect::<Vec<_>>();
 3003
 3004        self.change_selections(None, window, cx, |s| {
 3005            s.select_ranges(selection_ranges);
 3006        });
 3007        cx.notify();
 3008    }
 3009
 3010    pub fn has_pending_nonempty_selection(&self) -> bool {
 3011        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3012            Some(Selection { start, end, .. }) => start != end,
 3013            None => false,
 3014        };
 3015
 3016        pending_nonempty_selection
 3017            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3018    }
 3019
 3020    pub fn has_pending_selection(&self) -> bool {
 3021        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3022    }
 3023
 3024    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 3025        self.selection_mark_mode = false;
 3026
 3027        if self.clear_expanded_diff_hunks(cx) {
 3028            cx.notify();
 3029            return;
 3030        }
 3031        if self.dismiss_menus_and_popups(true, window, cx) {
 3032            return;
 3033        }
 3034
 3035        if self.mode.is_full()
 3036            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 3037        {
 3038            return;
 3039        }
 3040
 3041        cx.propagate();
 3042    }
 3043
 3044    pub fn dismiss_menus_and_popups(
 3045        &mut self,
 3046        is_user_requested: bool,
 3047        window: &mut Window,
 3048        cx: &mut Context<Self>,
 3049    ) -> bool {
 3050        if self.take_rename(false, window, cx).is_some() {
 3051            return true;
 3052        }
 3053
 3054        if hide_hover(self, cx) {
 3055            return true;
 3056        }
 3057
 3058        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3059            return true;
 3060        }
 3061
 3062        if self.hide_context_menu(window, cx).is_some() {
 3063            return true;
 3064        }
 3065
 3066        if self.mouse_context_menu.take().is_some() {
 3067            return true;
 3068        }
 3069
 3070        if is_user_requested && self.discard_inline_completion(true, cx) {
 3071            return true;
 3072        }
 3073
 3074        if self.snippet_stack.pop().is_some() {
 3075            return true;
 3076        }
 3077
 3078        if self.mode.is_full() && self.active_diagnostics.is_some() {
 3079            self.dismiss_diagnostics(cx);
 3080            return true;
 3081        }
 3082
 3083        false
 3084    }
 3085
 3086    fn linked_editing_ranges_for(
 3087        &self,
 3088        selection: Range<text::Anchor>,
 3089        cx: &App,
 3090    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 3091        if self.linked_edit_ranges.is_empty() {
 3092            return None;
 3093        }
 3094        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3095            selection.end.buffer_id.and_then(|end_buffer_id| {
 3096                if selection.start.buffer_id != Some(end_buffer_id) {
 3097                    return None;
 3098                }
 3099                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3100                let snapshot = buffer.read(cx).snapshot();
 3101                self.linked_edit_ranges
 3102                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3103                    .map(|ranges| (ranges, snapshot, buffer))
 3104            })?;
 3105        use text::ToOffset as TO;
 3106        // find offset from the start of current range to current cursor position
 3107        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3108
 3109        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3110        let start_difference = start_offset - start_byte_offset;
 3111        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3112        let end_difference = end_offset - start_byte_offset;
 3113        // Current range has associated linked ranges.
 3114        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3115        for range in linked_ranges.iter() {
 3116            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3117            let end_offset = start_offset + end_difference;
 3118            let start_offset = start_offset + start_difference;
 3119            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3120                continue;
 3121            }
 3122            if self.selections.disjoint_anchor_ranges().any(|s| {
 3123                if s.start.buffer_id != selection.start.buffer_id
 3124                    || s.end.buffer_id != selection.end.buffer_id
 3125                {
 3126                    return false;
 3127                }
 3128                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3129                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3130            }) {
 3131                continue;
 3132            }
 3133            let start = buffer_snapshot.anchor_after(start_offset);
 3134            let end = buffer_snapshot.anchor_after(end_offset);
 3135            linked_edits
 3136                .entry(buffer.clone())
 3137                .or_default()
 3138                .push(start..end);
 3139        }
 3140        Some(linked_edits)
 3141    }
 3142
 3143    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3144        let text: Arc<str> = text.into();
 3145
 3146        if self.read_only(cx) {
 3147            return;
 3148        }
 3149
 3150        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3151
 3152        let selections = self.selections.all_adjusted(cx);
 3153        let mut bracket_inserted = false;
 3154        let mut edits = Vec::new();
 3155        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3156        let mut new_selections = Vec::with_capacity(selections.len());
 3157        let mut new_autoclose_regions = Vec::new();
 3158        let snapshot = self.buffer.read(cx).read(cx);
 3159        let mut clear_linked_edit_ranges = false;
 3160
 3161        for (selection, autoclose_region) in
 3162            self.selections_with_autoclose_regions(selections, &snapshot)
 3163        {
 3164            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3165                // Determine if the inserted text matches the opening or closing
 3166                // bracket of any of this language's bracket pairs.
 3167                let mut bracket_pair = None;
 3168                let mut is_bracket_pair_start = false;
 3169                let mut is_bracket_pair_end = false;
 3170                if !text.is_empty() {
 3171                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3172                    //  and they are removing the character that triggered IME popup.
 3173                    for (pair, enabled) in scope.brackets() {
 3174                        if !pair.close && !pair.surround {
 3175                            continue;
 3176                        }
 3177
 3178                        if enabled && pair.start.ends_with(text.as_ref()) {
 3179                            let prefix_len = pair.start.len() - text.len();
 3180                            let preceding_text_matches_prefix = prefix_len == 0
 3181                                || (selection.start.column >= (prefix_len as u32)
 3182                                    && snapshot.contains_str_at(
 3183                                        Point::new(
 3184                                            selection.start.row,
 3185                                            selection.start.column - (prefix_len as u32),
 3186                                        ),
 3187                                        &pair.start[..prefix_len],
 3188                                    ));
 3189                            if preceding_text_matches_prefix {
 3190                                bracket_pair = Some(pair.clone());
 3191                                is_bracket_pair_start = true;
 3192                                break;
 3193                            }
 3194                        }
 3195                        if pair.end.as_str() == text.as_ref() {
 3196                            bracket_pair = Some(pair.clone());
 3197                            is_bracket_pair_end = true;
 3198                            break;
 3199                        }
 3200                    }
 3201                }
 3202
 3203                if let Some(bracket_pair) = bracket_pair {
 3204                    let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
 3205                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3206                    let auto_surround =
 3207                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3208                    if selection.is_empty() {
 3209                        if is_bracket_pair_start {
 3210                            // If the inserted text is a suffix of an opening bracket and the
 3211                            // selection is preceded by the rest of the opening bracket, then
 3212                            // insert the closing bracket.
 3213                            let following_text_allows_autoclose = snapshot
 3214                                .chars_at(selection.start)
 3215                                .next()
 3216                                .map_or(true, |c| scope.should_autoclose_before(c));
 3217
 3218                            let preceding_text_allows_autoclose = selection.start.column == 0
 3219                                || snapshot.reversed_chars_at(selection.start).next().map_or(
 3220                                    true,
 3221                                    |c| {
 3222                                        bracket_pair.start != bracket_pair.end
 3223                                            || !snapshot
 3224                                                .char_classifier_at(selection.start)
 3225                                                .is_word(c)
 3226                                    },
 3227                                );
 3228
 3229                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3230                                && bracket_pair.start.len() == 1
 3231                            {
 3232                                let target = bracket_pair.start.chars().next().unwrap();
 3233                                let current_line_count = snapshot
 3234                                    .reversed_chars_at(selection.start)
 3235                                    .take_while(|&c| c != '\n')
 3236                                    .filter(|&c| c == target)
 3237                                    .count();
 3238                                current_line_count % 2 == 1
 3239                            } else {
 3240                                false
 3241                            };
 3242
 3243                            if autoclose
 3244                                && bracket_pair.close
 3245                                && following_text_allows_autoclose
 3246                                && preceding_text_allows_autoclose
 3247                                && !is_closing_quote
 3248                            {
 3249                                let anchor = snapshot.anchor_before(selection.end);
 3250                                new_selections.push((selection.map(|_| anchor), text.len()));
 3251                                new_autoclose_regions.push((
 3252                                    anchor,
 3253                                    text.len(),
 3254                                    selection.id,
 3255                                    bracket_pair.clone(),
 3256                                ));
 3257                                edits.push((
 3258                                    selection.range(),
 3259                                    format!("{}{}", text, bracket_pair.end).into(),
 3260                                ));
 3261                                bracket_inserted = true;
 3262                                continue;
 3263                            }
 3264                        }
 3265
 3266                        if let Some(region) = autoclose_region {
 3267                            // If the selection is followed by an auto-inserted closing bracket,
 3268                            // then don't insert that closing bracket again; just move the selection
 3269                            // past the closing bracket.
 3270                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3271                                && text.as_ref() == region.pair.end.as_str();
 3272                            if should_skip {
 3273                                let anchor = snapshot.anchor_after(selection.end);
 3274                                new_selections
 3275                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3276                                continue;
 3277                            }
 3278                        }
 3279
 3280                        let always_treat_brackets_as_autoclosed = snapshot
 3281                            .language_settings_at(selection.start, cx)
 3282                            .always_treat_brackets_as_autoclosed;
 3283                        if always_treat_brackets_as_autoclosed
 3284                            && is_bracket_pair_end
 3285                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3286                        {
 3287                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3288                            // and the inserted text is a closing bracket and the selection is followed
 3289                            // by the closing bracket then move the selection past the closing bracket.
 3290                            let anchor = snapshot.anchor_after(selection.end);
 3291                            new_selections.push((selection.map(|_| anchor), text.len()));
 3292                            continue;
 3293                        }
 3294                    }
 3295                    // If an opening bracket is 1 character long and is typed while
 3296                    // text is selected, then surround that text with the bracket pair.
 3297                    else if auto_surround
 3298                        && bracket_pair.surround
 3299                        && is_bracket_pair_start
 3300                        && bracket_pair.start.chars().count() == 1
 3301                    {
 3302                        edits.push((selection.start..selection.start, text.clone()));
 3303                        edits.push((
 3304                            selection.end..selection.end,
 3305                            bracket_pair.end.as_str().into(),
 3306                        ));
 3307                        bracket_inserted = true;
 3308                        new_selections.push((
 3309                            Selection {
 3310                                id: selection.id,
 3311                                start: snapshot.anchor_after(selection.start),
 3312                                end: snapshot.anchor_before(selection.end),
 3313                                reversed: selection.reversed,
 3314                                goal: selection.goal,
 3315                            },
 3316                            0,
 3317                        ));
 3318                        continue;
 3319                    }
 3320                }
 3321            }
 3322
 3323            if self.auto_replace_emoji_shortcode
 3324                && selection.is_empty()
 3325                && text.as_ref().ends_with(':')
 3326            {
 3327                if let Some(possible_emoji_short_code) =
 3328                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3329                {
 3330                    if !possible_emoji_short_code.is_empty() {
 3331                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3332                            let emoji_shortcode_start = Point::new(
 3333                                selection.start.row,
 3334                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3335                            );
 3336
 3337                            // Remove shortcode from buffer
 3338                            edits.push((
 3339                                emoji_shortcode_start..selection.start,
 3340                                "".to_string().into(),
 3341                            ));
 3342                            new_selections.push((
 3343                                Selection {
 3344                                    id: selection.id,
 3345                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3346                                    end: snapshot.anchor_before(selection.start),
 3347                                    reversed: selection.reversed,
 3348                                    goal: selection.goal,
 3349                                },
 3350                                0,
 3351                            ));
 3352
 3353                            // Insert emoji
 3354                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3355                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3356                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3357
 3358                            continue;
 3359                        }
 3360                    }
 3361                }
 3362            }
 3363
 3364            // If not handling any auto-close operation, then just replace the selected
 3365            // text with the given input and move the selection to the end of the
 3366            // newly inserted text.
 3367            let anchor = snapshot.anchor_after(selection.end);
 3368            if !self.linked_edit_ranges.is_empty() {
 3369                let start_anchor = snapshot.anchor_before(selection.start);
 3370
 3371                let is_word_char = text.chars().next().map_or(true, |char| {
 3372                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3373                    classifier.is_word(char)
 3374                });
 3375
 3376                if is_word_char {
 3377                    if let Some(ranges) = self
 3378                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3379                    {
 3380                        for (buffer, edits) in ranges {
 3381                            linked_edits
 3382                                .entry(buffer.clone())
 3383                                .or_default()
 3384                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3385                        }
 3386                    }
 3387                } else {
 3388                    clear_linked_edit_ranges = true;
 3389                }
 3390            }
 3391
 3392            new_selections.push((selection.map(|_| anchor), 0));
 3393            edits.push((selection.start..selection.end, text.clone()));
 3394        }
 3395
 3396        drop(snapshot);
 3397
 3398        self.transact(window, cx, |this, window, cx| {
 3399            if clear_linked_edit_ranges {
 3400                this.linked_edit_ranges.clear();
 3401            }
 3402            let initial_buffer_versions =
 3403                jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
 3404
 3405            this.buffer.update(cx, |buffer, cx| {
 3406                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3407            });
 3408            for (buffer, edits) in linked_edits {
 3409                buffer.update(cx, |buffer, cx| {
 3410                    let snapshot = buffer.snapshot();
 3411                    let edits = edits
 3412                        .into_iter()
 3413                        .map(|(range, text)| {
 3414                            use text::ToPoint as TP;
 3415                            let end_point = TP::to_point(&range.end, &snapshot);
 3416                            let start_point = TP::to_point(&range.start, &snapshot);
 3417                            (start_point..end_point, text)
 3418                        })
 3419                        .sorted_by_key(|(range, _)| range.start);
 3420                    buffer.edit(edits, None, cx);
 3421                })
 3422            }
 3423            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3424            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3425            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3426            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3427                .zip(new_selection_deltas)
 3428                .map(|(selection, delta)| Selection {
 3429                    id: selection.id,
 3430                    start: selection.start + delta,
 3431                    end: selection.end + delta,
 3432                    reversed: selection.reversed,
 3433                    goal: SelectionGoal::None,
 3434                })
 3435                .collect::<Vec<_>>();
 3436
 3437            let mut i = 0;
 3438            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3439                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3440                let start = map.buffer_snapshot.anchor_before(position);
 3441                let end = map.buffer_snapshot.anchor_after(position);
 3442                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3443                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3444                        Ordering::Less => i += 1,
 3445                        Ordering::Greater => break,
 3446                        Ordering::Equal => {
 3447                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3448                                Ordering::Less => i += 1,
 3449                                Ordering::Equal => break,
 3450                                Ordering::Greater => break,
 3451                            }
 3452                        }
 3453                    }
 3454                }
 3455                this.autoclose_regions.insert(
 3456                    i,
 3457                    AutocloseRegion {
 3458                        selection_id,
 3459                        range: start..end,
 3460                        pair,
 3461                    },
 3462                );
 3463            }
 3464
 3465            let had_active_inline_completion = this.has_active_inline_completion();
 3466            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3467                s.select(new_selections)
 3468            });
 3469
 3470            if !bracket_inserted {
 3471                if let Some(on_type_format_task) =
 3472                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3473                {
 3474                    on_type_format_task.detach_and_log_err(cx);
 3475                }
 3476            }
 3477
 3478            let editor_settings = EditorSettings::get_global(cx);
 3479            if bracket_inserted
 3480                && (editor_settings.auto_signature_help
 3481                    || editor_settings.show_signature_help_after_edits)
 3482            {
 3483                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3484            }
 3485
 3486            let trigger_in_words =
 3487                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3488            if this.hard_wrap.is_some() {
 3489                let latest: Range<Point> = this.selections.newest(cx).range();
 3490                if latest.is_empty()
 3491                    && this
 3492                        .buffer()
 3493                        .read(cx)
 3494                        .snapshot(cx)
 3495                        .line_len(MultiBufferRow(latest.start.row))
 3496                        == latest.start.column
 3497                {
 3498                    this.rewrap_impl(
 3499                        RewrapOptions {
 3500                            override_language_settings: true,
 3501                            preserve_existing_whitespace: true,
 3502                        },
 3503                        cx,
 3504                    )
 3505                }
 3506            }
 3507            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3508            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3509            this.refresh_inline_completion(true, false, window, cx);
 3510            jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
 3511        });
 3512    }
 3513
 3514    fn find_possible_emoji_shortcode_at_position(
 3515        snapshot: &MultiBufferSnapshot,
 3516        position: Point,
 3517    ) -> Option<String> {
 3518        let mut chars = Vec::new();
 3519        let mut found_colon = false;
 3520        for char in snapshot.reversed_chars_at(position).take(100) {
 3521            // Found a possible emoji shortcode in the middle of the buffer
 3522            if found_colon {
 3523                if char.is_whitespace() {
 3524                    chars.reverse();
 3525                    return Some(chars.iter().collect());
 3526                }
 3527                // If the previous character is not a whitespace, we are in the middle of a word
 3528                // and we only want to complete the shortcode if the word is made up of other emojis
 3529                let mut containing_word = String::new();
 3530                for ch in snapshot
 3531                    .reversed_chars_at(position)
 3532                    .skip(chars.len() + 1)
 3533                    .take(100)
 3534                {
 3535                    if ch.is_whitespace() {
 3536                        break;
 3537                    }
 3538                    containing_word.push(ch);
 3539                }
 3540                let containing_word = containing_word.chars().rev().collect::<String>();
 3541                if util::word_consists_of_emojis(containing_word.as_str()) {
 3542                    chars.reverse();
 3543                    return Some(chars.iter().collect());
 3544                }
 3545            }
 3546
 3547            if char.is_whitespace() || !char.is_ascii() {
 3548                return None;
 3549            }
 3550            if char == ':' {
 3551                found_colon = true;
 3552            } else {
 3553                chars.push(char);
 3554            }
 3555        }
 3556        // Found a possible emoji shortcode at the beginning of the buffer
 3557        chars.reverse();
 3558        Some(chars.iter().collect())
 3559    }
 3560
 3561    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3562        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3563        self.transact(window, cx, |this, window, cx| {
 3564            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3565                let selections = this.selections.all::<usize>(cx);
 3566                let multi_buffer = this.buffer.read(cx);
 3567                let buffer = multi_buffer.snapshot(cx);
 3568                selections
 3569                    .iter()
 3570                    .map(|selection| {
 3571                        let start_point = selection.start.to_point(&buffer);
 3572                        let mut indent =
 3573                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3574                        indent.len = cmp::min(indent.len, start_point.column);
 3575                        let start = selection.start;
 3576                        let end = selection.end;
 3577                        let selection_is_empty = start == end;
 3578                        let language_scope = buffer.language_scope_at(start);
 3579                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3580                            &language_scope
 3581                        {
 3582                            let insert_extra_newline =
 3583                                insert_extra_newline_brackets(&buffer, start..end, language)
 3584                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3585
 3586                            // Comment extension on newline is allowed only for cursor selections
 3587                            let comment_delimiter = maybe!({
 3588                                if !selection_is_empty {
 3589                                    return None;
 3590                                }
 3591
 3592                                if !multi_buffer.language_settings(cx).extend_comment_on_newline {
 3593                                    return None;
 3594                                }
 3595
 3596                                let delimiters = language.line_comment_prefixes();
 3597                                let max_len_of_delimiter =
 3598                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3599                                let (snapshot, range) =
 3600                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3601
 3602                                let mut index_of_first_non_whitespace = 0;
 3603                                let comment_candidate = snapshot
 3604                                    .chars_for_range(range)
 3605                                    .skip_while(|c| {
 3606                                        let should_skip = c.is_whitespace();
 3607                                        if should_skip {
 3608                                            index_of_first_non_whitespace += 1;
 3609                                        }
 3610                                        should_skip
 3611                                    })
 3612                                    .take(max_len_of_delimiter)
 3613                                    .collect::<String>();
 3614                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3615                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3616                                })?;
 3617                                let cursor_is_placed_after_comment_marker =
 3618                                    index_of_first_non_whitespace + comment_prefix.len()
 3619                                        <= start_point.column as usize;
 3620                                if cursor_is_placed_after_comment_marker {
 3621                                    Some(comment_prefix.clone())
 3622                                } else {
 3623                                    None
 3624                                }
 3625                            });
 3626                            (comment_delimiter, insert_extra_newline)
 3627                        } else {
 3628                            (None, false)
 3629                        };
 3630
 3631                        let capacity_for_delimiter = comment_delimiter
 3632                            .as_deref()
 3633                            .map(str::len)
 3634                            .unwrap_or_default();
 3635                        let mut new_text =
 3636                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3637                        new_text.push('\n');
 3638                        new_text.extend(indent.chars());
 3639                        if let Some(delimiter) = &comment_delimiter {
 3640                            new_text.push_str(delimiter);
 3641                        }
 3642                        if insert_extra_newline {
 3643                            new_text = new_text.repeat(2);
 3644                        }
 3645
 3646                        let anchor = buffer.anchor_after(end);
 3647                        let new_selection = selection.map(|_| anchor);
 3648                        (
 3649                            (start..end, new_text),
 3650                            (insert_extra_newline, new_selection),
 3651                        )
 3652                    })
 3653                    .unzip()
 3654            };
 3655
 3656            this.edit_with_autoindent(edits, cx);
 3657            let buffer = this.buffer.read(cx).snapshot(cx);
 3658            let new_selections = selection_fixup_info
 3659                .into_iter()
 3660                .map(|(extra_newline_inserted, new_selection)| {
 3661                    let mut cursor = new_selection.end.to_point(&buffer);
 3662                    if extra_newline_inserted {
 3663                        cursor.row -= 1;
 3664                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3665                    }
 3666                    new_selection.map(|_| cursor)
 3667                })
 3668                .collect();
 3669
 3670            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3671                s.select(new_selections)
 3672            });
 3673            this.refresh_inline_completion(true, false, window, cx);
 3674        });
 3675    }
 3676
 3677    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3678        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3679
 3680        let buffer = self.buffer.read(cx);
 3681        let snapshot = buffer.snapshot(cx);
 3682
 3683        let mut edits = Vec::new();
 3684        let mut rows = Vec::new();
 3685
 3686        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3687            let cursor = selection.head();
 3688            let row = cursor.row;
 3689
 3690            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3691
 3692            let newline = "\n".to_string();
 3693            edits.push((start_of_line..start_of_line, newline));
 3694
 3695            rows.push(row + rows_inserted as u32);
 3696        }
 3697
 3698        self.transact(window, cx, |editor, window, cx| {
 3699            editor.edit(edits, cx);
 3700
 3701            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3702                let mut index = 0;
 3703                s.move_cursors_with(|map, _, _| {
 3704                    let row = rows[index];
 3705                    index += 1;
 3706
 3707                    let point = Point::new(row, 0);
 3708                    let boundary = map.next_line_boundary(point).1;
 3709                    let clipped = map.clip_point(boundary, Bias::Left);
 3710
 3711                    (clipped, SelectionGoal::None)
 3712                });
 3713            });
 3714
 3715            let mut indent_edits = Vec::new();
 3716            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3717            for row in rows {
 3718                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3719                for (row, indent) in indents {
 3720                    if indent.len == 0 {
 3721                        continue;
 3722                    }
 3723
 3724                    let text = match indent.kind {
 3725                        IndentKind::Space => " ".repeat(indent.len as usize),
 3726                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3727                    };
 3728                    let point = Point::new(row.0, 0);
 3729                    indent_edits.push((point..point, text));
 3730                }
 3731            }
 3732            editor.edit(indent_edits, cx);
 3733        });
 3734    }
 3735
 3736    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3737        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3738
 3739        let buffer = self.buffer.read(cx);
 3740        let snapshot = buffer.snapshot(cx);
 3741
 3742        let mut edits = Vec::new();
 3743        let mut rows = Vec::new();
 3744        let mut rows_inserted = 0;
 3745
 3746        for selection in self.selections.all_adjusted(cx) {
 3747            let cursor = selection.head();
 3748            let row = cursor.row;
 3749
 3750            let point = Point::new(row + 1, 0);
 3751            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3752
 3753            let newline = "\n".to_string();
 3754            edits.push((start_of_line..start_of_line, newline));
 3755
 3756            rows_inserted += 1;
 3757            rows.push(row + rows_inserted);
 3758        }
 3759
 3760        self.transact(window, cx, |editor, window, cx| {
 3761            editor.edit(edits, cx);
 3762
 3763            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3764                let mut index = 0;
 3765                s.move_cursors_with(|map, _, _| {
 3766                    let row = rows[index];
 3767                    index += 1;
 3768
 3769                    let point = Point::new(row, 0);
 3770                    let boundary = map.next_line_boundary(point).1;
 3771                    let clipped = map.clip_point(boundary, Bias::Left);
 3772
 3773                    (clipped, SelectionGoal::None)
 3774                });
 3775            });
 3776
 3777            let mut indent_edits = Vec::new();
 3778            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3779            for row in rows {
 3780                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3781                for (row, indent) in indents {
 3782                    if indent.len == 0 {
 3783                        continue;
 3784                    }
 3785
 3786                    let text = match indent.kind {
 3787                        IndentKind::Space => " ".repeat(indent.len as usize),
 3788                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3789                    };
 3790                    let point = Point::new(row.0, 0);
 3791                    indent_edits.push((point..point, text));
 3792                }
 3793            }
 3794            editor.edit(indent_edits, cx);
 3795        });
 3796    }
 3797
 3798    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3799        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3800            original_indent_columns: Vec::new(),
 3801        });
 3802        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3803    }
 3804
 3805    fn insert_with_autoindent_mode(
 3806        &mut self,
 3807        text: &str,
 3808        autoindent_mode: Option<AutoindentMode>,
 3809        window: &mut Window,
 3810        cx: &mut Context<Self>,
 3811    ) {
 3812        if self.read_only(cx) {
 3813            return;
 3814        }
 3815
 3816        let text: Arc<str> = text.into();
 3817        self.transact(window, cx, |this, window, cx| {
 3818            let old_selections = this.selections.all_adjusted(cx);
 3819            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3820                let anchors = {
 3821                    let snapshot = buffer.read(cx);
 3822                    old_selections
 3823                        .iter()
 3824                        .map(|s| {
 3825                            let anchor = snapshot.anchor_after(s.head());
 3826                            s.map(|_| anchor)
 3827                        })
 3828                        .collect::<Vec<_>>()
 3829                };
 3830                buffer.edit(
 3831                    old_selections
 3832                        .iter()
 3833                        .map(|s| (s.start..s.end, text.clone())),
 3834                    autoindent_mode,
 3835                    cx,
 3836                );
 3837                anchors
 3838            });
 3839
 3840            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3841                s.select_anchors(selection_anchors);
 3842            });
 3843
 3844            cx.notify();
 3845        });
 3846    }
 3847
 3848    fn trigger_completion_on_input(
 3849        &mut self,
 3850        text: &str,
 3851        trigger_in_words: bool,
 3852        window: &mut Window,
 3853        cx: &mut Context<Self>,
 3854    ) {
 3855        let ignore_completion_provider = self
 3856            .context_menu
 3857            .borrow()
 3858            .as_ref()
 3859            .map(|menu| match menu {
 3860                CodeContextMenu::Completions(completions_menu) => {
 3861                    completions_menu.ignore_completion_provider
 3862                }
 3863                CodeContextMenu::CodeActions(_) => false,
 3864            })
 3865            .unwrap_or(false);
 3866
 3867        if ignore_completion_provider {
 3868            self.show_word_completions(&ShowWordCompletions, window, cx);
 3869        } else if self.is_completion_trigger(text, trigger_in_words, cx) {
 3870            self.show_completions(
 3871                &ShowCompletions {
 3872                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3873                },
 3874                window,
 3875                cx,
 3876            );
 3877        } else {
 3878            self.hide_context_menu(window, cx);
 3879        }
 3880    }
 3881
 3882    fn is_completion_trigger(
 3883        &self,
 3884        text: &str,
 3885        trigger_in_words: bool,
 3886        cx: &mut Context<Self>,
 3887    ) -> bool {
 3888        let position = self.selections.newest_anchor().head();
 3889        let multibuffer = self.buffer.read(cx);
 3890        let Some(buffer) = position
 3891            .buffer_id
 3892            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3893        else {
 3894            return false;
 3895        };
 3896
 3897        if let Some(completion_provider) = &self.completion_provider {
 3898            completion_provider.is_completion_trigger(
 3899                &buffer,
 3900                position.text_anchor,
 3901                text,
 3902                trigger_in_words,
 3903                cx,
 3904            )
 3905        } else {
 3906            false
 3907        }
 3908    }
 3909
 3910    /// If any empty selections is touching the start of its innermost containing autoclose
 3911    /// region, expand it to select the brackets.
 3912    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3913        let selections = self.selections.all::<usize>(cx);
 3914        let buffer = self.buffer.read(cx).read(cx);
 3915        let new_selections = self
 3916            .selections_with_autoclose_regions(selections, &buffer)
 3917            .map(|(mut selection, region)| {
 3918                if !selection.is_empty() {
 3919                    return selection;
 3920                }
 3921
 3922                if let Some(region) = region {
 3923                    let mut range = region.range.to_offset(&buffer);
 3924                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3925                        range.start -= region.pair.start.len();
 3926                        if buffer.contains_str_at(range.start, &region.pair.start)
 3927                            && buffer.contains_str_at(range.end, &region.pair.end)
 3928                        {
 3929                            range.end += region.pair.end.len();
 3930                            selection.start = range.start;
 3931                            selection.end = range.end;
 3932
 3933                            return selection;
 3934                        }
 3935                    }
 3936                }
 3937
 3938                let always_treat_brackets_as_autoclosed = buffer
 3939                    .language_settings_at(selection.start, cx)
 3940                    .always_treat_brackets_as_autoclosed;
 3941
 3942                if !always_treat_brackets_as_autoclosed {
 3943                    return selection;
 3944                }
 3945
 3946                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3947                    for (pair, enabled) in scope.brackets() {
 3948                        if !enabled || !pair.close {
 3949                            continue;
 3950                        }
 3951
 3952                        if buffer.contains_str_at(selection.start, &pair.end) {
 3953                            let pair_start_len = pair.start.len();
 3954                            if buffer.contains_str_at(
 3955                                selection.start.saturating_sub(pair_start_len),
 3956                                &pair.start,
 3957                            ) {
 3958                                selection.start -= pair_start_len;
 3959                                selection.end += pair.end.len();
 3960
 3961                                return selection;
 3962                            }
 3963                        }
 3964                    }
 3965                }
 3966
 3967                selection
 3968            })
 3969            .collect();
 3970
 3971        drop(buffer);
 3972        self.change_selections(None, window, cx, |selections| {
 3973            selections.select(new_selections)
 3974        });
 3975    }
 3976
 3977    /// Iterate the given selections, and for each one, find the smallest surrounding
 3978    /// autoclose region. This uses the ordering of the selections and the autoclose
 3979    /// regions to avoid repeated comparisons.
 3980    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3981        &'a self,
 3982        selections: impl IntoIterator<Item = Selection<D>>,
 3983        buffer: &'a MultiBufferSnapshot,
 3984    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3985        let mut i = 0;
 3986        let mut regions = self.autoclose_regions.as_slice();
 3987        selections.into_iter().map(move |selection| {
 3988            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3989
 3990            let mut enclosing = None;
 3991            while let Some(pair_state) = regions.get(i) {
 3992                if pair_state.range.end.to_offset(buffer) < range.start {
 3993                    regions = &regions[i + 1..];
 3994                    i = 0;
 3995                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3996                    break;
 3997                } else {
 3998                    if pair_state.selection_id == selection.id {
 3999                        enclosing = Some(pair_state);
 4000                    }
 4001                    i += 1;
 4002                }
 4003            }
 4004
 4005            (selection, enclosing)
 4006        })
 4007    }
 4008
 4009    /// Remove any autoclose regions that no longer contain their selection.
 4010    fn invalidate_autoclose_regions(
 4011        &mut self,
 4012        mut selections: &[Selection<Anchor>],
 4013        buffer: &MultiBufferSnapshot,
 4014    ) {
 4015        self.autoclose_regions.retain(|state| {
 4016            let mut i = 0;
 4017            while let Some(selection) = selections.get(i) {
 4018                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4019                    selections = &selections[1..];
 4020                    continue;
 4021                }
 4022                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4023                    break;
 4024                }
 4025                if selection.id == state.selection_id {
 4026                    return true;
 4027                } else {
 4028                    i += 1;
 4029                }
 4030            }
 4031            false
 4032        });
 4033    }
 4034
 4035    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4036        let offset = position.to_offset(buffer);
 4037        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4038        if offset > word_range.start && kind == Some(CharKind::Word) {
 4039            Some(
 4040                buffer
 4041                    .text_for_range(word_range.start..offset)
 4042                    .collect::<String>(),
 4043            )
 4044        } else {
 4045            None
 4046        }
 4047    }
 4048
 4049    pub fn toggle_inlay_hints(
 4050        &mut self,
 4051        _: &ToggleInlayHints,
 4052        _: &mut Window,
 4053        cx: &mut Context<Self>,
 4054    ) {
 4055        self.refresh_inlay_hints(
 4056            InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
 4057            cx,
 4058        );
 4059    }
 4060
 4061    pub fn inlay_hints_enabled(&self) -> bool {
 4062        self.inlay_hint_cache.enabled
 4063    }
 4064
 4065    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 4066        if self.semantics_provider.is_none() || !self.mode.is_full() {
 4067            return;
 4068        }
 4069
 4070        let reason_description = reason.description();
 4071        let ignore_debounce = matches!(
 4072            reason,
 4073            InlayHintRefreshReason::SettingsChange(_)
 4074                | InlayHintRefreshReason::Toggle(_)
 4075                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4076                | InlayHintRefreshReason::ModifiersChanged(_)
 4077        );
 4078        let (invalidate_cache, required_languages) = match reason {
 4079            InlayHintRefreshReason::ModifiersChanged(enabled) => {
 4080                match self.inlay_hint_cache.modifiers_override(enabled) {
 4081                    Some(enabled) => {
 4082                        if enabled {
 4083                            (InvalidationStrategy::RefreshRequested, None)
 4084                        } else {
 4085                            self.splice_inlays(
 4086                                &self
 4087                                    .visible_inlay_hints(cx)
 4088                                    .iter()
 4089                                    .map(|inlay| inlay.id)
 4090                                    .collect::<Vec<InlayId>>(),
 4091                                Vec::new(),
 4092                                cx,
 4093                            );
 4094                            return;
 4095                        }
 4096                    }
 4097                    None => return,
 4098                }
 4099            }
 4100            InlayHintRefreshReason::Toggle(enabled) => {
 4101                if self.inlay_hint_cache.toggle(enabled) {
 4102                    if enabled {
 4103                        (InvalidationStrategy::RefreshRequested, None)
 4104                    } else {
 4105                        self.splice_inlays(
 4106                            &self
 4107                                .visible_inlay_hints(cx)
 4108                                .iter()
 4109                                .map(|inlay| inlay.id)
 4110                                .collect::<Vec<InlayId>>(),
 4111                            Vec::new(),
 4112                            cx,
 4113                        );
 4114                        return;
 4115                    }
 4116                } else {
 4117                    return;
 4118                }
 4119            }
 4120            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4121                match self.inlay_hint_cache.update_settings(
 4122                    &self.buffer,
 4123                    new_settings,
 4124                    self.visible_inlay_hints(cx),
 4125                    cx,
 4126                ) {
 4127                    ControlFlow::Break(Some(InlaySplice {
 4128                        to_remove,
 4129                        to_insert,
 4130                    })) => {
 4131                        self.splice_inlays(&to_remove, to_insert, cx);
 4132                        return;
 4133                    }
 4134                    ControlFlow::Break(None) => return,
 4135                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4136                }
 4137            }
 4138            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4139                if let Some(InlaySplice {
 4140                    to_remove,
 4141                    to_insert,
 4142                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 4143                {
 4144                    self.splice_inlays(&to_remove, to_insert, cx);
 4145                }
 4146                return;
 4147            }
 4148            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4149            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4150                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4151            }
 4152            InlayHintRefreshReason::RefreshRequested => {
 4153                (InvalidationStrategy::RefreshRequested, None)
 4154            }
 4155        };
 4156
 4157        if let Some(InlaySplice {
 4158            to_remove,
 4159            to_insert,
 4160        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4161            reason_description,
 4162            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4163            invalidate_cache,
 4164            ignore_debounce,
 4165            cx,
 4166        ) {
 4167            self.splice_inlays(&to_remove, to_insert, cx);
 4168        }
 4169    }
 4170
 4171    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 4172        self.display_map
 4173            .read(cx)
 4174            .current_inlays()
 4175            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4176            .cloned()
 4177            .collect()
 4178    }
 4179
 4180    pub fn excerpts_for_inlay_hints_query(
 4181        &self,
 4182        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4183        cx: &mut Context<Editor>,
 4184    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 4185        let Some(project) = self.project.as_ref() else {
 4186            return HashMap::default();
 4187        };
 4188        let project = project.read(cx);
 4189        let multi_buffer = self.buffer().read(cx);
 4190        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4191        let multi_buffer_visible_start = self
 4192            .scroll_manager
 4193            .anchor()
 4194            .anchor
 4195            .to_point(&multi_buffer_snapshot);
 4196        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4197            multi_buffer_visible_start
 4198                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4199            Bias::Left,
 4200        );
 4201        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4202        multi_buffer_snapshot
 4203            .range_to_buffer_ranges(multi_buffer_visible_range)
 4204            .into_iter()
 4205            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4206            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 4207                let buffer_file = project::File::from_dyn(buffer.file())?;
 4208                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4209                let worktree_entry = buffer_worktree
 4210                    .read(cx)
 4211                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4212                if worktree_entry.is_ignored {
 4213                    return None;
 4214                }
 4215
 4216                let language = buffer.language()?;
 4217                if let Some(restrict_to_languages) = restrict_to_languages {
 4218                    if !restrict_to_languages.contains(language) {
 4219                        return None;
 4220                    }
 4221                }
 4222                Some((
 4223                    excerpt_id,
 4224                    (
 4225                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 4226                        buffer.version().clone(),
 4227                        excerpt_visible_range,
 4228                    ),
 4229                ))
 4230            })
 4231            .collect()
 4232    }
 4233
 4234    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 4235        TextLayoutDetails {
 4236            text_system: window.text_system().clone(),
 4237            editor_style: self.style.clone().unwrap(),
 4238            rem_size: window.rem_size(),
 4239            scroll_anchor: self.scroll_manager.anchor(),
 4240            visible_rows: self.visible_line_count(),
 4241            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4242        }
 4243    }
 4244
 4245    pub fn splice_inlays(
 4246        &self,
 4247        to_remove: &[InlayId],
 4248        to_insert: Vec<Inlay>,
 4249        cx: &mut Context<Self>,
 4250    ) {
 4251        self.display_map.update(cx, |display_map, cx| {
 4252            display_map.splice_inlays(to_remove, to_insert, cx)
 4253        });
 4254        cx.notify();
 4255    }
 4256
 4257    fn trigger_on_type_formatting(
 4258        &self,
 4259        input: String,
 4260        window: &mut Window,
 4261        cx: &mut Context<Self>,
 4262    ) -> Option<Task<Result<()>>> {
 4263        if input.len() != 1 {
 4264            return None;
 4265        }
 4266
 4267        let project = self.project.as_ref()?;
 4268        let position = self.selections.newest_anchor().head();
 4269        let (buffer, buffer_position) = self
 4270            .buffer
 4271            .read(cx)
 4272            .text_anchor_for_position(position, cx)?;
 4273
 4274        let settings = language_settings::language_settings(
 4275            buffer
 4276                .read(cx)
 4277                .language_at(buffer_position)
 4278                .map(|l| l.name()),
 4279            buffer.read(cx).file(),
 4280            cx,
 4281        );
 4282        if !settings.use_on_type_format {
 4283            return None;
 4284        }
 4285
 4286        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4287        // hence we do LSP request & edit on host side only — add formats to host's history.
 4288        let push_to_lsp_host_history = true;
 4289        // If this is not the host, append its history with new edits.
 4290        let push_to_client_history = project.read(cx).is_via_collab();
 4291
 4292        let on_type_formatting = project.update(cx, |project, cx| {
 4293            project.on_type_format(
 4294                buffer.clone(),
 4295                buffer_position,
 4296                input,
 4297                push_to_lsp_host_history,
 4298                cx,
 4299            )
 4300        });
 4301        Some(cx.spawn_in(window, async move |editor, cx| {
 4302            if let Some(transaction) = on_type_formatting.await? {
 4303                if push_to_client_history {
 4304                    buffer
 4305                        .update(cx, |buffer, _| {
 4306                            buffer.push_transaction(transaction, Instant::now());
 4307                            buffer.finalize_last_transaction();
 4308                        })
 4309                        .ok();
 4310                }
 4311                editor.update(cx, |editor, cx| {
 4312                    editor.refresh_document_highlights(cx);
 4313                })?;
 4314            }
 4315            Ok(())
 4316        }))
 4317    }
 4318
 4319    pub fn show_word_completions(
 4320        &mut self,
 4321        _: &ShowWordCompletions,
 4322        window: &mut Window,
 4323        cx: &mut Context<Self>,
 4324    ) {
 4325        self.open_completions_menu(true, None, window, cx);
 4326    }
 4327
 4328    pub fn show_completions(
 4329        &mut self,
 4330        options: &ShowCompletions,
 4331        window: &mut Window,
 4332        cx: &mut Context<Self>,
 4333    ) {
 4334        self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
 4335    }
 4336
 4337    fn open_completions_menu(
 4338        &mut self,
 4339        ignore_completion_provider: bool,
 4340        trigger: Option<&str>,
 4341        window: &mut Window,
 4342        cx: &mut Context<Self>,
 4343    ) {
 4344        if self.pending_rename.is_some() {
 4345            return;
 4346        }
 4347        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 4348            return;
 4349        }
 4350
 4351        let position = self.selections.newest_anchor().head();
 4352        if position.diff_base_anchor.is_some() {
 4353            return;
 4354        }
 4355        let (buffer, buffer_position) =
 4356            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4357                output
 4358            } else {
 4359                return;
 4360            };
 4361        let buffer_snapshot = buffer.read(cx).snapshot();
 4362        let show_completion_documentation = buffer_snapshot
 4363            .settings_at(buffer_position, cx)
 4364            .show_completion_documentation;
 4365
 4366        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4367
 4368        let trigger_kind = match trigger {
 4369            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4370                CompletionTriggerKind::TRIGGER_CHARACTER
 4371            }
 4372            _ => CompletionTriggerKind::INVOKED,
 4373        };
 4374        let completion_context = CompletionContext {
 4375            trigger_character: trigger.and_then(|trigger| {
 4376                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4377                    Some(String::from(trigger))
 4378                } else {
 4379                    None
 4380                }
 4381            }),
 4382            trigger_kind,
 4383        };
 4384
 4385        let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
 4386        let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
 4387            let word_to_exclude = buffer_snapshot
 4388                .text_for_range(old_range.clone())
 4389                .collect::<String>();
 4390            (
 4391                buffer_snapshot.anchor_before(old_range.start)
 4392                    ..buffer_snapshot.anchor_after(old_range.end),
 4393                Some(word_to_exclude),
 4394            )
 4395        } else {
 4396            (buffer_position..buffer_position, None)
 4397        };
 4398
 4399        let completion_settings = language_settings(
 4400            buffer_snapshot
 4401                .language_at(buffer_position)
 4402                .map(|language| language.name()),
 4403            buffer_snapshot.file(),
 4404            cx,
 4405        )
 4406        .completions;
 4407
 4408        // The document can be large, so stay in reasonable bounds when searching for words,
 4409        // otherwise completion pop-up might be slow to appear.
 4410        const WORD_LOOKUP_ROWS: u32 = 5_000;
 4411        let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
 4412        let min_word_search = buffer_snapshot.clip_point(
 4413            Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
 4414            Bias::Left,
 4415        );
 4416        let max_word_search = buffer_snapshot.clip_point(
 4417            Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
 4418            Bias::Right,
 4419        );
 4420        let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
 4421            ..buffer_snapshot.point_to_offset(max_word_search);
 4422
 4423        let provider = self
 4424            .completion_provider
 4425            .as_ref()
 4426            .filter(|_| !ignore_completion_provider);
 4427        let skip_digits = query
 4428            .as_ref()
 4429            .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
 4430
 4431        let (mut words, provided_completions) = match provider {
 4432            Some(provider) => {
 4433                let completions = provider.completions(
 4434                    position.excerpt_id,
 4435                    &buffer,
 4436                    buffer_position,
 4437                    completion_context,
 4438                    window,
 4439                    cx,
 4440                );
 4441
 4442                let words = match completion_settings.words {
 4443                    WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
 4444                    WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
 4445                        .background_spawn(async move {
 4446                            buffer_snapshot.words_in_range(WordsQuery {
 4447                                fuzzy_contents: None,
 4448                                range: word_search_range,
 4449                                skip_digits,
 4450                            })
 4451                        }),
 4452                };
 4453
 4454                (words, completions)
 4455            }
 4456            None => (
 4457                cx.background_spawn(async move {
 4458                    buffer_snapshot.words_in_range(WordsQuery {
 4459                        fuzzy_contents: None,
 4460                        range: word_search_range,
 4461                        skip_digits,
 4462                    })
 4463                }),
 4464                Task::ready(Ok(None)),
 4465            ),
 4466        };
 4467
 4468        let sort_completions = provider
 4469            .as_ref()
 4470            .map_or(false, |provider| provider.sort_completions());
 4471
 4472        let filter_completions = provider
 4473            .as_ref()
 4474            .map_or(true, |provider| provider.filter_completions());
 4475
 4476        let id = post_inc(&mut self.next_completion_id);
 4477        let task = cx.spawn_in(window, async move |editor, cx| {
 4478            async move {
 4479                editor.update(cx, |this, _| {
 4480                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4481                })?;
 4482
 4483                let mut completions = Vec::new();
 4484                if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
 4485                    completions.extend(provided_completions);
 4486                    if completion_settings.words == WordsCompletionMode::Fallback {
 4487                        words = Task::ready(BTreeMap::default());
 4488                    }
 4489                }
 4490
 4491                let mut words = words.await;
 4492                if let Some(word_to_exclude) = &word_to_exclude {
 4493                    words.remove(word_to_exclude);
 4494                }
 4495                for lsp_completion in &completions {
 4496                    words.remove(&lsp_completion.new_text);
 4497                }
 4498                completions.extend(words.into_iter().map(|(word, word_range)| Completion {
 4499                    replace_range: old_range.clone(),
 4500                    new_text: word.clone(),
 4501                    label: CodeLabel::plain(word, None),
 4502                    icon_path: None,
 4503                    documentation: None,
 4504                    source: CompletionSource::BufferWord {
 4505                        word_range,
 4506                        resolved: false,
 4507                    },
 4508                    insert_text_mode: Some(InsertTextMode::AS_IS),
 4509                    confirm: None,
 4510                }));
 4511
 4512                let menu = if completions.is_empty() {
 4513                    None
 4514                } else {
 4515                    let mut menu = CompletionsMenu::new(
 4516                        id,
 4517                        sort_completions,
 4518                        show_completion_documentation,
 4519                        ignore_completion_provider,
 4520                        position,
 4521                        buffer.clone(),
 4522                        completions.into(),
 4523                    );
 4524
 4525                    menu.filter(
 4526                        if filter_completions {
 4527                            query.as_deref()
 4528                        } else {
 4529                            None
 4530                        },
 4531                        cx.background_executor().clone(),
 4532                    )
 4533                    .await;
 4534
 4535                    menu.visible().then_some(menu)
 4536                };
 4537
 4538                editor.update_in(cx, |editor, window, cx| {
 4539                    match editor.context_menu.borrow().as_ref() {
 4540                        None => {}
 4541                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4542                            if prev_menu.id > id {
 4543                                return;
 4544                            }
 4545                        }
 4546                        _ => return,
 4547                    }
 4548
 4549                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4550                        let mut menu = menu.unwrap();
 4551                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4552
 4553                        *editor.context_menu.borrow_mut() =
 4554                            Some(CodeContextMenu::Completions(menu));
 4555
 4556                        if editor.show_edit_predictions_in_menu() {
 4557                            editor.update_visible_inline_completion(window, cx);
 4558                        } else {
 4559                            editor.discard_inline_completion(false, cx);
 4560                        }
 4561
 4562                        cx.notify();
 4563                    } else if editor.completion_tasks.len() <= 1 {
 4564                        // If there are no more completion tasks and the last menu was
 4565                        // empty, we should hide it.
 4566                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4567                        // If it was already hidden and we don't show inline
 4568                        // completions in the menu, we should also show the
 4569                        // inline-completion when available.
 4570                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4571                            editor.update_visible_inline_completion(window, cx);
 4572                        }
 4573                    }
 4574                })?;
 4575
 4576                anyhow::Ok(())
 4577            }
 4578            .log_err()
 4579            .await
 4580        });
 4581
 4582        self.completion_tasks.push((id, task));
 4583    }
 4584
 4585    #[cfg(feature = "test-support")]
 4586    pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
 4587        let menu = self.context_menu.borrow();
 4588        if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
 4589            let completions = menu.completions.borrow();
 4590            Some(completions.to_vec())
 4591        } else {
 4592            None
 4593        }
 4594    }
 4595
 4596    pub fn confirm_completion(
 4597        &mut self,
 4598        action: &ConfirmCompletion,
 4599        window: &mut Window,
 4600        cx: &mut Context<Self>,
 4601    ) -> Option<Task<Result<()>>> {
 4602        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4603        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4604    }
 4605
 4606    pub fn confirm_completion_insert(
 4607        &mut self,
 4608        _: &ConfirmCompletionInsert,
 4609        window: &mut Window,
 4610        cx: &mut Context<Self>,
 4611    ) -> Option<Task<Result<()>>> {
 4612        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4613        self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
 4614    }
 4615
 4616    pub fn confirm_completion_replace(
 4617        &mut self,
 4618        _: &ConfirmCompletionReplace,
 4619        window: &mut Window,
 4620        cx: &mut Context<Self>,
 4621    ) -> Option<Task<Result<()>>> {
 4622        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4623        self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
 4624    }
 4625
 4626    pub fn compose_completion(
 4627        &mut self,
 4628        action: &ComposeCompletion,
 4629        window: &mut Window,
 4630        cx: &mut Context<Self>,
 4631    ) -> Option<Task<Result<()>>> {
 4632        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4633        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4634    }
 4635
 4636    fn do_completion(
 4637        &mut self,
 4638        item_ix: Option<usize>,
 4639        intent: CompletionIntent,
 4640        window: &mut Window,
 4641        cx: &mut Context<Editor>,
 4642    ) -> Option<Task<Result<()>>> {
 4643        use language::ToOffset as _;
 4644
 4645        let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
 4646        else {
 4647            return None;
 4648        };
 4649
 4650        let candidate_id = {
 4651            let entries = completions_menu.entries.borrow();
 4652            let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4653            if self.show_edit_predictions_in_menu() {
 4654                self.discard_inline_completion(true, cx);
 4655            }
 4656            mat.candidate_id
 4657        };
 4658
 4659        let buffer_handle = completions_menu.buffer;
 4660        let completion = completions_menu
 4661            .completions
 4662            .borrow()
 4663            .get(candidate_id)?
 4664            .clone();
 4665        cx.stop_propagation();
 4666
 4667        let snippet;
 4668        let new_text;
 4669        if completion.is_snippet() {
 4670            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4671            new_text = snippet.as_ref().unwrap().text.clone();
 4672        } else {
 4673            snippet = None;
 4674            new_text = completion.new_text.clone();
 4675        };
 4676        let selections = self.selections.all::<usize>(cx);
 4677
 4678        let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
 4679        let buffer = buffer_handle.read(cx);
 4680        let old_text = buffer
 4681            .text_for_range(replace_range.clone())
 4682            .collect::<String>();
 4683
 4684        let newest_selection = self.selections.newest_anchor();
 4685        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4686            return None;
 4687        }
 4688
 4689        let lookbehind = newest_selection
 4690            .start
 4691            .text_anchor
 4692            .to_offset(buffer)
 4693            .saturating_sub(replace_range.start);
 4694        let lookahead = replace_range
 4695            .end
 4696            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4697        let mut common_prefix_len = 0;
 4698        for (a, b) in old_text.chars().zip(new_text.chars()) {
 4699            if a == b {
 4700                common_prefix_len += a.len_utf8();
 4701            } else {
 4702                break;
 4703            }
 4704        }
 4705
 4706        let snapshot = self.buffer.read(cx).snapshot(cx);
 4707        let mut range_to_replace: Option<Range<usize>> = None;
 4708        let mut ranges = Vec::new();
 4709        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4710        for selection in &selections {
 4711            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4712                let start = selection.start.saturating_sub(lookbehind);
 4713                let end = selection.end + lookahead;
 4714                if selection.id == newest_selection.id {
 4715                    range_to_replace = Some(start + common_prefix_len..end);
 4716                }
 4717                ranges.push(start + common_prefix_len..end);
 4718            } else {
 4719                common_prefix_len = 0;
 4720                ranges.clear();
 4721                ranges.extend(selections.iter().map(|s| {
 4722                    if s.id == newest_selection.id {
 4723                        range_to_replace = Some(replace_range.clone());
 4724                        replace_range.clone()
 4725                    } else {
 4726                        s.start..s.end
 4727                    }
 4728                }));
 4729                break;
 4730            }
 4731            if !self.linked_edit_ranges.is_empty() {
 4732                let start_anchor = snapshot.anchor_before(selection.head());
 4733                let end_anchor = snapshot.anchor_after(selection.tail());
 4734                if let Some(ranges) = self
 4735                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4736                {
 4737                    for (buffer, edits) in ranges {
 4738                        linked_edits.entry(buffer.clone()).or_default().extend(
 4739                            edits
 4740                                .into_iter()
 4741                                .map(|range| (range, new_text[common_prefix_len..].to_owned())),
 4742                        );
 4743                    }
 4744                }
 4745            }
 4746        }
 4747        let text = &new_text[common_prefix_len..];
 4748
 4749        let utf16_range_to_replace = range_to_replace.map(|range| {
 4750            let newest_selection = self.selections.newest::<OffsetUtf16>(cx).range();
 4751            let selection_start_utf16 = newest_selection.start.0 as isize;
 4752
 4753            range.start.to_offset_utf16(&snapshot).0 as isize - selection_start_utf16
 4754                ..range.end.to_offset_utf16(&snapshot).0 as isize - selection_start_utf16
 4755        });
 4756        cx.emit(EditorEvent::InputHandled {
 4757            utf16_range_to_replace,
 4758            text: text.into(),
 4759        });
 4760
 4761        self.transact(window, cx, |this, window, cx| {
 4762            if let Some(mut snippet) = snippet {
 4763                snippet.text = text.to_string();
 4764                for tabstop in snippet
 4765                    .tabstops
 4766                    .iter_mut()
 4767                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4768                {
 4769                    tabstop.start -= common_prefix_len as isize;
 4770                    tabstop.end -= common_prefix_len as isize;
 4771                }
 4772
 4773                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4774            } else {
 4775                this.buffer.update(cx, |buffer, cx| {
 4776                    let edits = ranges.iter().map(|range| (range.clone(), text));
 4777                    let auto_indent = if completion.insert_text_mode == Some(InsertTextMode::AS_IS)
 4778                    {
 4779                        None
 4780                    } else {
 4781                        this.autoindent_mode.clone()
 4782                    };
 4783                    buffer.edit(edits, auto_indent, cx);
 4784                });
 4785            }
 4786            for (buffer, edits) in linked_edits {
 4787                buffer.update(cx, |buffer, cx| {
 4788                    let snapshot = buffer.snapshot();
 4789                    let edits = edits
 4790                        .into_iter()
 4791                        .map(|(range, text)| {
 4792                            use text::ToPoint as TP;
 4793                            let end_point = TP::to_point(&range.end, &snapshot);
 4794                            let start_point = TP::to_point(&range.start, &snapshot);
 4795                            (start_point..end_point, text)
 4796                        })
 4797                        .sorted_by_key(|(range, _)| range.start);
 4798                    buffer.edit(edits, None, cx);
 4799                })
 4800            }
 4801
 4802            this.refresh_inline_completion(true, false, window, cx);
 4803        });
 4804
 4805        let show_new_completions_on_confirm = completion
 4806            .confirm
 4807            .as_ref()
 4808            .map_or(false, |confirm| confirm(intent, window, cx));
 4809        if show_new_completions_on_confirm {
 4810            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4811        }
 4812
 4813        let provider = self.completion_provider.as_ref()?;
 4814        drop(completion);
 4815        let apply_edits = provider.apply_additional_edits_for_completion(
 4816            buffer_handle,
 4817            completions_menu.completions.clone(),
 4818            candidate_id,
 4819            true,
 4820            cx,
 4821        );
 4822
 4823        let editor_settings = EditorSettings::get_global(cx);
 4824        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4825            // After the code completion is finished, users often want to know what signatures are needed.
 4826            // so we should automatically call signature_help
 4827            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4828        }
 4829
 4830        Some(cx.foreground_executor().spawn(async move {
 4831            apply_edits.await?;
 4832            Ok(())
 4833        }))
 4834    }
 4835
 4836    pub fn toggle_code_actions(
 4837        &mut self,
 4838        action: &ToggleCodeActions,
 4839        window: &mut Window,
 4840        cx: &mut Context<Self>,
 4841    ) {
 4842        let mut context_menu = self.context_menu.borrow_mut();
 4843        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4844            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4845                // Toggle if we're selecting the same one
 4846                *context_menu = None;
 4847                cx.notify();
 4848                return;
 4849            } else {
 4850                // Otherwise, clear it and start a new one
 4851                *context_menu = None;
 4852                cx.notify();
 4853            }
 4854        }
 4855        drop(context_menu);
 4856        let snapshot = self.snapshot(window, cx);
 4857        let deployed_from_indicator = action.deployed_from_indicator;
 4858        let mut task = self.code_actions_task.take();
 4859        let action = action.clone();
 4860        cx.spawn_in(window, async move |editor, cx| {
 4861            while let Some(prev_task) = task {
 4862                prev_task.await.log_err();
 4863                task = editor.update(cx, |this, _| this.code_actions_task.take())?;
 4864            }
 4865
 4866            let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
 4867                if editor.focus_handle.is_focused(window) {
 4868                    let multibuffer_point = action
 4869                        .deployed_from_indicator
 4870                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4871                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4872                    let (buffer, buffer_row) = snapshot
 4873                        .buffer_snapshot
 4874                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4875                        .and_then(|(buffer_snapshot, range)| {
 4876                            editor
 4877                                .buffer
 4878                                .read(cx)
 4879                                .buffer(buffer_snapshot.remote_id())
 4880                                .map(|buffer| (buffer, range.start.row))
 4881                        })?;
 4882                    let (_, code_actions) = editor
 4883                        .available_code_actions
 4884                        .clone()
 4885                        .and_then(|(location, code_actions)| {
 4886                            let snapshot = location.buffer.read(cx).snapshot();
 4887                            let point_range = location.range.to_point(&snapshot);
 4888                            let point_range = point_range.start.row..=point_range.end.row;
 4889                            if point_range.contains(&buffer_row) {
 4890                                Some((location, code_actions))
 4891                            } else {
 4892                                None
 4893                            }
 4894                        })
 4895                        .unzip();
 4896                    let buffer_id = buffer.read(cx).remote_id();
 4897                    let tasks = editor
 4898                        .tasks
 4899                        .get(&(buffer_id, buffer_row))
 4900                        .map(|t| Arc::new(t.to_owned()));
 4901                    if tasks.is_none() && code_actions.is_none() {
 4902                        return None;
 4903                    }
 4904
 4905                    editor.completion_tasks.clear();
 4906                    editor.discard_inline_completion(false, cx);
 4907                    let task_context =
 4908                        tasks
 4909                            .as_ref()
 4910                            .zip(editor.project.clone())
 4911                            .map(|(tasks, project)| {
 4912                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4913                            });
 4914
 4915                    let debugger_flag = cx.has_flag::<Debugger>();
 4916
 4917                    Some(cx.spawn_in(window, async move |editor, cx| {
 4918                        let task_context = match task_context {
 4919                            Some(task_context) => task_context.await,
 4920                            None => None,
 4921                        };
 4922                        let resolved_tasks =
 4923                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4924                                Rc::new(ResolvedTasks {
 4925                                    templates: tasks.resolve(&task_context).collect(),
 4926                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4927                                        multibuffer_point.row,
 4928                                        tasks.column,
 4929                                    )),
 4930                                })
 4931                            });
 4932                        let spawn_straight_away = resolved_tasks.as_ref().map_or(false, |tasks| {
 4933                            tasks
 4934                                .templates
 4935                                .iter()
 4936                                .filter(|task| {
 4937                                    if matches!(task.1.task_type(), task::TaskType::Debug(_)) {
 4938                                        debugger_flag
 4939                                    } else {
 4940                                        true
 4941                                    }
 4942                                })
 4943                                .count()
 4944                                == 1
 4945                        }) && code_actions
 4946                            .as_ref()
 4947                            .map_or(true, |actions| actions.is_empty());
 4948                        if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
 4949                            *editor.context_menu.borrow_mut() =
 4950                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4951                                    buffer,
 4952                                    actions: CodeActionContents {
 4953                                        tasks: resolved_tasks,
 4954                                        actions: code_actions,
 4955                                    },
 4956                                    selected_item: Default::default(),
 4957                                    scroll_handle: UniformListScrollHandle::default(),
 4958                                    deployed_from_indicator,
 4959                                }));
 4960                            if spawn_straight_away {
 4961                                if let Some(task) = editor.confirm_code_action(
 4962                                    &ConfirmCodeAction { item_ix: Some(0) },
 4963                                    window,
 4964                                    cx,
 4965                                ) {
 4966                                    cx.notify();
 4967                                    return task;
 4968                                }
 4969                            }
 4970                            cx.notify();
 4971                            Task::ready(Ok(()))
 4972                        }) {
 4973                            task.await
 4974                        } else {
 4975                            Ok(())
 4976                        }
 4977                    }))
 4978                } else {
 4979                    Some(Task::ready(Ok(())))
 4980                }
 4981            })?;
 4982            if let Some(task) = spawned_test_task {
 4983                task.await?;
 4984            }
 4985
 4986            Ok::<_, anyhow::Error>(())
 4987        })
 4988        .detach_and_log_err(cx);
 4989    }
 4990
 4991    pub fn confirm_code_action(
 4992        &mut self,
 4993        action: &ConfirmCodeAction,
 4994        window: &mut Window,
 4995        cx: &mut Context<Self>,
 4996    ) -> Option<Task<Result<()>>> {
 4997        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4998
 4999        let actions_menu =
 5000            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 5001                menu
 5002            } else {
 5003                return None;
 5004            };
 5005
 5006        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 5007        let action = actions_menu.actions.get(action_ix)?;
 5008        let title = action.label();
 5009        let buffer = actions_menu.buffer;
 5010        let workspace = self.workspace()?;
 5011
 5012        match action {
 5013            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 5014                match resolved_task.task_type() {
 5015                    task::TaskType::Script => workspace.update(cx, |workspace, cx| {
 5016                        workspace::tasks::schedule_resolved_task(
 5017                            workspace,
 5018                            task_source_kind,
 5019                            resolved_task,
 5020                            false,
 5021                            cx,
 5022                        );
 5023
 5024                        Some(Task::ready(Ok(())))
 5025                    }),
 5026                    task::TaskType::Debug(debug_args) => {
 5027                        if debug_args.locator.is_some() {
 5028                            workspace.update(cx, |workspace, cx| {
 5029                                workspace::tasks::schedule_resolved_task(
 5030                                    workspace,
 5031                                    task_source_kind,
 5032                                    resolved_task,
 5033                                    false,
 5034                                    cx,
 5035                                );
 5036                            });
 5037
 5038                            return Some(Task::ready(Ok(())));
 5039                        }
 5040
 5041                        if let Some(project) = self.project.as_ref() {
 5042                            project
 5043                                .update(cx, |project, cx| {
 5044                                    project.start_debug_session(
 5045                                        resolved_task.resolved_debug_adapter_config().unwrap(),
 5046                                        cx,
 5047                                    )
 5048                                })
 5049                                .detach_and_log_err(cx);
 5050                            Some(Task::ready(Ok(())))
 5051                        } else {
 5052                            Some(Task::ready(Ok(())))
 5053                        }
 5054                    }
 5055                }
 5056            }
 5057            CodeActionsItem::CodeAction {
 5058                excerpt_id,
 5059                action,
 5060                provider,
 5061            } => {
 5062                let apply_code_action =
 5063                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 5064                let workspace = workspace.downgrade();
 5065                Some(cx.spawn_in(window, async move |editor, cx| {
 5066                    let project_transaction = apply_code_action.await?;
 5067                    Self::open_project_transaction(
 5068                        &editor,
 5069                        workspace,
 5070                        project_transaction,
 5071                        title,
 5072                        cx,
 5073                    )
 5074                    .await
 5075                }))
 5076            }
 5077        }
 5078    }
 5079
 5080    pub async fn open_project_transaction(
 5081        this: &WeakEntity<Editor>,
 5082        workspace: WeakEntity<Workspace>,
 5083        transaction: ProjectTransaction,
 5084        title: String,
 5085        cx: &mut AsyncWindowContext,
 5086    ) -> Result<()> {
 5087        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 5088        cx.update(|_, cx| {
 5089            entries.sort_unstable_by_key(|(buffer, _)| {
 5090                buffer.read(cx).file().map(|f| f.path().clone())
 5091            });
 5092        })?;
 5093
 5094        // If the project transaction's edits are all contained within this editor, then
 5095        // avoid opening a new editor to display them.
 5096
 5097        if let Some((buffer, transaction)) = entries.first() {
 5098            if entries.len() == 1 {
 5099                let excerpt = this.update(cx, |editor, cx| {
 5100                    editor
 5101                        .buffer()
 5102                        .read(cx)
 5103                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 5104                })?;
 5105                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 5106                    if excerpted_buffer == *buffer {
 5107                        let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
 5108                            let excerpt_range = excerpt_range.to_offset(buffer);
 5109                            buffer
 5110                                .edited_ranges_for_transaction::<usize>(transaction)
 5111                                .all(|range| {
 5112                                    excerpt_range.start <= range.start
 5113                                        && excerpt_range.end >= range.end
 5114                                })
 5115                        })?;
 5116
 5117                        if all_edits_within_excerpt {
 5118                            return Ok(());
 5119                        }
 5120                    }
 5121                }
 5122            }
 5123        } else {
 5124            return Ok(());
 5125        }
 5126
 5127        let mut ranges_to_highlight = Vec::new();
 5128        let excerpt_buffer = cx.new(|cx| {
 5129            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 5130            for (buffer_handle, transaction) in &entries {
 5131                let edited_ranges = buffer_handle
 5132                    .read(cx)
 5133                    .edited_ranges_for_transaction::<Point>(transaction)
 5134                    .collect::<Vec<_>>();
 5135                let (ranges, _) = multibuffer.set_excerpts_for_path(
 5136                    PathKey::for_buffer(buffer_handle, cx),
 5137                    buffer_handle.clone(),
 5138                    edited_ranges,
 5139                    DEFAULT_MULTIBUFFER_CONTEXT,
 5140                    cx,
 5141                );
 5142
 5143                ranges_to_highlight.extend(ranges);
 5144            }
 5145            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5146            multibuffer
 5147        })?;
 5148
 5149        workspace.update_in(cx, |workspace, window, cx| {
 5150            let project = workspace.project().clone();
 5151            let editor =
 5152                cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
 5153            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 5154            editor.update(cx, |editor, cx| {
 5155                editor.highlight_background::<Self>(
 5156                    &ranges_to_highlight,
 5157                    |theme| theme.editor_highlighted_line_background,
 5158                    cx,
 5159                );
 5160            });
 5161        })?;
 5162
 5163        Ok(())
 5164    }
 5165
 5166    pub fn clear_code_action_providers(&mut self) {
 5167        self.code_action_providers.clear();
 5168        self.available_code_actions.take();
 5169    }
 5170
 5171    pub fn add_code_action_provider(
 5172        &mut self,
 5173        provider: Rc<dyn CodeActionProvider>,
 5174        window: &mut Window,
 5175        cx: &mut Context<Self>,
 5176    ) {
 5177        if self
 5178            .code_action_providers
 5179            .iter()
 5180            .any(|existing_provider| existing_provider.id() == provider.id())
 5181        {
 5182            return;
 5183        }
 5184
 5185        self.code_action_providers.push(provider);
 5186        self.refresh_code_actions(window, cx);
 5187    }
 5188
 5189    pub fn remove_code_action_provider(
 5190        &mut self,
 5191        id: Arc<str>,
 5192        window: &mut Window,
 5193        cx: &mut Context<Self>,
 5194    ) {
 5195        self.code_action_providers
 5196            .retain(|provider| provider.id() != id);
 5197        self.refresh_code_actions(window, cx);
 5198    }
 5199
 5200    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 5201        let newest_selection = self.selections.newest_anchor().clone();
 5202        let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
 5203        let buffer = self.buffer.read(cx);
 5204        if newest_selection.head().diff_base_anchor.is_some() {
 5205            return None;
 5206        }
 5207        let (start_buffer, start) =
 5208            buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
 5209        let (end_buffer, end) =
 5210            buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
 5211        if start_buffer != end_buffer {
 5212            return None;
 5213        }
 5214
 5215        self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
 5216            cx.background_executor()
 5217                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5218                .await;
 5219
 5220            let (providers, tasks) = this.update_in(cx, |this, window, cx| {
 5221                let providers = this.code_action_providers.clone();
 5222                let tasks = this
 5223                    .code_action_providers
 5224                    .iter()
 5225                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 5226                    .collect::<Vec<_>>();
 5227                (providers, tasks)
 5228            })?;
 5229
 5230            let mut actions = Vec::new();
 5231            for (provider, provider_actions) in
 5232                providers.into_iter().zip(future::join_all(tasks).await)
 5233            {
 5234                if let Some(provider_actions) = provider_actions.log_err() {
 5235                    actions.extend(provider_actions.into_iter().map(|action| {
 5236                        AvailableCodeAction {
 5237                            excerpt_id: newest_selection.start.excerpt_id,
 5238                            action,
 5239                            provider: provider.clone(),
 5240                        }
 5241                    }));
 5242                }
 5243            }
 5244
 5245            this.update(cx, |this, cx| {
 5246                this.available_code_actions = if actions.is_empty() {
 5247                    None
 5248                } else {
 5249                    Some((
 5250                        Location {
 5251                            buffer: start_buffer,
 5252                            range: start..end,
 5253                        },
 5254                        actions.into(),
 5255                    ))
 5256                };
 5257                cx.notify();
 5258            })
 5259        }));
 5260        None
 5261    }
 5262
 5263    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5264        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5265            self.show_git_blame_inline = false;
 5266
 5267            self.show_git_blame_inline_delay_task =
 5268                Some(cx.spawn_in(window, async move |this, cx| {
 5269                    cx.background_executor().timer(delay).await;
 5270
 5271                    this.update(cx, |this, cx| {
 5272                        this.show_git_blame_inline = true;
 5273                        cx.notify();
 5274                    })
 5275                    .log_err();
 5276                }));
 5277        }
 5278    }
 5279
 5280    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 5281        if self.pending_rename.is_some() {
 5282            return None;
 5283        }
 5284
 5285        let provider = self.semantics_provider.clone()?;
 5286        let buffer = self.buffer.read(cx);
 5287        let newest_selection = self.selections.newest_anchor().clone();
 5288        let cursor_position = newest_selection.head();
 5289        let (cursor_buffer, cursor_buffer_position) =
 5290            buffer.text_anchor_for_position(cursor_position, cx)?;
 5291        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5292        if cursor_buffer != tail_buffer {
 5293            return None;
 5294        }
 5295        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 5296        self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
 5297            cx.background_executor()
 5298                .timer(Duration::from_millis(debounce))
 5299                .await;
 5300
 5301            let highlights = if let Some(highlights) = cx
 5302                .update(|cx| {
 5303                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5304                })
 5305                .ok()
 5306                .flatten()
 5307            {
 5308                highlights.await.log_err()
 5309            } else {
 5310                None
 5311            };
 5312
 5313            if let Some(highlights) = highlights {
 5314                this.update(cx, |this, cx| {
 5315                    if this.pending_rename.is_some() {
 5316                        return;
 5317                    }
 5318
 5319                    let buffer_id = cursor_position.buffer_id;
 5320                    let buffer = this.buffer.read(cx);
 5321                    if !buffer
 5322                        .text_anchor_for_position(cursor_position, cx)
 5323                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5324                    {
 5325                        return;
 5326                    }
 5327
 5328                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5329                    let mut write_ranges = Vec::new();
 5330                    let mut read_ranges = Vec::new();
 5331                    for highlight in highlights {
 5332                        for (excerpt_id, excerpt_range) in
 5333                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 5334                        {
 5335                            let start = highlight
 5336                                .range
 5337                                .start
 5338                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5339                            let end = highlight
 5340                                .range
 5341                                .end
 5342                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5343                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5344                                continue;
 5345                            }
 5346
 5347                            let range = Anchor {
 5348                                buffer_id,
 5349                                excerpt_id,
 5350                                text_anchor: start,
 5351                                diff_base_anchor: None,
 5352                            }..Anchor {
 5353                                buffer_id,
 5354                                excerpt_id,
 5355                                text_anchor: end,
 5356                                diff_base_anchor: None,
 5357                            };
 5358                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5359                                write_ranges.push(range);
 5360                            } else {
 5361                                read_ranges.push(range);
 5362                            }
 5363                        }
 5364                    }
 5365
 5366                    this.highlight_background::<DocumentHighlightRead>(
 5367                        &read_ranges,
 5368                        |theme| theme.editor_document_highlight_read_background,
 5369                        cx,
 5370                    );
 5371                    this.highlight_background::<DocumentHighlightWrite>(
 5372                        &write_ranges,
 5373                        |theme| theme.editor_document_highlight_write_background,
 5374                        cx,
 5375                    );
 5376                    cx.notify();
 5377                })
 5378                .log_err();
 5379            }
 5380        }));
 5381        None
 5382    }
 5383
 5384    pub fn refresh_selected_text_highlights(
 5385        &mut self,
 5386        window: &mut Window,
 5387        cx: &mut Context<Editor>,
 5388    ) {
 5389        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 5390            return;
 5391        }
 5392        self.selection_highlight_task.take();
 5393        if !EditorSettings::get_global(cx).selection_highlight {
 5394            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5395            return;
 5396        }
 5397        if self.selections.count() != 1 || self.selections.line_mode {
 5398            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5399            return;
 5400        }
 5401        let selection = self.selections.newest::<Point>(cx);
 5402        if selection.is_empty() || selection.start.row != selection.end.row {
 5403            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5404            return;
 5405        }
 5406        let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
 5407        self.selection_highlight_task = Some(cx.spawn_in(window, async move |editor, cx| {
 5408            cx.background_executor()
 5409                .timer(Duration::from_millis(debounce))
 5410                .await;
 5411            let Some(Some(matches_task)) = editor
 5412                .update_in(cx, |editor, _, cx| {
 5413                    if editor.selections.count() != 1 || editor.selections.line_mode {
 5414                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5415                        return None;
 5416                    }
 5417                    let selection = editor.selections.newest::<Point>(cx);
 5418                    if selection.is_empty() || selection.start.row != selection.end.row {
 5419                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5420                        return None;
 5421                    }
 5422                    let buffer = editor.buffer().read(cx).snapshot(cx);
 5423                    let query = buffer.text_for_range(selection.range()).collect::<String>();
 5424                    if query.trim().is_empty() {
 5425                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5426                        return None;
 5427                    }
 5428                    Some(cx.background_spawn(async move {
 5429                        let mut ranges = Vec::new();
 5430                        let selection_anchors = selection.range().to_anchors(&buffer);
 5431                        for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
 5432                            for (search_buffer, search_range, excerpt_id) in
 5433                                buffer.range_to_buffer_ranges(range)
 5434                            {
 5435                                ranges.extend(
 5436                                    project::search::SearchQuery::text(
 5437                                        query.clone(),
 5438                                        false,
 5439                                        false,
 5440                                        false,
 5441                                        Default::default(),
 5442                                        Default::default(),
 5443                                        None,
 5444                                    )
 5445                                    .unwrap()
 5446                                    .search(search_buffer, Some(search_range.clone()))
 5447                                    .await
 5448                                    .into_iter()
 5449                                    .filter_map(
 5450                                        |match_range| {
 5451                                            let start = search_buffer.anchor_after(
 5452                                                search_range.start + match_range.start,
 5453                                            );
 5454                                            let end = search_buffer.anchor_before(
 5455                                                search_range.start + match_range.end,
 5456                                            );
 5457                                            let range = Anchor::range_in_buffer(
 5458                                                excerpt_id,
 5459                                                search_buffer.remote_id(),
 5460                                                start..end,
 5461                                            );
 5462                                            (range != selection_anchors).then_some(range)
 5463                                        },
 5464                                    ),
 5465                                );
 5466                            }
 5467                        }
 5468                        ranges
 5469                    }))
 5470                })
 5471                .log_err()
 5472            else {
 5473                return;
 5474            };
 5475            let matches = matches_task.await;
 5476            editor
 5477                .update_in(cx, |editor, _, cx| {
 5478                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5479                    if !matches.is_empty() {
 5480                        editor.highlight_background::<SelectedTextHighlight>(
 5481                            &matches,
 5482                            |theme| theme.editor_document_highlight_bracket_background,
 5483                            cx,
 5484                        )
 5485                    }
 5486                })
 5487                .log_err();
 5488        }));
 5489    }
 5490
 5491    pub fn refresh_inline_completion(
 5492        &mut self,
 5493        debounce: bool,
 5494        user_requested: bool,
 5495        window: &mut Window,
 5496        cx: &mut Context<Self>,
 5497    ) -> Option<()> {
 5498        let provider = self.edit_prediction_provider()?;
 5499        let cursor = self.selections.newest_anchor().head();
 5500        let (buffer, cursor_buffer_position) =
 5501            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5502
 5503        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 5504            self.discard_inline_completion(false, cx);
 5505            return None;
 5506        }
 5507
 5508        if !user_requested
 5509            && (!self.should_show_edit_predictions()
 5510                || !self.is_focused(window)
 5511                || buffer.read(cx).is_empty())
 5512        {
 5513            self.discard_inline_completion(false, cx);
 5514            return None;
 5515        }
 5516
 5517        self.update_visible_inline_completion(window, cx);
 5518        provider.refresh(
 5519            self.project.clone(),
 5520            buffer,
 5521            cursor_buffer_position,
 5522            debounce,
 5523            cx,
 5524        );
 5525        Some(())
 5526    }
 5527
 5528    fn show_edit_predictions_in_menu(&self) -> bool {
 5529        match self.edit_prediction_settings {
 5530            EditPredictionSettings::Disabled => false,
 5531            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 5532        }
 5533    }
 5534
 5535    pub fn edit_predictions_enabled(&self) -> bool {
 5536        match self.edit_prediction_settings {
 5537            EditPredictionSettings::Disabled => false,
 5538            EditPredictionSettings::Enabled { .. } => true,
 5539        }
 5540    }
 5541
 5542    fn edit_prediction_requires_modifier(&self) -> bool {
 5543        match self.edit_prediction_settings {
 5544            EditPredictionSettings::Disabled => false,
 5545            EditPredictionSettings::Enabled {
 5546                preview_requires_modifier,
 5547                ..
 5548            } => preview_requires_modifier,
 5549        }
 5550    }
 5551
 5552    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 5553        if self.edit_prediction_provider.is_none() {
 5554            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5555        } else {
 5556            let selection = self.selections.newest_anchor();
 5557            let cursor = selection.head();
 5558
 5559            if let Some((buffer, cursor_buffer_position)) =
 5560                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5561            {
 5562                self.edit_prediction_settings =
 5563                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5564            }
 5565        }
 5566    }
 5567
 5568    fn edit_prediction_settings_at_position(
 5569        &self,
 5570        buffer: &Entity<Buffer>,
 5571        buffer_position: language::Anchor,
 5572        cx: &App,
 5573    ) -> EditPredictionSettings {
 5574        if !self.mode.is_full()
 5575            || !self.show_inline_completions_override.unwrap_or(true)
 5576            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 5577        {
 5578            return EditPredictionSettings::Disabled;
 5579        }
 5580
 5581        let buffer = buffer.read(cx);
 5582
 5583        let file = buffer.file();
 5584
 5585        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 5586            return EditPredictionSettings::Disabled;
 5587        };
 5588
 5589        let by_provider = matches!(
 5590            self.menu_inline_completions_policy,
 5591            MenuInlineCompletionsPolicy::ByProvider
 5592        );
 5593
 5594        let show_in_menu = by_provider
 5595            && self
 5596                .edit_prediction_provider
 5597                .as_ref()
 5598                .map_or(false, |provider| {
 5599                    provider.provider.show_completions_in_menu()
 5600                });
 5601
 5602        let preview_requires_modifier =
 5603            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 5604
 5605        EditPredictionSettings::Enabled {
 5606            show_in_menu,
 5607            preview_requires_modifier,
 5608        }
 5609    }
 5610
 5611    fn should_show_edit_predictions(&self) -> bool {
 5612        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 5613    }
 5614
 5615    pub fn edit_prediction_preview_is_active(&self) -> bool {
 5616        matches!(
 5617            self.edit_prediction_preview,
 5618            EditPredictionPreview::Active { .. }
 5619        )
 5620    }
 5621
 5622    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 5623        let cursor = self.selections.newest_anchor().head();
 5624        if let Some((buffer, cursor_position)) =
 5625            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5626        {
 5627            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 5628        } else {
 5629            false
 5630        }
 5631    }
 5632
 5633    fn edit_predictions_enabled_in_buffer(
 5634        &self,
 5635        buffer: &Entity<Buffer>,
 5636        buffer_position: language::Anchor,
 5637        cx: &App,
 5638    ) -> bool {
 5639        maybe!({
 5640            if self.read_only(cx) {
 5641                return Some(false);
 5642            }
 5643            let provider = self.edit_prediction_provider()?;
 5644            if !provider.is_enabled(&buffer, buffer_position, cx) {
 5645                return Some(false);
 5646            }
 5647            let buffer = buffer.read(cx);
 5648            let Some(file) = buffer.file() else {
 5649                return Some(true);
 5650            };
 5651            let settings = all_language_settings(Some(file), cx);
 5652            Some(settings.edit_predictions_enabled_for_file(file, cx))
 5653        })
 5654        .unwrap_or(false)
 5655    }
 5656
 5657    fn cycle_inline_completion(
 5658        &mut self,
 5659        direction: Direction,
 5660        window: &mut Window,
 5661        cx: &mut Context<Self>,
 5662    ) -> Option<()> {
 5663        let provider = self.edit_prediction_provider()?;
 5664        let cursor = self.selections.newest_anchor().head();
 5665        let (buffer, cursor_buffer_position) =
 5666            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5667        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 5668            return None;
 5669        }
 5670
 5671        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5672        self.update_visible_inline_completion(window, cx);
 5673
 5674        Some(())
 5675    }
 5676
 5677    pub fn show_inline_completion(
 5678        &mut self,
 5679        _: &ShowEditPrediction,
 5680        window: &mut Window,
 5681        cx: &mut Context<Self>,
 5682    ) {
 5683        if !self.has_active_inline_completion() {
 5684            self.refresh_inline_completion(false, true, window, cx);
 5685            return;
 5686        }
 5687
 5688        self.update_visible_inline_completion(window, cx);
 5689    }
 5690
 5691    pub fn display_cursor_names(
 5692        &mut self,
 5693        _: &DisplayCursorNames,
 5694        window: &mut Window,
 5695        cx: &mut Context<Self>,
 5696    ) {
 5697        self.show_cursor_names(window, cx);
 5698    }
 5699
 5700    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5701        self.show_cursor_names = true;
 5702        cx.notify();
 5703        cx.spawn_in(window, async move |this, cx| {
 5704            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5705            this.update(cx, |this, cx| {
 5706                this.show_cursor_names = false;
 5707                cx.notify()
 5708            })
 5709            .ok()
 5710        })
 5711        .detach();
 5712    }
 5713
 5714    pub fn next_edit_prediction(
 5715        &mut self,
 5716        _: &NextEditPrediction,
 5717        window: &mut Window,
 5718        cx: &mut Context<Self>,
 5719    ) {
 5720        if self.has_active_inline_completion() {
 5721            self.cycle_inline_completion(Direction::Next, window, cx);
 5722        } else {
 5723            let is_copilot_disabled = self
 5724                .refresh_inline_completion(false, true, window, cx)
 5725                .is_none();
 5726            if is_copilot_disabled {
 5727                cx.propagate();
 5728            }
 5729        }
 5730    }
 5731
 5732    pub fn previous_edit_prediction(
 5733        &mut self,
 5734        _: &PreviousEditPrediction,
 5735        window: &mut Window,
 5736        cx: &mut Context<Self>,
 5737    ) {
 5738        if self.has_active_inline_completion() {
 5739            self.cycle_inline_completion(Direction::Prev, window, cx);
 5740        } else {
 5741            let is_copilot_disabled = self
 5742                .refresh_inline_completion(false, true, window, cx)
 5743                .is_none();
 5744            if is_copilot_disabled {
 5745                cx.propagate();
 5746            }
 5747        }
 5748    }
 5749
 5750    pub fn accept_edit_prediction(
 5751        &mut self,
 5752        _: &AcceptEditPrediction,
 5753        window: &mut Window,
 5754        cx: &mut Context<Self>,
 5755    ) {
 5756        if self.show_edit_predictions_in_menu() {
 5757            self.hide_context_menu(window, cx);
 5758        }
 5759
 5760        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5761            return;
 5762        };
 5763
 5764        self.report_inline_completion_event(
 5765            active_inline_completion.completion_id.clone(),
 5766            true,
 5767            cx,
 5768        );
 5769
 5770        match &active_inline_completion.completion {
 5771            InlineCompletion::Move { target, .. } => {
 5772                let target = *target;
 5773
 5774                if let Some(position_map) = &self.last_position_map {
 5775                    if position_map
 5776                        .visible_row_range
 5777                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5778                        || !self.edit_prediction_requires_modifier()
 5779                    {
 5780                        self.unfold_ranges(&[target..target], true, false, cx);
 5781                        // Note that this is also done in vim's handler of the Tab action.
 5782                        self.change_selections(
 5783                            Some(Autoscroll::newest()),
 5784                            window,
 5785                            cx,
 5786                            |selections| {
 5787                                selections.select_anchor_ranges([target..target]);
 5788                            },
 5789                        );
 5790                        self.clear_row_highlights::<EditPredictionPreview>();
 5791
 5792                        self.edit_prediction_preview
 5793                            .set_previous_scroll_position(None);
 5794                    } else {
 5795                        self.edit_prediction_preview
 5796                            .set_previous_scroll_position(Some(
 5797                                position_map.snapshot.scroll_anchor,
 5798                            ));
 5799
 5800                        self.highlight_rows::<EditPredictionPreview>(
 5801                            target..target,
 5802                            cx.theme().colors().editor_highlighted_line_background,
 5803                            true,
 5804                            cx,
 5805                        );
 5806                        self.request_autoscroll(Autoscroll::fit(), cx);
 5807                    }
 5808                }
 5809            }
 5810            InlineCompletion::Edit { edits, .. } => {
 5811                if let Some(provider) = self.edit_prediction_provider() {
 5812                    provider.accept(cx);
 5813                }
 5814
 5815                let snapshot = self.buffer.read(cx).snapshot(cx);
 5816                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5817
 5818                self.buffer.update(cx, |buffer, cx| {
 5819                    buffer.edit(edits.iter().cloned(), None, cx)
 5820                });
 5821
 5822                self.change_selections(None, window, cx, |s| {
 5823                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5824                });
 5825
 5826                self.update_visible_inline_completion(window, cx);
 5827                if self.active_inline_completion.is_none() {
 5828                    self.refresh_inline_completion(true, true, window, cx);
 5829                }
 5830
 5831                cx.notify();
 5832            }
 5833        }
 5834
 5835        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 5836    }
 5837
 5838    pub fn accept_partial_inline_completion(
 5839        &mut self,
 5840        _: &AcceptPartialEditPrediction,
 5841        window: &mut Window,
 5842        cx: &mut Context<Self>,
 5843    ) {
 5844        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5845            return;
 5846        };
 5847        if self.selections.count() != 1 {
 5848            return;
 5849        }
 5850
 5851        self.report_inline_completion_event(
 5852            active_inline_completion.completion_id.clone(),
 5853            true,
 5854            cx,
 5855        );
 5856
 5857        match &active_inline_completion.completion {
 5858            InlineCompletion::Move { target, .. } => {
 5859                let target = *target;
 5860                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5861                    selections.select_anchor_ranges([target..target]);
 5862                });
 5863            }
 5864            InlineCompletion::Edit { edits, .. } => {
 5865                // Find an insertion that starts at the cursor position.
 5866                let snapshot = self.buffer.read(cx).snapshot(cx);
 5867                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5868                let insertion = edits.iter().find_map(|(range, text)| {
 5869                    let range = range.to_offset(&snapshot);
 5870                    if range.is_empty() && range.start == cursor_offset {
 5871                        Some(text)
 5872                    } else {
 5873                        None
 5874                    }
 5875                });
 5876
 5877                if let Some(text) = insertion {
 5878                    let mut partial_completion = text
 5879                        .chars()
 5880                        .by_ref()
 5881                        .take_while(|c| c.is_alphabetic())
 5882                        .collect::<String>();
 5883                    if partial_completion.is_empty() {
 5884                        partial_completion = text
 5885                            .chars()
 5886                            .by_ref()
 5887                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5888                            .collect::<String>();
 5889                    }
 5890
 5891                    cx.emit(EditorEvent::InputHandled {
 5892                        utf16_range_to_replace: None,
 5893                        text: partial_completion.clone().into(),
 5894                    });
 5895
 5896                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5897
 5898                    self.refresh_inline_completion(true, true, window, cx);
 5899                    cx.notify();
 5900                } else {
 5901                    self.accept_edit_prediction(&Default::default(), window, cx);
 5902                }
 5903            }
 5904        }
 5905    }
 5906
 5907    fn discard_inline_completion(
 5908        &mut self,
 5909        should_report_inline_completion_event: bool,
 5910        cx: &mut Context<Self>,
 5911    ) -> bool {
 5912        if should_report_inline_completion_event {
 5913            let completion_id = self
 5914                .active_inline_completion
 5915                .as_ref()
 5916                .and_then(|active_completion| active_completion.completion_id.clone());
 5917
 5918            self.report_inline_completion_event(completion_id, false, cx);
 5919        }
 5920
 5921        if let Some(provider) = self.edit_prediction_provider() {
 5922            provider.discard(cx);
 5923        }
 5924
 5925        self.take_active_inline_completion(cx)
 5926    }
 5927
 5928    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5929        let Some(provider) = self.edit_prediction_provider() else {
 5930            return;
 5931        };
 5932
 5933        let Some((_, buffer, _)) = self
 5934            .buffer
 5935            .read(cx)
 5936            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5937        else {
 5938            return;
 5939        };
 5940
 5941        let extension = buffer
 5942            .read(cx)
 5943            .file()
 5944            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5945
 5946        let event_type = match accepted {
 5947            true => "Edit Prediction Accepted",
 5948            false => "Edit Prediction Discarded",
 5949        };
 5950        telemetry::event!(
 5951            event_type,
 5952            provider = provider.name(),
 5953            prediction_id = id,
 5954            suggestion_accepted = accepted,
 5955            file_extension = extension,
 5956        );
 5957    }
 5958
 5959    pub fn has_active_inline_completion(&self) -> bool {
 5960        self.active_inline_completion.is_some()
 5961    }
 5962
 5963    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5964        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5965            return false;
 5966        };
 5967
 5968        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5969        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5970        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5971        true
 5972    }
 5973
 5974    /// Returns true when we're displaying the edit prediction popover below the cursor
 5975    /// like we are not previewing and the LSP autocomplete menu is visible
 5976    /// or we are in `when_holding_modifier` mode.
 5977    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5978        if self.edit_prediction_preview_is_active()
 5979            || !self.show_edit_predictions_in_menu()
 5980            || !self.edit_predictions_enabled()
 5981        {
 5982            return false;
 5983        }
 5984
 5985        if self.has_visible_completions_menu() {
 5986            return true;
 5987        }
 5988
 5989        has_completion && self.edit_prediction_requires_modifier()
 5990    }
 5991
 5992    fn handle_modifiers_changed(
 5993        &mut self,
 5994        modifiers: Modifiers,
 5995        position_map: &PositionMap,
 5996        window: &mut Window,
 5997        cx: &mut Context<Self>,
 5998    ) {
 5999        if self.show_edit_predictions_in_menu() {
 6000            self.update_edit_prediction_preview(&modifiers, window, cx);
 6001        }
 6002
 6003        self.update_selection_mode(&modifiers, position_map, window, cx);
 6004
 6005        let mouse_position = window.mouse_position();
 6006        if !position_map.text_hitbox.is_hovered(window) {
 6007            return;
 6008        }
 6009
 6010        self.update_hovered_link(
 6011            position_map.point_for_position(mouse_position),
 6012            &position_map.snapshot,
 6013            modifiers,
 6014            window,
 6015            cx,
 6016        )
 6017    }
 6018
 6019    fn update_selection_mode(
 6020        &mut self,
 6021        modifiers: &Modifiers,
 6022        position_map: &PositionMap,
 6023        window: &mut Window,
 6024        cx: &mut Context<Self>,
 6025    ) {
 6026        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 6027            return;
 6028        }
 6029
 6030        let mouse_position = window.mouse_position();
 6031        let point_for_position = position_map.point_for_position(mouse_position);
 6032        let position = point_for_position.previous_valid;
 6033
 6034        self.select(
 6035            SelectPhase::BeginColumnar {
 6036                position,
 6037                reset: false,
 6038                goal_column: point_for_position.exact_unclipped.column(),
 6039            },
 6040            window,
 6041            cx,
 6042        );
 6043    }
 6044
 6045    fn update_edit_prediction_preview(
 6046        &mut self,
 6047        modifiers: &Modifiers,
 6048        window: &mut Window,
 6049        cx: &mut Context<Self>,
 6050    ) {
 6051        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 6052        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 6053            return;
 6054        };
 6055
 6056        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 6057            if matches!(
 6058                self.edit_prediction_preview,
 6059                EditPredictionPreview::Inactive { .. }
 6060            ) {
 6061                self.edit_prediction_preview = EditPredictionPreview::Active {
 6062                    previous_scroll_position: None,
 6063                    since: Instant::now(),
 6064                };
 6065
 6066                self.update_visible_inline_completion(window, cx);
 6067                cx.notify();
 6068            }
 6069        } else if let EditPredictionPreview::Active {
 6070            previous_scroll_position,
 6071            since,
 6072        } = self.edit_prediction_preview
 6073        {
 6074            if let (Some(previous_scroll_position), Some(position_map)) =
 6075                (previous_scroll_position, self.last_position_map.as_ref())
 6076            {
 6077                self.set_scroll_position(
 6078                    previous_scroll_position
 6079                        .scroll_position(&position_map.snapshot.display_snapshot),
 6080                    window,
 6081                    cx,
 6082                );
 6083            }
 6084
 6085            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 6086                released_too_fast: since.elapsed() < Duration::from_millis(200),
 6087            };
 6088            self.clear_row_highlights::<EditPredictionPreview>();
 6089            self.update_visible_inline_completion(window, cx);
 6090            cx.notify();
 6091        }
 6092    }
 6093
 6094    fn update_visible_inline_completion(
 6095        &mut self,
 6096        _window: &mut Window,
 6097        cx: &mut Context<Self>,
 6098    ) -> Option<()> {
 6099        let selection = self.selections.newest_anchor();
 6100        let cursor = selection.head();
 6101        let multibuffer = self.buffer.read(cx).snapshot(cx);
 6102        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 6103        let excerpt_id = cursor.excerpt_id;
 6104
 6105        let show_in_menu = self.show_edit_predictions_in_menu();
 6106        let completions_menu_has_precedence = !show_in_menu
 6107            && (self.context_menu.borrow().is_some()
 6108                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 6109
 6110        if completions_menu_has_precedence
 6111            || !offset_selection.is_empty()
 6112            || self
 6113                .active_inline_completion
 6114                .as_ref()
 6115                .map_or(false, |completion| {
 6116                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 6117                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 6118                    !invalidation_range.contains(&offset_selection.head())
 6119                })
 6120        {
 6121            self.discard_inline_completion(false, cx);
 6122            return None;
 6123        }
 6124
 6125        self.take_active_inline_completion(cx);
 6126        let Some(provider) = self.edit_prediction_provider() else {
 6127            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 6128            return None;
 6129        };
 6130
 6131        let (buffer, cursor_buffer_position) =
 6132            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 6133
 6134        self.edit_prediction_settings =
 6135            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 6136
 6137        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 6138
 6139        if self.edit_prediction_indent_conflict {
 6140            let cursor_point = cursor.to_point(&multibuffer);
 6141
 6142            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 6143
 6144            if let Some((_, indent)) = indents.iter().next() {
 6145                if indent.len == cursor_point.column {
 6146                    self.edit_prediction_indent_conflict = false;
 6147                }
 6148            }
 6149        }
 6150
 6151        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 6152        let edits = inline_completion
 6153            .edits
 6154            .into_iter()
 6155            .flat_map(|(range, new_text)| {
 6156                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 6157                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 6158                Some((start..end, new_text))
 6159            })
 6160            .collect::<Vec<_>>();
 6161        if edits.is_empty() {
 6162            return None;
 6163        }
 6164
 6165        let first_edit_start = edits.first().unwrap().0.start;
 6166        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 6167        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 6168
 6169        let last_edit_end = edits.last().unwrap().0.end;
 6170        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 6171        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 6172
 6173        let cursor_row = cursor.to_point(&multibuffer).row;
 6174
 6175        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 6176
 6177        let mut inlay_ids = Vec::new();
 6178        let invalidation_row_range;
 6179        let move_invalidation_row_range = if cursor_row < edit_start_row {
 6180            Some(cursor_row..edit_end_row)
 6181        } else if cursor_row > edit_end_row {
 6182            Some(edit_start_row..cursor_row)
 6183        } else {
 6184            None
 6185        };
 6186        let is_move =
 6187            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 6188        let completion = if is_move {
 6189            invalidation_row_range =
 6190                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 6191            let target = first_edit_start;
 6192            InlineCompletion::Move { target, snapshot }
 6193        } else {
 6194            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 6195                && !self.inline_completions_hidden_for_vim_mode;
 6196
 6197            if show_completions_in_buffer {
 6198                if edits
 6199                    .iter()
 6200                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 6201                {
 6202                    let mut inlays = Vec::new();
 6203                    for (range, new_text) in &edits {
 6204                        let inlay = Inlay::inline_completion(
 6205                            post_inc(&mut self.next_inlay_id),
 6206                            range.start,
 6207                            new_text.as_str(),
 6208                        );
 6209                        inlay_ids.push(inlay.id);
 6210                        inlays.push(inlay);
 6211                    }
 6212
 6213                    self.splice_inlays(&[], inlays, cx);
 6214                } else {
 6215                    let background_color = cx.theme().status().deleted_background;
 6216                    self.highlight_text::<InlineCompletionHighlight>(
 6217                        edits.iter().map(|(range, _)| range.clone()).collect(),
 6218                        HighlightStyle {
 6219                            background_color: Some(background_color),
 6220                            ..Default::default()
 6221                        },
 6222                        cx,
 6223                    );
 6224                }
 6225            }
 6226
 6227            invalidation_row_range = edit_start_row..edit_end_row;
 6228
 6229            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 6230                if provider.show_tab_accept_marker() {
 6231                    EditDisplayMode::TabAccept
 6232                } else {
 6233                    EditDisplayMode::Inline
 6234                }
 6235            } else {
 6236                EditDisplayMode::DiffPopover
 6237            };
 6238
 6239            InlineCompletion::Edit {
 6240                edits,
 6241                edit_preview: inline_completion.edit_preview,
 6242                display_mode,
 6243                snapshot,
 6244            }
 6245        };
 6246
 6247        let invalidation_range = multibuffer
 6248            .anchor_before(Point::new(invalidation_row_range.start, 0))
 6249            ..multibuffer.anchor_after(Point::new(
 6250                invalidation_row_range.end,
 6251                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 6252            ));
 6253
 6254        self.stale_inline_completion_in_menu = None;
 6255        self.active_inline_completion = Some(InlineCompletionState {
 6256            inlay_ids,
 6257            completion,
 6258            completion_id: inline_completion.id,
 6259            invalidation_range,
 6260        });
 6261
 6262        cx.notify();
 6263
 6264        Some(())
 6265    }
 6266
 6267    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 6268        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 6269    }
 6270
 6271    fn render_code_actions_indicator(
 6272        &self,
 6273        _style: &EditorStyle,
 6274        row: DisplayRow,
 6275        is_active: bool,
 6276        breakpoint: Option<&(Anchor, Breakpoint)>,
 6277        cx: &mut Context<Self>,
 6278    ) -> Option<IconButton> {
 6279        let color = Color::Muted;
 6280        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6281        let show_tooltip = !self.context_menu_visible();
 6282
 6283        if self.available_code_actions.is_some() {
 6284            Some(
 6285                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 6286                    .shape(ui::IconButtonShape::Square)
 6287                    .icon_size(IconSize::XSmall)
 6288                    .icon_color(color)
 6289                    .toggle_state(is_active)
 6290                    .when(show_tooltip, |this| {
 6291                        this.tooltip({
 6292                            let focus_handle = self.focus_handle.clone();
 6293                            move |window, cx| {
 6294                                Tooltip::for_action_in(
 6295                                    "Toggle Code Actions",
 6296                                    &ToggleCodeActions {
 6297                                        deployed_from_indicator: None,
 6298                                    },
 6299                                    &focus_handle,
 6300                                    window,
 6301                                    cx,
 6302                                )
 6303                            }
 6304                        })
 6305                    })
 6306                    .on_click(cx.listener(move |editor, _e, window, cx| {
 6307                        window.focus(&editor.focus_handle(cx));
 6308                        editor.toggle_code_actions(
 6309                            &ToggleCodeActions {
 6310                                deployed_from_indicator: Some(row),
 6311                            },
 6312                            window,
 6313                            cx,
 6314                        );
 6315                    }))
 6316                    .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6317                        editor.set_breakpoint_context_menu(
 6318                            row,
 6319                            position,
 6320                            event.down.position,
 6321                            window,
 6322                            cx,
 6323                        );
 6324                    })),
 6325            )
 6326        } else {
 6327            None
 6328        }
 6329    }
 6330
 6331    fn clear_tasks(&mut self) {
 6332        self.tasks.clear()
 6333    }
 6334
 6335    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 6336        if self.tasks.insert(key, value).is_some() {
 6337            // This case should hopefully be rare, but just in case...
 6338            log::error!(
 6339                "multiple different run targets found on a single line, only the last target will be rendered"
 6340            )
 6341        }
 6342    }
 6343
 6344    /// Get all display points of breakpoints that will be rendered within editor
 6345    ///
 6346    /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
 6347    /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
 6348    /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
 6349    fn active_breakpoints(
 6350        &self,
 6351        range: Range<DisplayRow>,
 6352        window: &mut Window,
 6353        cx: &mut Context<Self>,
 6354    ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
 6355        let mut breakpoint_display_points = HashMap::default();
 6356
 6357        let Some(breakpoint_store) = self.breakpoint_store.clone() else {
 6358            return breakpoint_display_points;
 6359        };
 6360
 6361        let snapshot = self.snapshot(window, cx);
 6362
 6363        let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
 6364        let Some(project) = self.project.as_ref() else {
 6365            return breakpoint_display_points;
 6366        };
 6367
 6368        let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
 6369            ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
 6370
 6371        for (buffer_snapshot, range, excerpt_id) in
 6372            multi_buffer_snapshot.range_to_buffer_ranges(range)
 6373        {
 6374            let Some(buffer) = project.read_with(cx, |this, cx| {
 6375                this.buffer_for_id(buffer_snapshot.remote_id(), cx)
 6376            }) else {
 6377                continue;
 6378            };
 6379            let breakpoints = breakpoint_store.read(cx).breakpoints(
 6380                &buffer,
 6381                Some(
 6382                    buffer_snapshot.anchor_before(range.start)
 6383                        ..buffer_snapshot.anchor_after(range.end),
 6384                ),
 6385                buffer_snapshot,
 6386                cx,
 6387            );
 6388            for (anchor, breakpoint) in breakpoints {
 6389                let multi_buffer_anchor =
 6390                    Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
 6391                let position = multi_buffer_anchor
 6392                    .to_point(&multi_buffer_snapshot)
 6393                    .to_display_point(&snapshot);
 6394
 6395                breakpoint_display_points
 6396                    .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
 6397            }
 6398        }
 6399
 6400        breakpoint_display_points
 6401    }
 6402
 6403    fn breakpoint_context_menu(
 6404        &self,
 6405        anchor: Anchor,
 6406        window: &mut Window,
 6407        cx: &mut Context<Self>,
 6408    ) -> Entity<ui::ContextMenu> {
 6409        let weak_editor = cx.weak_entity();
 6410        let focus_handle = self.focus_handle(cx);
 6411
 6412        let row = self
 6413            .buffer
 6414            .read(cx)
 6415            .snapshot(cx)
 6416            .summary_for_anchor::<Point>(&anchor)
 6417            .row;
 6418
 6419        let breakpoint = self
 6420            .breakpoint_at_row(row, window, cx)
 6421            .map(|(anchor, bp)| (anchor, Arc::from(bp)));
 6422
 6423        let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
 6424            "Edit Log Breakpoint"
 6425        } else {
 6426            "Set Log Breakpoint"
 6427        };
 6428
 6429        let condition_breakpoint_msg = if breakpoint
 6430            .as_ref()
 6431            .is_some_and(|bp| bp.1.condition.is_some())
 6432        {
 6433            "Edit Condition Breakpoint"
 6434        } else {
 6435            "Set Condition Breakpoint"
 6436        };
 6437
 6438        let hit_condition_breakpoint_msg = if breakpoint
 6439            .as_ref()
 6440            .is_some_and(|bp| bp.1.hit_condition.is_some())
 6441        {
 6442            "Edit Hit Condition Breakpoint"
 6443        } else {
 6444            "Set Hit Condition Breakpoint"
 6445        };
 6446
 6447        let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
 6448            "Unset Breakpoint"
 6449        } else {
 6450            "Set Breakpoint"
 6451        };
 6452
 6453        let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
 6454            .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
 6455
 6456        let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
 6457            BreakpointState::Enabled => Some("Disable"),
 6458            BreakpointState::Disabled => Some("Enable"),
 6459        });
 6460
 6461        let (anchor, breakpoint) =
 6462            breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
 6463
 6464        ui::ContextMenu::build(window, cx, |menu, _, _cx| {
 6465            menu.on_blur_subscription(Subscription::new(|| {}))
 6466                .context(focus_handle)
 6467                .when(run_to_cursor, |this| {
 6468                    let weak_editor = weak_editor.clone();
 6469                    this.entry("Run to cursor", None, move |window, cx| {
 6470                        weak_editor
 6471                            .update(cx, |editor, cx| {
 6472                                editor.change_selections(None, window, cx, |s| {
 6473                                    s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
 6474                                });
 6475                            })
 6476                            .ok();
 6477
 6478                        window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
 6479                    })
 6480                    .separator()
 6481                })
 6482                .when_some(toggle_state_msg, |this, msg| {
 6483                    this.entry(msg, None, {
 6484                        let weak_editor = weak_editor.clone();
 6485                        let breakpoint = breakpoint.clone();
 6486                        move |_window, cx| {
 6487                            weak_editor
 6488                                .update(cx, |this, cx| {
 6489                                    this.edit_breakpoint_at_anchor(
 6490                                        anchor,
 6491                                        breakpoint.as_ref().clone(),
 6492                                        BreakpointEditAction::InvertState,
 6493                                        cx,
 6494                                    );
 6495                                })
 6496                                .log_err();
 6497                        }
 6498                    })
 6499                })
 6500                .entry(set_breakpoint_msg, None, {
 6501                    let weak_editor = weak_editor.clone();
 6502                    let breakpoint = breakpoint.clone();
 6503                    move |_window, cx| {
 6504                        weak_editor
 6505                            .update(cx, |this, cx| {
 6506                                this.edit_breakpoint_at_anchor(
 6507                                    anchor,
 6508                                    breakpoint.as_ref().clone(),
 6509                                    BreakpointEditAction::Toggle,
 6510                                    cx,
 6511                                );
 6512                            })
 6513                            .log_err();
 6514                    }
 6515                })
 6516                .entry(log_breakpoint_msg, None, {
 6517                    let breakpoint = breakpoint.clone();
 6518                    let weak_editor = weak_editor.clone();
 6519                    move |window, cx| {
 6520                        weak_editor
 6521                            .update(cx, |this, cx| {
 6522                                this.add_edit_breakpoint_block(
 6523                                    anchor,
 6524                                    breakpoint.as_ref(),
 6525                                    BreakpointPromptEditAction::Log,
 6526                                    window,
 6527                                    cx,
 6528                                );
 6529                            })
 6530                            .log_err();
 6531                    }
 6532                })
 6533                .entry(condition_breakpoint_msg, None, {
 6534                    let breakpoint = breakpoint.clone();
 6535                    let weak_editor = weak_editor.clone();
 6536                    move |window, cx| {
 6537                        weak_editor
 6538                            .update(cx, |this, cx| {
 6539                                this.add_edit_breakpoint_block(
 6540                                    anchor,
 6541                                    breakpoint.as_ref(),
 6542                                    BreakpointPromptEditAction::Condition,
 6543                                    window,
 6544                                    cx,
 6545                                );
 6546                            })
 6547                            .log_err();
 6548                    }
 6549                })
 6550                .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
 6551                    weak_editor
 6552                        .update(cx, |this, cx| {
 6553                            this.add_edit_breakpoint_block(
 6554                                anchor,
 6555                                breakpoint.as_ref(),
 6556                                BreakpointPromptEditAction::HitCondition,
 6557                                window,
 6558                                cx,
 6559                            );
 6560                        })
 6561                        .log_err();
 6562                })
 6563        })
 6564    }
 6565
 6566    fn render_breakpoint(
 6567        &self,
 6568        position: Anchor,
 6569        row: DisplayRow,
 6570        breakpoint: &Breakpoint,
 6571        cx: &mut Context<Self>,
 6572    ) -> IconButton {
 6573        let (color, icon) = {
 6574            let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
 6575                (false, false) => ui::IconName::DebugBreakpoint,
 6576                (true, false) => ui::IconName::DebugLogBreakpoint,
 6577                (false, true) => ui::IconName::DebugDisabledBreakpoint,
 6578                (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
 6579            };
 6580
 6581            let color = if self
 6582                .gutter_breakpoint_indicator
 6583                .0
 6584                .is_some_and(|(point, is_visible)| is_visible && point.row() == row)
 6585            {
 6586                Color::Hint
 6587            } else {
 6588                Color::Debugger
 6589            };
 6590
 6591            (color, icon)
 6592        };
 6593
 6594        let breakpoint = Arc::from(breakpoint.clone());
 6595
 6596        IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
 6597            .icon_size(IconSize::XSmall)
 6598            .size(ui::ButtonSize::None)
 6599            .icon_color(color)
 6600            .style(ButtonStyle::Transparent)
 6601            .on_click(cx.listener({
 6602                let breakpoint = breakpoint.clone();
 6603
 6604                move |editor, event: &ClickEvent, window, cx| {
 6605                    let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
 6606                        BreakpointEditAction::InvertState
 6607                    } else {
 6608                        BreakpointEditAction::Toggle
 6609                    };
 6610
 6611                    window.focus(&editor.focus_handle(cx));
 6612                    editor.edit_breakpoint_at_anchor(
 6613                        position,
 6614                        breakpoint.as_ref().clone(),
 6615                        edit_action,
 6616                        cx,
 6617                    );
 6618                }
 6619            }))
 6620            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6621                editor.set_breakpoint_context_menu(
 6622                    row,
 6623                    Some(position),
 6624                    event.down.position,
 6625                    window,
 6626                    cx,
 6627                );
 6628            }))
 6629    }
 6630
 6631    fn build_tasks_context(
 6632        project: &Entity<Project>,
 6633        buffer: &Entity<Buffer>,
 6634        buffer_row: u32,
 6635        tasks: &Arc<RunnableTasks>,
 6636        cx: &mut Context<Self>,
 6637    ) -> Task<Option<task::TaskContext>> {
 6638        let position = Point::new(buffer_row, tasks.column);
 6639        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 6640        let location = Location {
 6641            buffer: buffer.clone(),
 6642            range: range_start..range_start,
 6643        };
 6644        // Fill in the environmental variables from the tree-sitter captures
 6645        let mut captured_task_variables = TaskVariables::default();
 6646        for (capture_name, value) in tasks.extra_variables.clone() {
 6647            captured_task_variables.insert(
 6648                task::VariableName::Custom(capture_name.into()),
 6649                value.clone(),
 6650            );
 6651        }
 6652        project.update(cx, |project, cx| {
 6653            project.task_store().update(cx, |task_store, cx| {
 6654                task_store.task_context_for_location(captured_task_variables, location, cx)
 6655            })
 6656        })
 6657    }
 6658
 6659    pub fn spawn_nearest_task(
 6660        &mut self,
 6661        action: &SpawnNearestTask,
 6662        window: &mut Window,
 6663        cx: &mut Context<Self>,
 6664    ) {
 6665        let Some((workspace, _)) = self.workspace.clone() else {
 6666            return;
 6667        };
 6668        let Some(project) = self.project.clone() else {
 6669            return;
 6670        };
 6671
 6672        // Try to find a closest, enclosing node using tree-sitter that has a
 6673        // task
 6674        let Some((buffer, buffer_row, tasks)) = self
 6675            .find_enclosing_node_task(cx)
 6676            // Or find the task that's closest in row-distance.
 6677            .or_else(|| self.find_closest_task(cx))
 6678        else {
 6679            return;
 6680        };
 6681
 6682        let reveal_strategy = action.reveal;
 6683        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 6684        cx.spawn_in(window, async move |_, cx| {
 6685            let context = task_context.await?;
 6686            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 6687
 6688            let resolved = resolved_task.resolved.as_mut()?;
 6689            resolved.reveal = reveal_strategy;
 6690
 6691            workspace
 6692                .update(cx, |workspace, cx| {
 6693                    workspace::tasks::schedule_resolved_task(
 6694                        workspace,
 6695                        task_source_kind,
 6696                        resolved_task,
 6697                        false,
 6698                        cx,
 6699                    );
 6700                })
 6701                .ok()
 6702        })
 6703        .detach();
 6704    }
 6705
 6706    fn find_closest_task(
 6707        &mut self,
 6708        cx: &mut Context<Self>,
 6709    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6710        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 6711
 6712        let ((buffer_id, row), tasks) = self
 6713            .tasks
 6714            .iter()
 6715            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 6716
 6717        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 6718        let tasks = Arc::new(tasks.to_owned());
 6719        Some((buffer, *row, tasks))
 6720    }
 6721
 6722    fn find_enclosing_node_task(
 6723        &mut self,
 6724        cx: &mut Context<Self>,
 6725    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6726        let snapshot = self.buffer.read(cx).snapshot(cx);
 6727        let offset = self.selections.newest::<usize>(cx).head();
 6728        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 6729        let buffer_id = excerpt.buffer().remote_id();
 6730
 6731        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 6732        let mut cursor = layer.node().walk();
 6733
 6734        while cursor.goto_first_child_for_byte(offset).is_some() {
 6735            if cursor.node().end_byte() == offset {
 6736                cursor.goto_next_sibling();
 6737            }
 6738        }
 6739
 6740        // Ascend to the smallest ancestor that contains the range and has a task.
 6741        loop {
 6742            let node = cursor.node();
 6743            let node_range = node.byte_range();
 6744            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 6745
 6746            // Check if this node contains our offset
 6747            if node_range.start <= offset && node_range.end >= offset {
 6748                // If it contains offset, check for task
 6749                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 6750                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 6751                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 6752                }
 6753            }
 6754
 6755            if !cursor.goto_parent() {
 6756                break;
 6757            }
 6758        }
 6759        None
 6760    }
 6761
 6762    fn render_run_indicator(
 6763        &self,
 6764        _style: &EditorStyle,
 6765        is_active: bool,
 6766        row: DisplayRow,
 6767        breakpoint: Option<(Anchor, Breakpoint)>,
 6768        cx: &mut Context<Self>,
 6769    ) -> IconButton {
 6770        let color = Color::Muted;
 6771        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6772
 6773        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 6774            .shape(ui::IconButtonShape::Square)
 6775            .icon_size(IconSize::XSmall)
 6776            .icon_color(color)
 6777            .toggle_state(is_active)
 6778            .on_click(cx.listener(move |editor, _e, window, cx| {
 6779                window.focus(&editor.focus_handle(cx));
 6780                editor.toggle_code_actions(
 6781                    &ToggleCodeActions {
 6782                        deployed_from_indicator: Some(row),
 6783                    },
 6784                    window,
 6785                    cx,
 6786                );
 6787            }))
 6788            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6789                editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
 6790            }))
 6791    }
 6792
 6793    pub fn context_menu_visible(&self) -> bool {
 6794        !self.edit_prediction_preview_is_active()
 6795            && self
 6796                .context_menu
 6797                .borrow()
 6798                .as_ref()
 6799                .map_or(false, |menu| menu.visible())
 6800    }
 6801
 6802    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 6803        self.context_menu
 6804            .borrow()
 6805            .as_ref()
 6806            .map(|menu| menu.origin())
 6807    }
 6808
 6809    pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
 6810        self.context_menu_options = Some(options);
 6811    }
 6812
 6813    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 6814    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 6815
 6816    fn render_edit_prediction_popover(
 6817        &mut self,
 6818        text_bounds: &Bounds<Pixels>,
 6819        content_origin: gpui::Point<Pixels>,
 6820        editor_snapshot: &EditorSnapshot,
 6821        visible_row_range: Range<DisplayRow>,
 6822        scroll_top: f32,
 6823        scroll_bottom: f32,
 6824        line_layouts: &[LineWithInvisibles],
 6825        line_height: Pixels,
 6826        scroll_pixel_position: gpui::Point<Pixels>,
 6827        newest_selection_head: Option<DisplayPoint>,
 6828        editor_width: Pixels,
 6829        style: &EditorStyle,
 6830        window: &mut Window,
 6831        cx: &mut App,
 6832    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6833        let active_inline_completion = self.active_inline_completion.as_ref()?;
 6834
 6835        if self.edit_prediction_visible_in_cursor_popover(true) {
 6836            return None;
 6837        }
 6838
 6839        match &active_inline_completion.completion {
 6840            InlineCompletion::Move { target, .. } => {
 6841                let target_display_point = target.to_display_point(editor_snapshot);
 6842
 6843                if self.edit_prediction_requires_modifier() {
 6844                    if !self.edit_prediction_preview_is_active() {
 6845                        return None;
 6846                    }
 6847
 6848                    self.render_edit_prediction_modifier_jump_popover(
 6849                        text_bounds,
 6850                        content_origin,
 6851                        visible_row_range,
 6852                        line_layouts,
 6853                        line_height,
 6854                        scroll_pixel_position,
 6855                        newest_selection_head,
 6856                        target_display_point,
 6857                        window,
 6858                        cx,
 6859                    )
 6860                } else {
 6861                    self.render_edit_prediction_eager_jump_popover(
 6862                        text_bounds,
 6863                        content_origin,
 6864                        editor_snapshot,
 6865                        visible_row_range,
 6866                        scroll_top,
 6867                        scroll_bottom,
 6868                        line_height,
 6869                        scroll_pixel_position,
 6870                        target_display_point,
 6871                        editor_width,
 6872                        window,
 6873                        cx,
 6874                    )
 6875                }
 6876            }
 6877            InlineCompletion::Edit {
 6878                display_mode: EditDisplayMode::Inline,
 6879                ..
 6880            } => None,
 6881            InlineCompletion::Edit {
 6882                display_mode: EditDisplayMode::TabAccept,
 6883                edits,
 6884                ..
 6885            } => {
 6886                let range = &edits.first()?.0;
 6887                let target_display_point = range.end.to_display_point(editor_snapshot);
 6888
 6889                self.render_edit_prediction_end_of_line_popover(
 6890                    "Accept",
 6891                    editor_snapshot,
 6892                    visible_row_range,
 6893                    target_display_point,
 6894                    line_height,
 6895                    scroll_pixel_position,
 6896                    content_origin,
 6897                    editor_width,
 6898                    window,
 6899                    cx,
 6900                )
 6901            }
 6902            InlineCompletion::Edit {
 6903                edits,
 6904                edit_preview,
 6905                display_mode: EditDisplayMode::DiffPopover,
 6906                snapshot,
 6907            } => self.render_edit_prediction_diff_popover(
 6908                text_bounds,
 6909                content_origin,
 6910                editor_snapshot,
 6911                visible_row_range,
 6912                line_layouts,
 6913                line_height,
 6914                scroll_pixel_position,
 6915                newest_selection_head,
 6916                editor_width,
 6917                style,
 6918                edits,
 6919                edit_preview,
 6920                snapshot,
 6921                window,
 6922                cx,
 6923            ),
 6924        }
 6925    }
 6926
 6927    fn render_edit_prediction_modifier_jump_popover(
 6928        &mut self,
 6929        text_bounds: &Bounds<Pixels>,
 6930        content_origin: gpui::Point<Pixels>,
 6931        visible_row_range: Range<DisplayRow>,
 6932        line_layouts: &[LineWithInvisibles],
 6933        line_height: Pixels,
 6934        scroll_pixel_position: gpui::Point<Pixels>,
 6935        newest_selection_head: Option<DisplayPoint>,
 6936        target_display_point: DisplayPoint,
 6937        window: &mut Window,
 6938        cx: &mut App,
 6939    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6940        let scrolled_content_origin =
 6941            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 6942
 6943        const SCROLL_PADDING_Y: Pixels = px(12.);
 6944
 6945        if target_display_point.row() < visible_row_range.start {
 6946            return self.render_edit_prediction_scroll_popover(
 6947                |_| SCROLL_PADDING_Y,
 6948                IconName::ArrowUp,
 6949                visible_row_range,
 6950                line_layouts,
 6951                newest_selection_head,
 6952                scrolled_content_origin,
 6953                window,
 6954                cx,
 6955            );
 6956        } else if target_display_point.row() >= visible_row_range.end {
 6957            return self.render_edit_prediction_scroll_popover(
 6958                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 6959                IconName::ArrowDown,
 6960                visible_row_range,
 6961                line_layouts,
 6962                newest_selection_head,
 6963                scrolled_content_origin,
 6964                window,
 6965                cx,
 6966            );
 6967        }
 6968
 6969        const POLE_WIDTH: Pixels = px(2.);
 6970
 6971        let line_layout =
 6972            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 6973        let target_column = target_display_point.column() as usize;
 6974
 6975        let target_x = line_layout.x_for_index(target_column);
 6976        let target_y =
 6977            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 6978
 6979        let flag_on_right = target_x < text_bounds.size.width / 2.;
 6980
 6981        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 6982        border_color.l += 0.001;
 6983
 6984        let mut element = v_flex()
 6985            .items_end()
 6986            .when(flag_on_right, |el| el.items_start())
 6987            .child(if flag_on_right {
 6988                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6989                    .rounded_bl(px(0.))
 6990                    .rounded_tl(px(0.))
 6991                    .border_l_2()
 6992                    .border_color(border_color)
 6993            } else {
 6994                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6995                    .rounded_br(px(0.))
 6996                    .rounded_tr(px(0.))
 6997                    .border_r_2()
 6998                    .border_color(border_color)
 6999            })
 7000            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 7001            .into_any();
 7002
 7003        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7004
 7005        let mut origin = scrolled_content_origin + point(target_x, target_y)
 7006            - point(
 7007                if flag_on_right {
 7008                    POLE_WIDTH
 7009                } else {
 7010                    size.width - POLE_WIDTH
 7011                },
 7012                size.height - line_height,
 7013            );
 7014
 7015        origin.x = origin.x.max(content_origin.x);
 7016
 7017        element.prepaint_at(origin, window, cx);
 7018
 7019        Some((element, origin))
 7020    }
 7021
 7022    fn render_edit_prediction_scroll_popover(
 7023        &mut self,
 7024        to_y: impl Fn(Size<Pixels>) -> Pixels,
 7025        scroll_icon: IconName,
 7026        visible_row_range: Range<DisplayRow>,
 7027        line_layouts: &[LineWithInvisibles],
 7028        newest_selection_head: Option<DisplayPoint>,
 7029        scrolled_content_origin: gpui::Point<Pixels>,
 7030        window: &mut Window,
 7031        cx: &mut App,
 7032    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7033        let mut element = self
 7034            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 7035            .into_any();
 7036
 7037        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7038
 7039        let cursor = newest_selection_head?;
 7040        let cursor_row_layout =
 7041            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 7042        let cursor_column = cursor.column() as usize;
 7043
 7044        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 7045
 7046        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 7047
 7048        element.prepaint_at(origin, window, cx);
 7049        Some((element, origin))
 7050    }
 7051
 7052    fn render_edit_prediction_eager_jump_popover(
 7053        &mut self,
 7054        text_bounds: &Bounds<Pixels>,
 7055        content_origin: gpui::Point<Pixels>,
 7056        editor_snapshot: &EditorSnapshot,
 7057        visible_row_range: Range<DisplayRow>,
 7058        scroll_top: f32,
 7059        scroll_bottom: f32,
 7060        line_height: Pixels,
 7061        scroll_pixel_position: gpui::Point<Pixels>,
 7062        target_display_point: DisplayPoint,
 7063        editor_width: Pixels,
 7064        window: &mut Window,
 7065        cx: &mut App,
 7066    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7067        if target_display_point.row().as_f32() < scroll_top {
 7068            let mut element = self
 7069                .render_edit_prediction_line_popover(
 7070                    "Jump to Edit",
 7071                    Some(IconName::ArrowUp),
 7072                    window,
 7073                    cx,
 7074                )?
 7075                .into_any();
 7076
 7077            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7078            let offset = point(
 7079                (text_bounds.size.width - size.width) / 2.,
 7080                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7081            );
 7082
 7083            let origin = text_bounds.origin + offset;
 7084            element.prepaint_at(origin, window, cx);
 7085            Some((element, origin))
 7086        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 7087            let mut element = self
 7088                .render_edit_prediction_line_popover(
 7089                    "Jump to Edit",
 7090                    Some(IconName::ArrowDown),
 7091                    window,
 7092                    cx,
 7093                )?
 7094                .into_any();
 7095
 7096            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7097            let offset = point(
 7098                (text_bounds.size.width - size.width) / 2.,
 7099                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7100            );
 7101
 7102            let origin = text_bounds.origin + offset;
 7103            element.prepaint_at(origin, window, cx);
 7104            Some((element, origin))
 7105        } else {
 7106            self.render_edit_prediction_end_of_line_popover(
 7107                "Jump to Edit",
 7108                editor_snapshot,
 7109                visible_row_range,
 7110                target_display_point,
 7111                line_height,
 7112                scroll_pixel_position,
 7113                content_origin,
 7114                editor_width,
 7115                window,
 7116                cx,
 7117            )
 7118        }
 7119    }
 7120
 7121    fn render_edit_prediction_end_of_line_popover(
 7122        self: &mut Editor,
 7123        label: &'static str,
 7124        editor_snapshot: &EditorSnapshot,
 7125        visible_row_range: Range<DisplayRow>,
 7126        target_display_point: DisplayPoint,
 7127        line_height: Pixels,
 7128        scroll_pixel_position: gpui::Point<Pixels>,
 7129        content_origin: gpui::Point<Pixels>,
 7130        editor_width: Pixels,
 7131        window: &mut Window,
 7132        cx: &mut App,
 7133    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7134        let target_line_end = DisplayPoint::new(
 7135            target_display_point.row(),
 7136            editor_snapshot.line_len(target_display_point.row()),
 7137        );
 7138
 7139        let mut element = self
 7140            .render_edit_prediction_line_popover(label, None, window, cx)?
 7141            .into_any();
 7142
 7143        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7144
 7145        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 7146
 7147        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 7148        let mut origin = start_point
 7149            + line_origin
 7150            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 7151        origin.x = origin.x.max(content_origin.x);
 7152
 7153        let max_x = content_origin.x + editor_width - size.width;
 7154
 7155        if origin.x > max_x {
 7156            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 7157
 7158            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 7159                origin.y += offset;
 7160                IconName::ArrowUp
 7161            } else {
 7162                origin.y -= offset;
 7163                IconName::ArrowDown
 7164            };
 7165
 7166            element = self
 7167                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 7168                .into_any();
 7169
 7170            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7171
 7172            origin.x = content_origin.x + editor_width - size.width - px(2.);
 7173        }
 7174
 7175        element.prepaint_at(origin, window, cx);
 7176        Some((element, origin))
 7177    }
 7178
 7179    fn render_edit_prediction_diff_popover(
 7180        self: &Editor,
 7181        text_bounds: &Bounds<Pixels>,
 7182        content_origin: gpui::Point<Pixels>,
 7183        editor_snapshot: &EditorSnapshot,
 7184        visible_row_range: Range<DisplayRow>,
 7185        line_layouts: &[LineWithInvisibles],
 7186        line_height: Pixels,
 7187        scroll_pixel_position: gpui::Point<Pixels>,
 7188        newest_selection_head: Option<DisplayPoint>,
 7189        editor_width: Pixels,
 7190        style: &EditorStyle,
 7191        edits: &Vec<(Range<Anchor>, String)>,
 7192        edit_preview: &Option<language::EditPreview>,
 7193        snapshot: &language::BufferSnapshot,
 7194        window: &mut Window,
 7195        cx: &mut App,
 7196    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7197        let edit_start = edits
 7198            .first()
 7199            .unwrap()
 7200            .0
 7201            .start
 7202            .to_display_point(editor_snapshot);
 7203        let edit_end = edits
 7204            .last()
 7205            .unwrap()
 7206            .0
 7207            .end
 7208            .to_display_point(editor_snapshot);
 7209
 7210        let is_visible = visible_row_range.contains(&edit_start.row())
 7211            || visible_row_range.contains(&edit_end.row());
 7212        if !is_visible {
 7213            return None;
 7214        }
 7215
 7216        let highlighted_edits =
 7217            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 7218
 7219        let styled_text = highlighted_edits.to_styled_text(&style.text);
 7220        let line_count = highlighted_edits.text.lines().count();
 7221
 7222        const BORDER_WIDTH: Pixels = px(1.);
 7223
 7224        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7225        let has_keybind = keybind.is_some();
 7226
 7227        let mut element = h_flex()
 7228            .items_start()
 7229            .child(
 7230                h_flex()
 7231                    .bg(cx.theme().colors().editor_background)
 7232                    .border(BORDER_WIDTH)
 7233                    .shadow_sm()
 7234                    .border_color(cx.theme().colors().border)
 7235                    .rounded_l_lg()
 7236                    .when(line_count > 1, |el| el.rounded_br_lg())
 7237                    .pr_1()
 7238                    .child(styled_text),
 7239            )
 7240            .child(
 7241                h_flex()
 7242                    .h(line_height + BORDER_WIDTH * 2.)
 7243                    .px_1p5()
 7244                    .gap_1()
 7245                    // Workaround: For some reason, there's a gap if we don't do this
 7246                    .ml(-BORDER_WIDTH)
 7247                    .shadow(smallvec![gpui::BoxShadow {
 7248                        color: gpui::black().opacity(0.05),
 7249                        offset: point(px(1.), px(1.)),
 7250                        blur_radius: px(2.),
 7251                        spread_radius: px(0.),
 7252                    }])
 7253                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 7254                    .border(BORDER_WIDTH)
 7255                    .border_color(cx.theme().colors().border)
 7256                    .rounded_r_lg()
 7257                    .id("edit_prediction_diff_popover_keybind")
 7258                    .when(!has_keybind, |el| {
 7259                        let status_colors = cx.theme().status();
 7260
 7261                        el.bg(status_colors.error_background)
 7262                            .border_color(status_colors.error.opacity(0.6))
 7263                            .child(Icon::new(IconName::Info).color(Color::Error))
 7264                            .cursor_default()
 7265                            .hoverable_tooltip(move |_window, cx| {
 7266                                cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7267                            })
 7268                    })
 7269                    .children(keybind),
 7270            )
 7271            .into_any();
 7272
 7273        let longest_row =
 7274            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 7275        let longest_line_width = if visible_row_range.contains(&longest_row) {
 7276            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 7277        } else {
 7278            layout_line(
 7279                longest_row,
 7280                editor_snapshot,
 7281                style,
 7282                editor_width,
 7283                |_| false,
 7284                window,
 7285                cx,
 7286            )
 7287            .width
 7288        };
 7289
 7290        let viewport_bounds =
 7291            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 7292                right: -EditorElement::SCROLLBAR_WIDTH,
 7293                ..Default::default()
 7294            });
 7295
 7296        let x_after_longest =
 7297            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 7298                - scroll_pixel_position.x;
 7299
 7300        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7301
 7302        // Fully visible if it can be displayed within the window (allow overlapping other
 7303        // panes). However, this is only allowed if the popover starts within text_bounds.
 7304        let can_position_to_the_right = x_after_longest < text_bounds.right()
 7305            && x_after_longest + element_bounds.width < viewport_bounds.right();
 7306
 7307        let mut origin = if can_position_to_the_right {
 7308            point(
 7309                x_after_longest,
 7310                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 7311                    - scroll_pixel_position.y,
 7312            )
 7313        } else {
 7314            let cursor_row = newest_selection_head.map(|head| head.row());
 7315            let above_edit = edit_start
 7316                .row()
 7317                .0
 7318                .checked_sub(line_count as u32)
 7319                .map(DisplayRow);
 7320            let below_edit = Some(edit_end.row() + 1);
 7321            let above_cursor =
 7322                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 7323            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 7324
 7325            // Place the edit popover adjacent to the edit if there is a location
 7326            // available that is onscreen and does not obscure the cursor. Otherwise,
 7327            // place it adjacent to the cursor.
 7328            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 7329                .into_iter()
 7330                .flatten()
 7331                .find(|&start_row| {
 7332                    let end_row = start_row + line_count as u32;
 7333                    visible_row_range.contains(&start_row)
 7334                        && visible_row_range.contains(&end_row)
 7335                        && cursor_row.map_or(true, |cursor_row| {
 7336                            !((start_row..end_row).contains(&cursor_row))
 7337                        })
 7338                })?;
 7339
 7340            content_origin
 7341                + point(
 7342                    -scroll_pixel_position.x,
 7343                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 7344                )
 7345        };
 7346
 7347        origin.x -= BORDER_WIDTH;
 7348
 7349        window.defer_draw(element, origin, 1);
 7350
 7351        // Do not return an element, since it will already be drawn due to defer_draw.
 7352        None
 7353    }
 7354
 7355    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 7356        px(30.)
 7357    }
 7358
 7359    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 7360        if self.read_only(cx) {
 7361            cx.theme().players().read_only()
 7362        } else {
 7363            self.style.as_ref().unwrap().local_player
 7364        }
 7365    }
 7366
 7367    fn render_edit_prediction_accept_keybind(
 7368        &self,
 7369        window: &mut Window,
 7370        cx: &App,
 7371    ) -> Option<AnyElement> {
 7372        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 7373        let accept_keystroke = accept_binding.keystroke()?;
 7374
 7375        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7376
 7377        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 7378            Color::Accent
 7379        } else {
 7380            Color::Muted
 7381        };
 7382
 7383        h_flex()
 7384            .px_0p5()
 7385            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 7386            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7387            .text_size(TextSize::XSmall.rems(cx))
 7388            .child(h_flex().children(ui::render_modifiers(
 7389                &accept_keystroke.modifiers,
 7390                PlatformStyle::platform(),
 7391                Some(modifiers_color),
 7392                Some(IconSize::XSmall.rems().into()),
 7393                true,
 7394            )))
 7395            .when(is_platform_style_mac, |parent| {
 7396                parent.child(accept_keystroke.key.clone())
 7397            })
 7398            .when(!is_platform_style_mac, |parent| {
 7399                parent.child(
 7400                    Key::new(
 7401                        util::capitalize(&accept_keystroke.key),
 7402                        Some(Color::Default),
 7403                    )
 7404                    .size(Some(IconSize::XSmall.rems().into())),
 7405                )
 7406            })
 7407            .into_any()
 7408            .into()
 7409    }
 7410
 7411    fn render_edit_prediction_line_popover(
 7412        &self,
 7413        label: impl Into<SharedString>,
 7414        icon: Option<IconName>,
 7415        window: &mut Window,
 7416        cx: &App,
 7417    ) -> Option<Stateful<Div>> {
 7418        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 7419
 7420        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7421        let has_keybind = keybind.is_some();
 7422
 7423        let result = h_flex()
 7424            .id("ep-line-popover")
 7425            .py_0p5()
 7426            .pl_1()
 7427            .pr(padding_right)
 7428            .gap_1()
 7429            .rounded_md()
 7430            .border_1()
 7431            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7432            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 7433            .shadow_sm()
 7434            .when(!has_keybind, |el| {
 7435                let status_colors = cx.theme().status();
 7436
 7437                el.bg(status_colors.error_background)
 7438                    .border_color(status_colors.error.opacity(0.6))
 7439                    .pl_2()
 7440                    .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
 7441                    .cursor_default()
 7442                    .hoverable_tooltip(move |_window, cx| {
 7443                        cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7444                    })
 7445            })
 7446            .children(keybind)
 7447            .child(
 7448                Label::new(label)
 7449                    .size(LabelSize::Small)
 7450                    .when(!has_keybind, |el| {
 7451                        el.color(cx.theme().status().error.into()).strikethrough()
 7452                    }),
 7453            )
 7454            .when(!has_keybind, |el| {
 7455                el.child(
 7456                    h_flex().ml_1().child(
 7457                        Icon::new(IconName::Info)
 7458                            .size(IconSize::Small)
 7459                            .color(cx.theme().status().error.into()),
 7460                    ),
 7461                )
 7462            })
 7463            .when_some(icon, |element, icon| {
 7464                element.child(
 7465                    div()
 7466                        .mt(px(1.5))
 7467                        .child(Icon::new(icon).size(IconSize::Small)),
 7468                )
 7469            });
 7470
 7471        Some(result)
 7472    }
 7473
 7474    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 7475        let accent_color = cx.theme().colors().text_accent;
 7476        let editor_bg_color = cx.theme().colors().editor_background;
 7477        editor_bg_color.blend(accent_color.opacity(0.1))
 7478    }
 7479
 7480    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 7481        let accent_color = cx.theme().colors().text_accent;
 7482        let editor_bg_color = cx.theme().colors().editor_background;
 7483        editor_bg_color.blend(accent_color.opacity(0.6))
 7484    }
 7485
 7486    fn render_edit_prediction_cursor_popover(
 7487        &self,
 7488        min_width: Pixels,
 7489        max_width: Pixels,
 7490        cursor_point: Point,
 7491        style: &EditorStyle,
 7492        accept_keystroke: Option<&gpui::Keystroke>,
 7493        _window: &Window,
 7494        cx: &mut Context<Editor>,
 7495    ) -> Option<AnyElement> {
 7496        let provider = self.edit_prediction_provider.as_ref()?;
 7497
 7498        if provider.provider.needs_terms_acceptance(cx) {
 7499            return Some(
 7500                h_flex()
 7501                    .min_w(min_width)
 7502                    .flex_1()
 7503                    .px_2()
 7504                    .py_1()
 7505                    .gap_3()
 7506                    .elevation_2(cx)
 7507                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 7508                    .id("accept-terms")
 7509                    .cursor_pointer()
 7510                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 7511                    .on_click(cx.listener(|this, _event, window, cx| {
 7512                        cx.stop_propagation();
 7513                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 7514                        window.dispatch_action(
 7515                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 7516                            cx,
 7517                        );
 7518                    }))
 7519                    .child(
 7520                        h_flex()
 7521                            .flex_1()
 7522                            .gap_2()
 7523                            .child(Icon::new(IconName::ZedPredict))
 7524                            .child(Label::new("Accept Terms of Service"))
 7525                            .child(div().w_full())
 7526                            .child(
 7527                                Icon::new(IconName::ArrowUpRight)
 7528                                    .color(Color::Muted)
 7529                                    .size(IconSize::Small),
 7530                            )
 7531                            .into_any_element(),
 7532                    )
 7533                    .into_any(),
 7534            );
 7535        }
 7536
 7537        let is_refreshing = provider.provider.is_refreshing(cx);
 7538
 7539        fn pending_completion_container() -> Div {
 7540            h_flex()
 7541                .h_full()
 7542                .flex_1()
 7543                .gap_2()
 7544                .child(Icon::new(IconName::ZedPredict))
 7545        }
 7546
 7547        let completion = match &self.active_inline_completion {
 7548            Some(prediction) => {
 7549                if !self.has_visible_completions_menu() {
 7550                    const RADIUS: Pixels = px(6.);
 7551                    const BORDER_WIDTH: Pixels = px(1.);
 7552
 7553                    return Some(
 7554                        h_flex()
 7555                            .elevation_2(cx)
 7556                            .border(BORDER_WIDTH)
 7557                            .border_color(cx.theme().colors().border)
 7558                            .when(accept_keystroke.is_none(), |el| {
 7559                                el.border_color(cx.theme().status().error)
 7560                            })
 7561                            .rounded(RADIUS)
 7562                            .rounded_tl(px(0.))
 7563                            .overflow_hidden()
 7564                            .child(div().px_1p5().child(match &prediction.completion {
 7565                                InlineCompletion::Move { target, snapshot } => {
 7566                                    use text::ToPoint as _;
 7567                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 7568                                    {
 7569                                        Icon::new(IconName::ZedPredictDown)
 7570                                    } else {
 7571                                        Icon::new(IconName::ZedPredictUp)
 7572                                    }
 7573                                }
 7574                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 7575                            }))
 7576                            .child(
 7577                                h_flex()
 7578                                    .gap_1()
 7579                                    .py_1()
 7580                                    .px_2()
 7581                                    .rounded_r(RADIUS - BORDER_WIDTH)
 7582                                    .border_l_1()
 7583                                    .border_color(cx.theme().colors().border)
 7584                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7585                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 7586                                        el.child(
 7587                                            Label::new("Hold")
 7588                                                .size(LabelSize::Small)
 7589                                                .when(accept_keystroke.is_none(), |el| {
 7590                                                    el.strikethrough()
 7591                                                })
 7592                                                .line_height_style(LineHeightStyle::UiLabel),
 7593                                        )
 7594                                    })
 7595                                    .id("edit_prediction_cursor_popover_keybind")
 7596                                    .when(accept_keystroke.is_none(), |el| {
 7597                                        let status_colors = cx.theme().status();
 7598
 7599                                        el.bg(status_colors.error_background)
 7600                                            .border_color(status_colors.error.opacity(0.6))
 7601                                            .child(Icon::new(IconName::Info).color(Color::Error))
 7602                                            .cursor_default()
 7603                                            .hoverable_tooltip(move |_window, cx| {
 7604                                                cx.new(|_| MissingEditPredictionKeybindingTooltip)
 7605                                                    .into()
 7606                                            })
 7607                                    })
 7608                                    .when_some(
 7609                                        accept_keystroke.as_ref(),
 7610                                        |el, accept_keystroke| {
 7611                                            el.child(h_flex().children(ui::render_modifiers(
 7612                                                &accept_keystroke.modifiers,
 7613                                                PlatformStyle::platform(),
 7614                                                Some(Color::Default),
 7615                                                Some(IconSize::XSmall.rems().into()),
 7616                                                false,
 7617                                            )))
 7618                                        },
 7619                                    ),
 7620                            )
 7621                            .into_any(),
 7622                    );
 7623                }
 7624
 7625                self.render_edit_prediction_cursor_popover_preview(
 7626                    prediction,
 7627                    cursor_point,
 7628                    style,
 7629                    cx,
 7630                )?
 7631            }
 7632
 7633            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 7634                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 7635                    stale_completion,
 7636                    cursor_point,
 7637                    style,
 7638                    cx,
 7639                )?,
 7640
 7641                None => {
 7642                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 7643                }
 7644            },
 7645
 7646            None => pending_completion_container().child(Label::new("No Prediction")),
 7647        };
 7648
 7649        let completion = if is_refreshing {
 7650            completion
 7651                .with_animation(
 7652                    "loading-completion",
 7653                    Animation::new(Duration::from_secs(2))
 7654                        .repeat()
 7655                        .with_easing(pulsating_between(0.4, 0.8)),
 7656                    |label, delta| label.opacity(delta),
 7657                )
 7658                .into_any_element()
 7659        } else {
 7660            completion.into_any_element()
 7661        };
 7662
 7663        let has_completion = self.active_inline_completion.is_some();
 7664
 7665        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7666        Some(
 7667            h_flex()
 7668                .min_w(min_width)
 7669                .max_w(max_width)
 7670                .flex_1()
 7671                .elevation_2(cx)
 7672                .border_color(cx.theme().colors().border)
 7673                .child(
 7674                    div()
 7675                        .flex_1()
 7676                        .py_1()
 7677                        .px_2()
 7678                        .overflow_hidden()
 7679                        .child(completion),
 7680                )
 7681                .when_some(accept_keystroke, |el, accept_keystroke| {
 7682                    if !accept_keystroke.modifiers.modified() {
 7683                        return el;
 7684                    }
 7685
 7686                    el.child(
 7687                        h_flex()
 7688                            .h_full()
 7689                            .border_l_1()
 7690                            .rounded_r_lg()
 7691                            .border_color(cx.theme().colors().border)
 7692                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7693                            .gap_1()
 7694                            .py_1()
 7695                            .px_2()
 7696                            .child(
 7697                                h_flex()
 7698                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7699                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 7700                                    .child(h_flex().children(ui::render_modifiers(
 7701                                        &accept_keystroke.modifiers,
 7702                                        PlatformStyle::platform(),
 7703                                        Some(if !has_completion {
 7704                                            Color::Muted
 7705                                        } else {
 7706                                            Color::Default
 7707                                        }),
 7708                                        None,
 7709                                        false,
 7710                                    ))),
 7711                            )
 7712                            .child(Label::new("Preview").into_any_element())
 7713                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 7714                    )
 7715                })
 7716                .into_any(),
 7717        )
 7718    }
 7719
 7720    fn render_edit_prediction_cursor_popover_preview(
 7721        &self,
 7722        completion: &InlineCompletionState,
 7723        cursor_point: Point,
 7724        style: &EditorStyle,
 7725        cx: &mut Context<Editor>,
 7726    ) -> Option<Div> {
 7727        use text::ToPoint as _;
 7728
 7729        fn render_relative_row_jump(
 7730            prefix: impl Into<String>,
 7731            current_row: u32,
 7732            target_row: u32,
 7733        ) -> Div {
 7734            let (row_diff, arrow) = if target_row < current_row {
 7735                (current_row - target_row, IconName::ArrowUp)
 7736            } else {
 7737                (target_row - current_row, IconName::ArrowDown)
 7738            };
 7739
 7740            h_flex()
 7741                .child(
 7742                    Label::new(format!("{}{}", prefix.into(), row_diff))
 7743                        .color(Color::Muted)
 7744                        .size(LabelSize::Small),
 7745                )
 7746                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 7747        }
 7748
 7749        match &completion.completion {
 7750            InlineCompletion::Move {
 7751                target, snapshot, ..
 7752            } => Some(
 7753                h_flex()
 7754                    .px_2()
 7755                    .gap_2()
 7756                    .flex_1()
 7757                    .child(
 7758                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 7759                            Icon::new(IconName::ZedPredictDown)
 7760                        } else {
 7761                            Icon::new(IconName::ZedPredictUp)
 7762                        },
 7763                    )
 7764                    .child(Label::new("Jump to Edit")),
 7765            ),
 7766
 7767            InlineCompletion::Edit {
 7768                edits,
 7769                edit_preview,
 7770                snapshot,
 7771                display_mode: _,
 7772            } => {
 7773                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 7774
 7775                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 7776                    &snapshot,
 7777                    &edits,
 7778                    edit_preview.as_ref()?,
 7779                    true,
 7780                    cx,
 7781                )
 7782                .first_line_preview();
 7783
 7784                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 7785                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 7786
 7787                let preview = h_flex()
 7788                    .gap_1()
 7789                    .min_w_16()
 7790                    .child(styled_text)
 7791                    .when(has_more_lines, |parent| parent.child(""));
 7792
 7793                let left = if first_edit_row != cursor_point.row {
 7794                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 7795                        .into_any_element()
 7796                } else {
 7797                    Icon::new(IconName::ZedPredict).into_any_element()
 7798                };
 7799
 7800                Some(
 7801                    h_flex()
 7802                        .h_full()
 7803                        .flex_1()
 7804                        .gap_2()
 7805                        .pr_1()
 7806                        .overflow_x_hidden()
 7807                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7808                        .child(left)
 7809                        .child(preview),
 7810                )
 7811            }
 7812        }
 7813    }
 7814
 7815    fn render_context_menu(
 7816        &self,
 7817        style: &EditorStyle,
 7818        max_height_in_lines: u32,
 7819        window: &mut Window,
 7820        cx: &mut Context<Editor>,
 7821    ) -> Option<AnyElement> {
 7822        let menu = self.context_menu.borrow();
 7823        let menu = menu.as_ref()?;
 7824        if !menu.visible() {
 7825            return None;
 7826        };
 7827        Some(menu.render(style, max_height_in_lines, window, cx))
 7828    }
 7829
 7830    fn render_context_menu_aside(
 7831        &mut self,
 7832        max_size: Size<Pixels>,
 7833        window: &mut Window,
 7834        cx: &mut Context<Editor>,
 7835    ) -> Option<AnyElement> {
 7836        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 7837            if menu.visible() {
 7838                menu.render_aside(self, max_size, window, cx)
 7839            } else {
 7840                None
 7841            }
 7842        })
 7843    }
 7844
 7845    fn hide_context_menu(
 7846        &mut self,
 7847        window: &mut Window,
 7848        cx: &mut Context<Self>,
 7849    ) -> Option<CodeContextMenu> {
 7850        cx.notify();
 7851        self.completion_tasks.clear();
 7852        let context_menu = self.context_menu.borrow_mut().take();
 7853        self.stale_inline_completion_in_menu.take();
 7854        self.update_visible_inline_completion(window, cx);
 7855        context_menu
 7856    }
 7857
 7858    fn show_snippet_choices(
 7859        &mut self,
 7860        choices: &Vec<String>,
 7861        selection: Range<Anchor>,
 7862        cx: &mut Context<Self>,
 7863    ) {
 7864        if selection.start.buffer_id.is_none() {
 7865            return;
 7866        }
 7867        let buffer_id = selection.start.buffer_id.unwrap();
 7868        let buffer = self.buffer().read(cx).buffer(buffer_id);
 7869        let id = post_inc(&mut self.next_completion_id);
 7870
 7871        if let Some(buffer) = buffer {
 7872            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 7873                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 7874            ));
 7875        }
 7876    }
 7877
 7878    pub fn insert_snippet(
 7879        &mut self,
 7880        insertion_ranges: &[Range<usize>],
 7881        snippet: Snippet,
 7882        window: &mut Window,
 7883        cx: &mut Context<Self>,
 7884    ) -> Result<()> {
 7885        struct Tabstop<T> {
 7886            is_end_tabstop: bool,
 7887            ranges: Vec<Range<T>>,
 7888            choices: Option<Vec<String>>,
 7889        }
 7890
 7891        let tabstops = self.buffer.update(cx, |buffer, cx| {
 7892            let snippet_text: Arc<str> = snippet.text.clone().into();
 7893            let edits = insertion_ranges
 7894                .iter()
 7895                .cloned()
 7896                .map(|range| (range, snippet_text.clone()));
 7897            buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
 7898
 7899            let snapshot = &*buffer.read(cx);
 7900            let snippet = &snippet;
 7901            snippet
 7902                .tabstops
 7903                .iter()
 7904                .map(|tabstop| {
 7905                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 7906                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 7907                    });
 7908                    let mut tabstop_ranges = tabstop
 7909                        .ranges
 7910                        .iter()
 7911                        .flat_map(|tabstop_range| {
 7912                            let mut delta = 0_isize;
 7913                            insertion_ranges.iter().map(move |insertion_range| {
 7914                                let insertion_start = insertion_range.start as isize + delta;
 7915                                delta +=
 7916                                    snippet.text.len() as isize - insertion_range.len() as isize;
 7917
 7918                                let start = ((insertion_start + tabstop_range.start) as usize)
 7919                                    .min(snapshot.len());
 7920                                let end = ((insertion_start + tabstop_range.end) as usize)
 7921                                    .min(snapshot.len());
 7922                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 7923                            })
 7924                        })
 7925                        .collect::<Vec<_>>();
 7926                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 7927
 7928                    Tabstop {
 7929                        is_end_tabstop,
 7930                        ranges: tabstop_ranges,
 7931                        choices: tabstop.choices.clone(),
 7932                    }
 7933                })
 7934                .collect::<Vec<_>>()
 7935        });
 7936        if let Some(tabstop) = tabstops.first() {
 7937            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7938                s.select_ranges(tabstop.ranges.iter().cloned());
 7939            });
 7940
 7941            if let Some(choices) = &tabstop.choices {
 7942                if let Some(selection) = tabstop.ranges.first() {
 7943                    self.show_snippet_choices(choices, selection.clone(), cx)
 7944                }
 7945            }
 7946
 7947            // If we're already at the last tabstop and it's at the end of the snippet,
 7948            // we're done, we don't need to keep the state around.
 7949            if !tabstop.is_end_tabstop {
 7950                let choices = tabstops
 7951                    .iter()
 7952                    .map(|tabstop| tabstop.choices.clone())
 7953                    .collect();
 7954
 7955                let ranges = tabstops
 7956                    .into_iter()
 7957                    .map(|tabstop| tabstop.ranges)
 7958                    .collect::<Vec<_>>();
 7959
 7960                self.snippet_stack.push(SnippetState {
 7961                    active_index: 0,
 7962                    ranges,
 7963                    choices,
 7964                });
 7965            }
 7966
 7967            // Check whether the just-entered snippet ends with an auto-closable bracket.
 7968            if self.autoclose_regions.is_empty() {
 7969                let snapshot = self.buffer.read(cx).snapshot(cx);
 7970                for selection in &mut self.selections.all::<Point>(cx) {
 7971                    let selection_head = selection.head();
 7972                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 7973                        continue;
 7974                    };
 7975
 7976                    let mut bracket_pair = None;
 7977                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 7978                    let prev_chars = snapshot
 7979                        .reversed_chars_at(selection_head)
 7980                        .collect::<String>();
 7981                    for (pair, enabled) in scope.brackets() {
 7982                        if enabled
 7983                            && pair.close
 7984                            && prev_chars.starts_with(pair.start.as_str())
 7985                            && next_chars.starts_with(pair.end.as_str())
 7986                        {
 7987                            bracket_pair = Some(pair.clone());
 7988                            break;
 7989                        }
 7990                    }
 7991                    if let Some(pair) = bracket_pair {
 7992                        let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
 7993                        let autoclose_enabled =
 7994                            self.use_autoclose && snapshot_settings.use_autoclose;
 7995                        if autoclose_enabled {
 7996                            let start = snapshot.anchor_after(selection_head);
 7997                            let end = snapshot.anchor_after(selection_head);
 7998                            self.autoclose_regions.push(AutocloseRegion {
 7999                                selection_id: selection.id,
 8000                                range: start..end,
 8001                                pair,
 8002                            });
 8003                        }
 8004                    }
 8005                }
 8006            }
 8007        }
 8008        Ok(())
 8009    }
 8010
 8011    pub fn move_to_next_snippet_tabstop(
 8012        &mut self,
 8013        window: &mut Window,
 8014        cx: &mut Context<Self>,
 8015    ) -> bool {
 8016        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 8017    }
 8018
 8019    pub fn move_to_prev_snippet_tabstop(
 8020        &mut self,
 8021        window: &mut Window,
 8022        cx: &mut Context<Self>,
 8023    ) -> bool {
 8024        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 8025    }
 8026
 8027    pub fn move_to_snippet_tabstop(
 8028        &mut self,
 8029        bias: Bias,
 8030        window: &mut Window,
 8031        cx: &mut Context<Self>,
 8032    ) -> bool {
 8033        if let Some(mut snippet) = self.snippet_stack.pop() {
 8034            match bias {
 8035                Bias::Left => {
 8036                    if snippet.active_index > 0 {
 8037                        snippet.active_index -= 1;
 8038                    } else {
 8039                        self.snippet_stack.push(snippet);
 8040                        return false;
 8041                    }
 8042                }
 8043                Bias::Right => {
 8044                    if snippet.active_index + 1 < snippet.ranges.len() {
 8045                        snippet.active_index += 1;
 8046                    } else {
 8047                        self.snippet_stack.push(snippet);
 8048                        return false;
 8049                    }
 8050                }
 8051            }
 8052            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 8053                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8054                    s.select_anchor_ranges(current_ranges.iter().cloned())
 8055                });
 8056
 8057                if let Some(choices) = &snippet.choices[snippet.active_index] {
 8058                    if let Some(selection) = current_ranges.first() {
 8059                        self.show_snippet_choices(&choices, selection.clone(), cx);
 8060                    }
 8061                }
 8062
 8063                // If snippet state is not at the last tabstop, push it back on the stack
 8064                if snippet.active_index + 1 < snippet.ranges.len() {
 8065                    self.snippet_stack.push(snippet);
 8066                }
 8067                return true;
 8068            }
 8069        }
 8070
 8071        false
 8072    }
 8073
 8074    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 8075        self.transact(window, cx, |this, window, cx| {
 8076            this.select_all(&SelectAll, window, cx);
 8077            this.insert("", window, cx);
 8078        });
 8079    }
 8080
 8081    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 8082        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8083        self.transact(window, cx, |this, window, cx| {
 8084            this.select_autoclose_pair(window, cx);
 8085            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 8086            if !this.linked_edit_ranges.is_empty() {
 8087                let selections = this.selections.all::<MultiBufferPoint>(cx);
 8088                let snapshot = this.buffer.read(cx).snapshot(cx);
 8089
 8090                for selection in selections.iter() {
 8091                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 8092                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 8093                    if selection_start.buffer_id != selection_end.buffer_id {
 8094                        continue;
 8095                    }
 8096                    if let Some(ranges) =
 8097                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 8098                    {
 8099                        for (buffer, entries) in ranges {
 8100                            linked_ranges.entry(buffer).or_default().extend(entries);
 8101                        }
 8102                    }
 8103                }
 8104            }
 8105
 8106            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8107            let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 8108            for selection in &mut selections {
 8109                if selection.is_empty() {
 8110                    let old_head = selection.head();
 8111                    let mut new_head =
 8112                        movement::left(&display_map, old_head.to_display_point(&display_map))
 8113                            .to_point(&display_map);
 8114                    if let Some((buffer, line_buffer_range)) = display_map
 8115                        .buffer_snapshot
 8116                        .buffer_line_for_row(MultiBufferRow(old_head.row))
 8117                    {
 8118                        let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
 8119                        let indent_len = match indent_size.kind {
 8120                            IndentKind::Space => {
 8121                                buffer.settings_at(line_buffer_range.start, cx).tab_size
 8122                            }
 8123                            IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 8124                        };
 8125                        if old_head.column <= indent_size.len && old_head.column > 0 {
 8126                            let indent_len = indent_len.get();
 8127                            new_head = cmp::min(
 8128                                new_head,
 8129                                MultiBufferPoint::new(
 8130                                    old_head.row,
 8131                                    ((old_head.column - 1) / indent_len) * indent_len,
 8132                                ),
 8133                            );
 8134                        }
 8135                    }
 8136
 8137                    selection.set_head(new_head, SelectionGoal::None);
 8138                }
 8139            }
 8140
 8141            this.signature_help_state.set_backspace_pressed(true);
 8142            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8143                s.select(selections)
 8144            });
 8145            this.insert("", window, cx);
 8146            let empty_str: Arc<str> = Arc::from("");
 8147            for (buffer, edits) in linked_ranges {
 8148                let snapshot = buffer.read(cx).snapshot();
 8149                use text::ToPoint as TP;
 8150
 8151                let edits = edits
 8152                    .into_iter()
 8153                    .map(|range| {
 8154                        let end_point = TP::to_point(&range.end, &snapshot);
 8155                        let mut start_point = TP::to_point(&range.start, &snapshot);
 8156
 8157                        if end_point == start_point {
 8158                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 8159                                .saturating_sub(1);
 8160                            start_point =
 8161                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 8162                        };
 8163
 8164                        (start_point..end_point, empty_str.clone())
 8165                    })
 8166                    .sorted_by_key(|(range, _)| range.start)
 8167                    .collect::<Vec<_>>();
 8168                buffer.update(cx, |this, cx| {
 8169                    this.edit(edits, None, cx);
 8170                })
 8171            }
 8172            this.refresh_inline_completion(true, false, window, cx);
 8173            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 8174        });
 8175    }
 8176
 8177    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 8178        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8179        self.transact(window, cx, |this, window, cx| {
 8180            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8181                s.move_with(|map, selection| {
 8182                    if selection.is_empty() {
 8183                        let cursor = movement::right(map, selection.head());
 8184                        selection.end = cursor;
 8185                        selection.reversed = true;
 8186                        selection.goal = SelectionGoal::None;
 8187                    }
 8188                })
 8189            });
 8190            this.insert("", window, cx);
 8191            this.refresh_inline_completion(true, false, window, cx);
 8192        });
 8193    }
 8194
 8195    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 8196        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8197        if self.move_to_prev_snippet_tabstop(window, cx) {
 8198            return;
 8199        }
 8200        self.outdent(&Outdent, window, cx);
 8201    }
 8202
 8203    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 8204        if self.move_to_next_snippet_tabstop(window, cx) {
 8205            self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8206            return;
 8207        }
 8208        if self.read_only(cx) {
 8209            return;
 8210        }
 8211        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8212        let mut selections = self.selections.all_adjusted(cx);
 8213        let buffer = self.buffer.read(cx);
 8214        let snapshot = buffer.snapshot(cx);
 8215        let rows_iter = selections.iter().map(|s| s.head().row);
 8216        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 8217
 8218        let mut edits = Vec::new();
 8219        let mut prev_edited_row = 0;
 8220        let mut row_delta = 0;
 8221        for selection in &mut selections {
 8222            if selection.start.row != prev_edited_row {
 8223                row_delta = 0;
 8224            }
 8225            prev_edited_row = selection.end.row;
 8226
 8227            // If the selection is non-empty, then increase the indentation of the selected lines.
 8228            if !selection.is_empty() {
 8229                row_delta =
 8230                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8231                continue;
 8232            }
 8233
 8234            // If the selection is empty and the cursor is in the leading whitespace before the
 8235            // suggested indentation, then auto-indent the line.
 8236            let cursor = selection.head();
 8237            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 8238            if let Some(suggested_indent) =
 8239                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 8240            {
 8241                if cursor.column < suggested_indent.len
 8242                    && cursor.column <= current_indent.len
 8243                    && current_indent.len <= suggested_indent.len
 8244                {
 8245                    selection.start = Point::new(cursor.row, suggested_indent.len);
 8246                    selection.end = selection.start;
 8247                    if row_delta == 0 {
 8248                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 8249                            cursor.row,
 8250                            current_indent,
 8251                            suggested_indent,
 8252                        ));
 8253                        row_delta = suggested_indent.len - current_indent.len;
 8254                    }
 8255                    continue;
 8256                }
 8257            }
 8258
 8259            // Otherwise, insert a hard or soft tab.
 8260            let settings = buffer.language_settings_at(cursor, cx);
 8261            let tab_size = if settings.hard_tabs {
 8262                IndentSize::tab()
 8263            } else {
 8264                let tab_size = settings.tab_size.get();
 8265                let indent_remainder = snapshot
 8266                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 8267                    .flat_map(str::chars)
 8268                    .fold(row_delta % tab_size, |counter: u32, c| {
 8269                        if c == '\t' {
 8270                            0
 8271                        } else {
 8272                            (counter + 1) % tab_size
 8273                        }
 8274                    });
 8275
 8276                let chars_to_next_tab_stop = tab_size - indent_remainder;
 8277                IndentSize::spaces(chars_to_next_tab_stop)
 8278            };
 8279            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 8280            selection.end = selection.start;
 8281            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 8282            row_delta += tab_size.len;
 8283        }
 8284
 8285        self.transact(window, cx, |this, window, cx| {
 8286            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8287            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8288                s.select(selections)
 8289            });
 8290            this.refresh_inline_completion(true, false, window, cx);
 8291        });
 8292    }
 8293
 8294    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 8295        if self.read_only(cx) {
 8296            return;
 8297        }
 8298        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8299        let mut selections = self.selections.all::<Point>(cx);
 8300        let mut prev_edited_row = 0;
 8301        let mut row_delta = 0;
 8302        let mut edits = Vec::new();
 8303        let buffer = self.buffer.read(cx);
 8304        let snapshot = buffer.snapshot(cx);
 8305        for selection in &mut selections {
 8306            if selection.start.row != prev_edited_row {
 8307                row_delta = 0;
 8308            }
 8309            prev_edited_row = selection.end.row;
 8310
 8311            row_delta =
 8312                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8313        }
 8314
 8315        self.transact(window, cx, |this, window, cx| {
 8316            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8317            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8318                s.select(selections)
 8319            });
 8320        });
 8321    }
 8322
 8323    fn indent_selection(
 8324        buffer: &MultiBuffer,
 8325        snapshot: &MultiBufferSnapshot,
 8326        selection: &mut Selection<Point>,
 8327        edits: &mut Vec<(Range<Point>, String)>,
 8328        delta_for_start_row: u32,
 8329        cx: &App,
 8330    ) -> u32 {
 8331        let settings = buffer.language_settings_at(selection.start, cx);
 8332        let tab_size = settings.tab_size.get();
 8333        let indent_kind = if settings.hard_tabs {
 8334            IndentKind::Tab
 8335        } else {
 8336            IndentKind::Space
 8337        };
 8338        let mut start_row = selection.start.row;
 8339        let mut end_row = selection.end.row + 1;
 8340
 8341        // If a selection ends at the beginning of a line, don't indent
 8342        // that last line.
 8343        if selection.end.column == 0 && selection.end.row > selection.start.row {
 8344            end_row -= 1;
 8345        }
 8346
 8347        // Avoid re-indenting a row that has already been indented by a
 8348        // previous selection, but still update this selection's column
 8349        // to reflect that indentation.
 8350        if delta_for_start_row > 0 {
 8351            start_row += 1;
 8352            selection.start.column += delta_for_start_row;
 8353            if selection.end.row == selection.start.row {
 8354                selection.end.column += delta_for_start_row;
 8355            }
 8356        }
 8357
 8358        let mut delta_for_end_row = 0;
 8359        let has_multiple_rows = start_row + 1 != end_row;
 8360        for row in start_row..end_row {
 8361            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 8362            let indent_delta = match (current_indent.kind, indent_kind) {
 8363                (IndentKind::Space, IndentKind::Space) => {
 8364                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 8365                    IndentSize::spaces(columns_to_next_tab_stop)
 8366                }
 8367                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 8368                (_, IndentKind::Tab) => IndentSize::tab(),
 8369            };
 8370
 8371            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 8372                0
 8373            } else {
 8374                selection.start.column
 8375            };
 8376            let row_start = Point::new(row, start);
 8377            edits.push((
 8378                row_start..row_start,
 8379                indent_delta.chars().collect::<String>(),
 8380            ));
 8381
 8382            // Update this selection's endpoints to reflect the indentation.
 8383            if row == selection.start.row {
 8384                selection.start.column += indent_delta.len;
 8385            }
 8386            if row == selection.end.row {
 8387                selection.end.column += indent_delta.len;
 8388                delta_for_end_row = indent_delta.len;
 8389            }
 8390        }
 8391
 8392        if selection.start.row == selection.end.row {
 8393            delta_for_start_row + delta_for_end_row
 8394        } else {
 8395            delta_for_end_row
 8396        }
 8397    }
 8398
 8399    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 8400        if self.read_only(cx) {
 8401            return;
 8402        }
 8403        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8404        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8405        let selections = self.selections.all::<Point>(cx);
 8406        let mut deletion_ranges = Vec::new();
 8407        let mut last_outdent = None;
 8408        {
 8409            let buffer = self.buffer.read(cx);
 8410            let snapshot = buffer.snapshot(cx);
 8411            for selection in &selections {
 8412                let settings = buffer.language_settings_at(selection.start, cx);
 8413                let tab_size = settings.tab_size.get();
 8414                let mut rows = selection.spanned_rows(false, &display_map);
 8415
 8416                // Avoid re-outdenting a row that has already been outdented by a
 8417                // previous selection.
 8418                if let Some(last_row) = last_outdent {
 8419                    if last_row == rows.start {
 8420                        rows.start = rows.start.next_row();
 8421                    }
 8422                }
 8423                let has_multiple_rows = rows.len() > 1;
 8424                for row in rows.iter_rows() {
 8425                    let indent_size = snapshot.indent_size_for_line(row);
 8426                    if indent_size.len > 0 {
 8427                        let deletion_len = match indent_size.kind {
 8428                            IndentKind::Space => {
 8429                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 8430                                if columns_to_prev_tab_stop == 0 {
 8431                                    tab_size
 8432                                } else {
 8433                                    columns_to_prev_tab_stop
 8434                                }
 8435                            }
 8436                            IndentKind::Tab => 1,
 8437                        };
 8438                        let start = if has_multiple_rows
 8439                            || deletion_len > selection.start.column
 8440                            || indent_size.len < selection.start.column
 8441                        {
 8442                            0
 8443                        } else {
 8444                            selection.start.column - deletion_len
 8445                        };
 8446                        deletion_ranges.push(
 8447                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 8448                        );
 8449                        last_outdent = Some(row);
 8450                    }
 8451                }
 8452            }
 8453        }
 8454
 8455        self.transact(window, cx, |this, window, cx| {
 8456            this.buffer.update(cx, |buffer, cx| {
 8457                let empty_str: Arc<str> = Arc::default();
 8458                buffer.edit(
 8459                    deletion_ranges
 8460                        .into_iter()
 8461                        .map(|range| (range, empty_str.clone())),
 8462                    None,
 8463                    cx,
 8464                );
 8465            });
 8466            let selections = this.selections.all::<usize>(cx);
 8467            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8468                s.select(selections)
 8469            });
 8470        });
 8471    }
 8472
 8473    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 8474        if self.read_only(cx) {
 8475            return;
 8476        }
 8477        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8478        let selections = self
 8479            .selections
 8480            .all::<usize>(cx)
 8481            .into_iter()
 8482            .map(|s| s.range());
 8483
 8484        self.transact(window, cx, |this, window, cx| {
 8485            this.buffer.update(cx, |buffer, cx| {
 8486                buffer.autoindent_ranges(selections, cx);
 8487            });
 8488            let selections = this.selections.all::<usize>(cx);
 8489            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8490                s.select(selections)
 8491            });
 8492        });
 8493    }
 8494
 8495    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 8496        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8497        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8498        let selections = self.selections.all::<Point>(cx);
 8499
 8500        let mut new_cursors = Vec::new();
 8501        let mut edit_ranges = Vec::new();
 8502        let mut selections = selections.iter().peekable();
 8503        while let Some(selection) = selections.next() {
 8504            let mut rows = selection.spanned_rows(false, &display_map);
 8505            let goal_display_column = selection.head().to_display_point(&display_map).column();
 8506
 8507            // Accumulate contiguous regions of rows that we want to delete.
 8508            while let Some(next_selection) = selections.peek() {
 8509                let next_rows = next_selection.spanned_rows(false, &display_map);
 8510                if next_rows.start <= rows.end {
 8511                    rows.end = next_rows.end;
 8512                    selections.next().unwrap();
 8513                } else {
 8514                    break;
 8515                }
 8516            }
 8517
 8518            let buffer = &display_map.buffer_snapshot;
 8519            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 8520            let edit_end;
 8521            let cursor_buffer_row;
 8522            if buffer.max_point().row >= rows.end.0 {
 8523                // If there's a line after the range, delete the \n from the end of the row range
 8524                // and position the cursor on the next line.
 8525                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 8526                cursor_buffer_row = rows.end;
 8527            } else {
 8528                // If there isn't a line after the range, delete the \n from the line before the
 8529                // start of the row range and position the cursor there.
 8530                edit_start = edit_start.saturating_sub(1);
 8531                edit_end = buffer.len();
 8532                cursor_buffer_row = rows.start.previous_row();
 8533            }
 8534
 8535            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 8536            *cursor.column_mut() =
 8537                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 8538
 8539            new_cursors.push((
 8540                selection.id,
 8541                buffer.anchor_after(cursor.to_point(&display_map)),
 8542            ));
 8543            edit_ranges.push(edit_start..edit_end);
 8544        }
 8545
 8546        self.transact(window, cx, |this, window, cx| {
 8547            let buffer = this.buffer.update(cx, |buffer, cx| {
 8548                let empty_str: Arc<str> = Arc::default();
 8549                buffer.edit(
 8550                    edit_ranges
 8551                        .into_iter()
 8552                        .map(|range| (range, empty_str.clone())),
 8553                    None,
 8554                    cx,
 8555                );
 8556                buffer.snapshot(cx)
 8557            });
 8558            let new_selections = new_cursors
 8559                .into_iter()
 8560                .map(|(id, cursor)| {
 8561                    let cursor = cursor.to_point(&buffer);
 8562                    Selection {
 8563                        id,
 8564                        start: cursor,
 8565                        end: cursor,
 8566                        reversed: false,
 8567                        goal: SelectionGoal::None,
 8568                    }
 8569                })
 8570                .collect();
 8571
 8572            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8573                s.select(new_selections);
 8574            });
 8575        });
 8576    }
 8577
 8578    pub fn join_lines_impl(
 8579        &mut self,
 8580        insert_whitespace: bool,
 8581        window: &mut Window,
 8582        cx: &mut Context<Self>,
 8583    ) {
 8584        if self.read_only(cx) {
 8585            return;
 8586        }
 8587        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 8588        for selection in self.selections.all::<Point>(cx) {
 8589            let start = MultiBufferRow(selection.start.row);
 8590            // Treat single line selections as if they include the next line. Otherwise this action
 8591            // would do nothing for single line selections individual cursors.
 8592            let end = if selection.start.row == selection.end.row {
 8593                MultiBufferRow(selection.start.row + 1)
 8594            } else {
 8595                MultiBufferRow(selection.end.row)
 8596            };
 8597
 8598            if let Some(last_row_range) = row_ranges.last_mut() {
 8599                if start <= last_row_range.end {
 8600                    last_row_range.end = end;
 8601                    continue;
 8602                }
 8603            }
 8604            row_ranges.push(start..end);
 8605        }
 8606
 8607        let snapshot = self.buffer.read(cx).snapshot(cx);
 8608        let mut cursor_positions = Vec::new();
 8609        for row_range in &row_ranges {
 8610            let anchor = snapshot.anchor_before(Point::new(
 8611                row_range.end.previous_row().0,
 8612                snapshot.line_len(row_range.end.previous_row()),
 8613            ));
 8614            cursor_positions.push(anchor..anchor);
 8615        }
 8616
 8617        self.transact(window, cx, |this, window, cx| {
 8618            for row_range in row_ranges.into_iter().rev() {
 8619                for row in row_range.iter_rows().rev() {
 8620                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 8621                    let next_line_row = row.next_row();
 8622                    let indent = snapshot.indent_size_for_line(next_line_row);
 8623                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 8624
 8625                    let replace =
 8626                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 8627                            " "
 8628                        } else {
 8629                            ""
 8630                        };
 8631
 8632                    this.buffer.update(cx, |buffer, cx| {
 8633                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 8634                    });
 8635                }
 8636            }
 8637
 8638            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8639                s.select_anchor_ranges(cursor_positions)
 8640            });
 8641        });
 8642    }
 8643
 8644    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 8645        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8646        self.join_lines_impl(true, window, cx);
 8647    }
 8648
 8649    pub fn sort_lines_case_sensitive(
 8650        &mut self,
 8651        _: &SortLinesCaseSensitive,
 8652        window: &mut Window,
 8653        cx: &mut Context<Self>,
 8654    ) {
 8655        self.manipulate_lines(window, cx, |lines| lines.sort())
 8656    }
 8657
 8658    pub fn sort_lines_case_insensitive(
 8659        &mut self,
 8660        _: &SortLinesCaseInsensitive,
 8661        window: &mut Window,
 8662        cx: &mut Context<Self>,
 8663    ) {
 8664        self.manipulate_lines(window, cx, |lines| {
 8665            lines.sort_by_key(|line| line.to_lowercase())
 8666        })
 8667    }
 8668
 8669    pub fn unique_lines_case_insensitive(
 8670        &mut self,
 8671        _: &UniqueLinesCaseInsensitive,
 8672        window: &mut Window,
 8673        cx: &mut Context<Self>,
 8674    ) {
 8675        self.manipulate_lines(window, cx, |lines| {
 8676            let mut seen = HashSet::default();
 8677            lines.retain(|line| seen.insert(line.to_lowercase()));
 8678        })
 8679    }
 8680
 8681    pub fn unique_lines_case_sensitive(
 8682        &mut self,
 8683        _: &UniqueLinesCaseSensitive,
 8684        window: &mut Window,
 8685        cx: &mut Context<Self>,
 8686    ) {
 8687        self.manipulate_lines(window, cx, |lines| {
 8688            let mut seen = HashSet::default();
 8689            lines.retain(|line| seen.insert(*line));
 8690        })
 8691    }
 8692
 8693    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 8694        let Some(project) = self.project.clone() else {
 8695            return;
 8696        };
 8697        self.reload(project, window, cx)
 8698            .detach_and_notify_err(window, cx);
 8699    }
 8700
 8701    pub fn restore_file(
 8702        &mut self,
 8703        _: &::git::RestoreFile,
 8704        window: &mut Window,
 8705        cx: &mut Context<Self>,
 8706    ) {
 8707        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8708        let mut buffer_ids = HashSet::default();
 8709        let snapshot = self.buffer().read(cx).snapshot(cx);
 8710        for selection in self.selections.all::<usize>(cx) {
 8711            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 8712        }
 8713
 8714        let buffer = self.buffer().read(cx);
 8715        let ranges = buffer_ids
 8716            .into_iter()
 8717            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 8718            .collect::<Vec<_>>();
 8719
 8720        self.restore_hunks_in_ranges(ranges, window, cx);
 8721    }
 8722
 8723    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 8724        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8725        let selections = self
 8726            .selections
 8727            .all(cx)
 8728            .into_iter()
 8729            .map(|s| s.range())
 8730            .collect();
 8731        self.restore_hunks_in_ranges(selections, window, cx);
 8732    }
 8733
 8734    pub fn restore_hunks_in_ranges(
 8735        &mut self,
 8736        ranges: Vec<Range<Point>>,
 8737        window: &mut Window,
 8738        cx: &mut Context<Editor>,
 8739    ) {
 8740        let mut revert_changes = HashMap::default();
 8741        let chunk_by = self
 8742            .snapshot(window, cx)
 8743            .hunks_for_ranges(ranges)
 8744            .into_iter()
 8745            .chunk_by(|hunk| hunk.buffer_id);
 8746        for (buffer_id, hunks) in &chunk_by {
 8747            let hunks = hunks.collect::<Vec<_>>();
 8748            for hunk in &hunks {
 8749                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 8750            }
 8751            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
 8752        }
 8753        drop(chunk_by);
 8754        if !revert_changes.is_empty() {
 8755            self.transact(window, cx, |editor, window, cx| {
 8756                editor.restore(revert_changes, window, cx);
 8757            });
 8758        }
 8759    }
 8760
 8761    pub fn open_active_item_in_terminal(
 8762        &mut self,
 8763        _: &OpenInTerminal,
 8764        window: &mut Window,
 8765        cx: &mut Context<Self>,
 8766    ) {
 8767        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 8768            let project_path = buffer.read(cx).project_path(cx)?;
 8769            let project = self.project.as_ref()?.read(cx);
 8770            let entry = project.entry_for_path(&project_path, cx)?;
 8771            let parent = match &entry.canonical_path {
 8772                Some(canonical_path) => canonical_path.to_path_buf(),
 8773                None => project.absolute_path(&project_path, cx)?,
 8774            }
 8775            .parent()?
 8776            .to_path_buf();
 8777            Some(parent)
 8778        }) {
 8779            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 8780        }
 8781    }
 8782
 8783    fn set_breakpoint_context_menu(
 8784        &mut self,
 8785        display_row: DisplayRow,
 8786        position: Option<Anchor>,
 8787        clicked_point: gpui::Point<Pixels>,
 8788        window: &mut Window,
 8789        cx: &mut Context<Self>,
 8790    ) {
 8791        if !cx.has_flag::<Debugger>() {
 8792            return;
 8793        }
 8794        let source = self
 8795            .buffer
 8796            .read(cx)
 8797            .snapshot(cx)
 8798            .anchor_before(Point::new(display_row.0, 0u32));
 8799
 8800        let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
 8801
 8802        self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
 8803            self,
 8804            source,
 8805            clicked_point,
 8806            context_menu,
 8807            window,
 8808            cx,
 8809        );
 8810    }
 8811
 8812    fn add_edit_breakpoint_block(
 8813        &mut self,
 8814        anchor: Anchor,
 8815        breakpoint: &Breakpoint,
 8816        edit_action: BreakpointPromptEditAction,
 8817        window: &mut Window,
 8818        cx: &mut Context<Self>,
 8819    ) {
 8820        let weak_editor = cx.weak_entity();
 8821        let bp_prompt = cx.new(|cx| {
 8822            BreakpointPromptEditor::new(
 8823                weak_editor,
 8824                anchor,
 8825                breakpoint.clone(),
 8826                edit_action,
 8827                window,
 8828                cx,
 8829            )
 8830        });
 8831
 8832        let height = bp_prompt.update(cx, |this, cx| {
 8833            this.prompt
 8834                .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
 8835        });
 8836        let cloned_prompt = bp_prompt.clone();
 8837        let blocks = vec![BlockProperties {
 8838            style: BlockStyle::Sticky,
 8839            placement: BlockPlacement::Above(anchor),
 8840            height: Some(height),
 8841            render: Arc::new(move |cx| {
 8842                *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
 8843                cloned_prompt.clone().into_any_element()
 8844            }),
 8845            priority: 0,
 8846        }];
 8847
 8848        let focus_handle = bp_prompt.focus_handle(cx);
 8849        window.focus(&focus_handle);
 8850
 8851        let block_ids = self.insert_blocks(blocks, None, cx);
 8852        bp_prompt.update(cx, |prompt, _| {
 8853            prompt.add_block_ids(block_ids);
 8854        });
 8855    }
 8856
 8857    fn breakpoint_at_cursor_head(
 8858        &self,
 8859        window: &mut Window,
 8860        cx: &mut Context<Self>,
 8861    ) -> Option<(Anchor, Breakpoint)> {
 8862        let cursor_position: Point = self.selections.newest(cx).head();
 8863        self.breakpoint_at_row(cursor_position.row, window, cx)
 8864    }
 8865
 8866    pub(crate) fn breakpoint_at_row(
 8867        &self,
 8868        row: u32,
 8869        window: &mut Window,
 8870        cx: &mut Context<Self>,
 8871    ) -> Option<(Anchor, Breakpoint)> {
 8872        let snapshot = self.snapshot(window, cx);
 8873        let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
 8874
 8875        let project = self.project.clone()?;
 8876
 8877        let buffer_id = breakpoint_position.buffer_id.or_else(|| {
 8878            snapshot
 8879                .buffer_snapshot
 8880                .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
 8881        })?;
 8882
 8883        let enclosing_excerpt = breakpoint_position.excerpt_id;
 8884        let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
 8885        let buffer_snapshot = buffer.read(cx).snapshot();
 8886
 8887        let row = buffer_snapshot
 8888            .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
 8889            .row;
 8890
 8891        let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
 8892        let anchor_end = snapshot
 8893            .buffer_snapshot
 8894            .anchor_after(Point::new(row, line_len));
 8895
 8896        let bp = self
 8897            .breakpoint_store
 8898            .as_ref()?
 8899            .read_with(cx, |breakpoint_store, cx| {
 8900                breakpoint_store
 8901                    .breakpoints(
 8902                        &buffer,
 8903                        Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
 8904                        &buffer_snapshot,
 8905                        cx,
 8906                    )
 8907                    .next()
 8908                    .and_then(|(anchor, bp)| {
 8909                        let breakpoint_row = buffer_snapshot
 8910                            .summary_for_anchor::<text::PointUtf16>(anchor)
 8911                            .row;
 8912
 8913                        if breakpoint_row == row {
 8914                            snapshot
 8915                                .buffer_snapshot
 8916                                .anchor_in_excerpt(enclosing_excerpt, *anchor)
 8917                                .map(|anchor| (anchor, bp.clone()))
 8918                        } else {
 8919                            None
 8920                        }
 8921                    })
 8922            });
 8923        bp
 8924    }
 8925
 8926    pub fn edit_log_breakpoint(
 8927        &mut self,
 8928        _: &EditLogBreakpoint,
 8929        window: &mut Window,
 8930        cx: &mut Context<Self>,
 8931    ) {
 8932        let (anchor, bp) = self
 8933            .breakpoint_at_cursor_head(window, cx)
 8934            .unwrap_or_else(|| {
 8935                let cursor_position: Point = self.selections.newest(cx).head();
 8936
 8937                let breakpoint_position = self
 8938                    .snapshot(window, cx)
 8939                    .display_snapshot
 8940                    .buffer_snapshot
 8941                    .anchor_after(Point::new(cursor_position.row, 0));
 8942
 8943                (
 8944                    breakpoint_position,
 8945                    Breakpoint {
 8946                        message: None,
 8947                        state: BreakpointState::Enabled,
 8948                        condition: None,
 8949                        hit_condition: None,
 8950                    },
 8951                )
 8952            });
 8953
 8954        self.add_edit_breakpoint_block(anchor, &bp, BreakpointPromptEditAction::Log, window, cx);
 8955    }
 8956
 8957    pub fn enable_breakpoint(
 8958        &mut self,
 8959        _: &crate::actions::EnableBreakpoint,
 8960        window: &mut Window,
 8961        cx: &mut Context<Self>,
 8962    ) {
 8963        if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
 8964            if breakpoint.is_disabled() {
 8965                self.edit_breakpoint_at_anchor(
 8966                    anchor,
 8967                    breakpoint,
 8968                    BreakpointEditAction::InvertState,
 8969                    cx,
 8970                );
 8971            }
 8972        }
 8973    }
 8974
 8975    pub fn disable_breakpoint(
 8976        &mut self,
 8977        _: &crate::actions::DisableBreakpoint,
 8978        window: &mut Window,
 8979        cx: &mut Context<Self>,
 8980    ) {
 8981        if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
 8982            if breakpoint.is_enabled() {
 8983                self.edit_breakpoint_at_anchor(
 8984                    anchor,
 8985                    breakpoint,
 8986                    BreakpointEditAction::InvertState,
 8987                    cx,
 8988                );
 8989            }
 8990        }
 8991    }
 8992
 8993    pub fn toggle_breakpoint(
 8994        &mut self,
 8995        _: &crate::actions::ToggleBreakpoint,
 8996        window: &mut Window,
 8997        cx: &mut Context<Self>,
 8998    ) {
 8999        let edit_action = BreakpointEditAction::Toggle;
 9000
 9001        if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
 9002            self.edit_breakpoint_at_anchor(anchor, breakpoint, edit_action, cx);
 9003        } else {
 9004            let cursor_position: Point = self.selections.newest(cx).head();
 9005
 9006            let breakpoint_position = self
 9007                .snapshot(window, cx)
 9008                .display_snapshot
 9009                .buffer_snapshot
 9010                .anchor_after(Point::new(cursor_position.row, 0));
 9011
 9012            self.edit_breakpoint_at_anchor(
 9013                breakpoint_position,
 9014                Breakpoint::new_standard(),
 9015                edit_action,
 9016                cx,
 9017            );
 9018        }
 9019    }
 9020
 9021    pub fn edit_breakpoint_at_anchor(
 9022        &mut self,
 9023        breakpoint_position: Anchor,
 9024        breakpoint: Breakpoint,
 9025        edit_action: BreakpointEditAction,
 9026        cx: &mut Context<Self>,
 9027    ) {
 9028        let Some(breakpoint_store) = &self.breakpoint_store else {
 9029            return;
 9030        };
 9031
 9032        let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
 9033            if breakpoint_position == Anchor::min() {
 9034                self.buffer()
 9035                    .read(cx)
 9036                    .excerpt_buffer_ids()
 9037                    .into_iter()
 9038                    .next()
 9039            } else {
 9040                None
 9041            }
 9042        }) else {
 9043            return;
 9044        };
 9045
 9046        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
 9047            return;
 9048        };
 9049
 9050        breakpoint_store.update(cx, |breakpoint_store, cx| {
 9051            breakpoint_store.toggle_breakpoint(
 9052                buffer,
 9053                (breakpoint_position.text_anchor, breakpoint),
 9054                edit_action,
 9055                cx,
 9056            );
 9057        });
 9058
 9059        cx.notify();
 9060    }
 9061
 9062    #[cfg(any(test, feature = "test-support"))]
 9063    pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
 9064        self.breakpoint_store.clone()
 9065    }
 9066
 9067    pub fn prepare_restore_change(
 9068        &self,
 9069        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 9070        hunk: &MultiBufferDiffHunk,
 9071        cx: &mut App,
 9072    ) -> Option<()> {
 9073        if hunk.is_created_file() {
 9074            return None;
 9075        }
 9076        let buffer = self.buffer.read(cx);
 9077        let diff = buffer.diff_for(hunk.buffer_id)?;
 9078        let buffer = buffer.buffer(hunk.buffer_id)?;
 9079        let buffer = buffer.read(cx);
 9080        let original_text = diff
 9081            .read(cx)
 9082            .base_text()
 9083            .as_rope()
 9084            .slice(hunk.diff_base_byte_range.clone());
 9085        let buffer_snapshot = buffer.snapshot();
 9086        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 9087        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 9088            probe
 9089                .0
 9090                .start
 9091                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 9092                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 9093        }) {
 9094            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 9095            Some(())
 9096        } else {
 9097            None
 9098        }
 9099    }
 9100
 9101    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 9102        self.manipulate_lines(window, cx, |lines| lines.reverse())
 9103    }
 9104
 9105    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 9106        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 9107    }
 9108
 9109    fn manipulate_lines<Fn>(
 9110        &mut self,
 9111        window: &mut Window,
 9112        cx: &mut Context<Self>,
 9113        mut callback: Fn,
 9114    ) where
 9115        Fn: FnMut(&mut Vec<&str>),
 9116    {
 9117        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9118
 9119        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9120        let buffer = self.buffer.read(cx).snapshot(cx);
 9121
 9122        let mut edits = Vec::new();
 9123
 9124        let selections = self.selections.all::<Point>(cx);
 9125        let mut selections = selections.iter().peekable();
 9126        let mut contiguous_row_selections = Vec::new();
 9127        let mut new_selections = Vec::new();
 9128        let mut added_lines = 0;
 9129        let mut removed_lines = 0;
 9130
 9131        while let Some(selection) = selections.next() {
 9132            let (start_row, end_row) = consume_contiguous_rows(
 9133                &mut contiguous_row_selections,
 9134                selection,
 9135                &display_map,
 9136                &mut selections,
 9137            );
 9138
 9139            let start_point = Point::new(start_row.0, 0);
 9140            let end_point = Point::new(
 9141                end_row.previous_row().0,
 9142                buffer.line_len(end_row.previous_row()),
 9143            );
 9144            let text = buffer
 9145                .text_for_range(start_point..end_point)
 9146                .collect::<String>();
 9147
 9148            let mut lines = text.split('\n').collect_vec();
 9149
 9150            let lines_before = lines.len();
 9151            callback(&mut lines);
 9152            let lines_after = lines.len();
 9153
 9154            edits.push((start_point..end_point, lines.join("\n")));
 9155
 9156            // Selections must change based on added and removed line count
 9157            let start_row =
 9158                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 9159            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 9160            new_selections.push(Selection {
 9161                id: selection.id,
 9162                start: start_row,
 9163                end: end_row,
 9164                goal: SelectionGoal::None,
 9165                reversed: selection.reversed,
 9166            });
 9167
 9168            if lines_after > lines_before {
 9169                added_lines += lines_after - lines_before;
 9170            } else if lines_before > lines_after {
 9171                removed_lines += lines_before - lines_after;
 9172            }
 9173        }
 9174
 9175        self.transact(window, cx, |this, window, cx| {
 9176            let buffer = this.buffer.update(cx, |buffer, cx| {
 9177                buffer.edit(edits, None, cx);
 9178                buffer.snapshot(cx)
 9179            });
 9180
 9181            // Recalculate offsets on newly edited buffer
 9182            let new_selections = new_selections
 9183                .iter()
 9184                .map(|s| {
 9185                    let start_point = Point::new(s.start.0, 0);
 9186                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 9187                    Selection {
 9188                        id: s.id,
 9189                        start: buffer.point_to_offset(start_point),
 9190                        end: buffer.point_to_offset(end_point),
 9191                        goal: s.goal,
 9192                        reversed: s.reversed,
 9193                    }
 9194                })
 9195                .collect();
 9196
 9197            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9198                s.select(new_selections);
 9199            });
 9200
 9201            this.request_autoscroll(Autoscroll::fit(), cx);
 9202        });
 9203    }
 9204
 9205    pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
 9206        self.manipulate_text(window, cx, |text| {
 9207            let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
 9208            if has_upper_case_characters {
 9209                text.to_lowercase()
 9210            } else {
 9211                text.to_uppercase()
 9212            }
 9213        })
 9214    }
 9215
 9216    pub fn convert_to_upper_case(
 9217        &mut self,
 9218        _: &ConvertToUpperCase,
 9219        window: &mut Window,
 9220        cx: &mut Context<Self>,
 9221    ) {
 9222        self.manipulate_text(window, cx, |text| text.to_uppercase())
 9223    }
 9224
 9225    pub fn convert_to_lower_case(
 9226        &mut self,
 9227        _: &ConvertToLowerCase,
 9228        window: &mut Window,
 9229        cx: &mut Context<Self>,
 9230    ) {
 9231        self.manipulate_text(window, cx, |text| text.to_lowercase())
 9232    }
 9233
 9234    pub fn convert_to_title_case(
 9235        &mut self,
 9236        _: &ConvertToTitleCase,
 9237        window: &mut Window,
 9238        cx: &mut Context<Self>,
 9239    ) {
 9240        self.manipulate_text(window, cx, |text| {
 9241            text.split('\n')
 9242                .map(|line| line.to_case(Case::Title))
 9243                .join("\n")
 9244        })
 9245    }
 9246
 9247    pub fn convert_to_snake_case(
 9248        &mut self,
 9249        _: &ConvertToSnakeCase,
 9250        window: &mut Window,
 9251        cx: &mut Context<Self>,
 9252    ) {
 9253        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 9254    }
 9255
 9256    pub fn convert_to_kebab_case(
 9257        &mut self,
 9258        _: &ConvertToKebabCase,
 9259        window: &mut Window,
 9260        cx: &mut Context<Self>,
 9261    ) {
 9262        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 9263    }
 9264
 9265    pub fn convert_to_upper_camel_case(
 9266        &mut self,
 9267        _: &ConvertToUpperCamelCase,
 9268        window: &mut Window,
 9269        cx: &mut Context<Self>,
 9270    ) {
 9271        self.manipulate_text(window, cx, |text| {
 9272            text.split('\n')
 9273                .map(|line| line.to_case(Case::UpperCamel))
 9274                .join("\n")
 9275        })
 9276    }
 9277
 9278    pub fn convert_to_lower_camel_case(
 9279        &mut self,
 9280        _: &ConvertToLowerCamelCase,
 9281        window: &mut Window,
 9282        cx: &mut Context<Self>,
 9283    ) {
 9284        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 9285    }
 9286
 9287    pub fn convert_to_opposite_case(
 9288        &mut self,
 9289        _: &ConvertToOppositeCase,
 9290        window: &mut Window,
 9291        cx: &mut Context<Self>,
 9292    ) {
 9293        self.manipulate_text(window, cx, |text| {
 9294            text.chars()
 9295                .fold(String::with_capacity(text.len()), |mut t, c| {
 9296                    if c.is_uppercase() {
 9297                        t.extend(c.to_lowercase());
 9298                    } else {
 9299                        t.extend(c.to_uppercase());
 9300                    }
 9301                    t
 9302                })
 9303        })
 9304    }
 9305
 9306    pub fn convert_to_rot13(
 9307        &mut self,
 9308        _: &ConvertToRot13,
 9309        window: &mut Window,
 9310        cx: &mut Context<Self>,
 9311    ) {
 9312        self.manipulate_text(window, cx, |text| {
 9313            text.chars()
 9314                .map(|c| match c {
 9315                    'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
 9316                    'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
 9317                    _ => c,
 9318                })
 9319                .collect()
 9320        })
 9321    }
 9322
 9323    pub fn convert_to_rot47(
 9324        &mut self,
 9325        _: &ConvertToRot47,
 9326        window: &mut Window,
 9327        cx: &mut Context<Self>,
 9328    ) {
 9329        self.manipulate_text(window, cx, |text| {
 9330            text.chars()
 9331                .map(|c| {
 9332                    let code_point = c as u32;
 9333                    if code_point >= 33 && code_point <= 126 {
 9334                        return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
 9335                    }
 9336                    c
 9337                })
 9338                .collect()
 9339        })
 9340    }
 9341
 9342    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 9343    where
 9344        Fn: FnMut(&str) -> String,
 9345    {
 9346        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9347        let buffer = self.buffer.read(cx).snapshot(cx);
 9348
 9349        let mut new_selections = Vec::new();
 9350        let mut edits = Vec::new();
 9351        let mut selection_adjustment = 0i32;
 9352
 9353        for selection in self.selections.all::<usize>(cx) {
 9354            let selection_is_empty = selection.is_empty();
 9355
 9356            let (start, end) = if selection_is_empty {
 9357                let word_range = movement::surrounding_word(
 9358                    &display_map,
 9359                    selection.start.to_display_point(&display_map),
 9360                );
 9361                let start = word_range.start.to_offset(&display_map, Bias::Left);
 9362                let end = word_range.end.to_offset(&display_map, Bias::Left);
 9363                (start, end)
 9364            } else {
 9365                (selection.start, selection.end)
 9366            };
 9367
 9368            let text = buffer.text_for_range(start..end).collect::<String>();
 9369            let old_length = text.len() as i32;
 9370            let text = callback(&text);
 9371
 9372            new_selections.push(Selection {
 9373                start: (start as i32 - selection_adjustment) as usize,
 9374                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 9375                goal: SelectionGoal::None,
 9376                ..selection
 9377            });
 9378
 9379            selection_adjustment += old_length - text.len() as i32;
 9380
 9381            edits.push((start..end, text));
 9382        }
 9383
 9384        self.transact(window, cx, |this, window, cx| {
 9385            this.buffer.update(cx, |buffer, cx| {
 9386                buffer.edit(edits, None, cx);
 9387            });
 9388
 9389            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9390                s.select(new_selections);
 9391            });
 9392
 9393            this.request_autoscroll(Autoscroll::fit(), cx);
 9394        });
 9395    }
 9396
 9397    pub fn duplicate(
 9398        &mut self,
 9399        upwards: bool,
 9400        whole_lines: bool,
 9401        window: &mut Window,
 9402        cx: &mut Context<Self>,
 9403    ) {
 9404        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9405
 9406        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9407        let buffer = &display_map.buffer_snapshot;
 9408        let selections = self.selections.all::<Point>(cx);
 9409
 9410        let mut edits = Vec::new();
 9411        let mut selections_iter = selections.iter().peekable();
 9412        while let Some(selection) = selections_iter.next() {
 9413            let mut rows = selection.spanned_rows(false, &display_map);
 9414            // duplicate line-wise
 9415            if whole_lines || selection.start == selection.end {
 9416                // Avoid duplicating the same lines twice.
 9417                while let Some(next_selection) = selections_iter.peek() {
 9418                    let next_rows = next_selection.spanned_rows(false, &display_map);
 9419                    if next_rows.start < rows.end {
 9420                        rows.end = next_rows.end;
 9421                        selections_iter.next().unwrap();
 9422                    } else {
 9423                        break;
 9424                    }
 9425                }
 9426
 9427                // Copy the text from the selected row region and splice it either at the start
 9428                // or end of the region.
 9429                let start = Point::new(rows.start.0, 0);
 9430                let end = Point::new(
 9431                    rows.end.previous_row().0,
 9432                    buffer.line_len(rows.end.previous_row()),
 9433                );
 9434                let text = buffer
 9435                    .text_for_range(start..end)
 9436                    .chain(Some("\n"))
 9437                    .collect::<String>();
 9438                let insert_location = if upwards {
 9439                    Point::new(rows.end.0, 0)
 9440                } else {
 9441                    start
 9442                };
 9443                edits.push((insert_location..insert_location, text));
 9444            } else {
 9445                // duplicate character-wise
 9446                let start = selection.start;
 9447                let end = selection.end;
 9448                let text = buffer.text_for_range(start..end).collect::<String>();
 9449                edits.push((selection.end..selection.end, text));
 9450            }
 9451        }
 9452
 9453        self.transact(window, cx, |this, _, cx| {
 9454            this.buffer.update(cx, |buffer, cx| {
 9455                buffer.edit(edits, None, cx);
 9456            });
 9457
 9458            this.request_autoscroll(Autoscroll::fit(), cx);
 9459        });
 9460    }
 9461
 9462    pub fn duplicate_line_up(
 9463        &mut self,
 9464        _: &DuplicateLineUp,
 9465        window: &mut Window,
 9466        cx: &mut Context<Self>,
 9467    ) {
 9468        self.duplicate(true, true, window, cx);
 9469    }
 9470
 9471    pub fn duplicate_line_down(
 9472        &mut self,
 9473        _: &DuplicateLineDown,
 9474        window: &mut Window,
 9475        cx: &mut Context<Self>,
 9476    ) {
 9477        self.duplicate(false, true, window, cx);
 9478    }
 9479
 9480    pub fn duplicate_selection(
 9481        &mut self,
 9482        _: &DuplicateSelection,
 9483        window: &mut Window,
 9484        cx: &mut Context<Self>,
 9485    ) {
 9486        self.duplicate(false, false, window, cx);
 9487    }
 9488
 9489    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 9490        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9491
 9492        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9493        let buffer = self.buffer.read(cx).snapshot(cx);
 9494
 9495        let mut edits = Vec::new();
 9496        let mut unfold_ranges = Vec::new();
 9497        let mut refold_creases = Vec::new();
 9498
 9499        let selections = self.selections.all::<Point>(cx);
 9500        let mut selections = selections.iter().peekable();
 9501        let mut contiguous_row_selections = Vec::new();
 9502        let mut new_selections = Vec::new();
 9503
 9504        while let Some(selection) = selections.next() {
 9505            // Find all the selections that span a contiguous row range
 9506            let (start_row, end_row) = consume_contiguous_rows(
 9507                &mut contiguous_row_selections,
 9508                selection,
 9509                &display_map,
 9510                &mut selections,
 9511            );
 9512
 9513            // Move the text spanned by the row range to be before the line preceding the row range
 9514            if start_row.0 > 0 {
 9515                let range_to_move = Point::new(
 9516                    start_row.previous_row().0,
 9517                    buffer.line_len(start_row.previous_row()),
 9518                )
 9519                    ..Point::new(
 9520                        end_row.previous_row().0,
 9521                        buffer.line_len(end_row.previous_row()),
 9522                    );
 9523                let insertion_point = display_map
 9524                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 9525                    .0;
 9526
 9527                // Don't move lines across excerpts
 9528                if buffer
 9529                    .excerpt_containing(insertion_point..range_to_move.end)
 9530                    .is_some()
 9531                {
 9532                    let text = buffer
 9533                        .text_for_range(range_to_move.clone())
 9534                        .flat_map(|s| s.chars())
 9535                        .skip(1)
 9536                        .chain(['\n'])
 9537                        .collect::<String>();
 9538
 9539                    edits.push((
 9540                        buffer.anchor_after(range_to_move.start)
 9541                            ..buffer.anchor_before(range_to_move.end),
 9542                        String::new(),
 9543                    ));
 9544                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9545                    edits.push((insertion_anchor..insertion_anchor, text));
 9546
 9547                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 9548
 9549                    // Move selections up
 9550                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9551                        |mut selection| {
 9552                            selection.start.row -= row_delta;
 9553                            selection.end.row -= row_delta;
 9554                            selection
 9555                        },
 9556                    ));
 9557
 9558                    // Move folds up
 9559                    unfold_ranges.push(range_to_move.clone());
 9560                    for fold in display_map.folds_in_range(
 9561                        buffer.anchor_before(range_to_move.start)
 9562                            ..buffer.anchor_after(range_to_move.end),
 9563                    ) {
 9564                        let mut start = fold.range.start.to_point(&buffer);
 9565                        let mut end = fold.range.end.to_point(&buffer);
 9566                        start.row -= row_delta;
 9567                        end.row -= row_delta;
 9568                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9569                    }
 9570                }
 9571            }
 9572
 9573            // If we didn't move line(s), preserve the existing selections
 9574            new_selections.append(&mut contiguous_row_selections);
 9575        }
 9576
 9577        self.transact(window, cx, |this, window, cx| {
 9578            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9579            this.buffer.update(cx, |buffer, cx| {
 9580                for (range, text) in edits {
 9581                    buffer.edit([(range, text)], None, cx);
 9582                }
 9583            });
 9584            this.fold_creases(refold_creases, true, window, cx);
 9585            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9586                s.select(new_selections);
 9587            })
 9588        });
 9589    }
 9590
 9591    pub fn move_line_down(
 9592        &mut self,
 9593        _: &MoveLineDown,
 9594        window: &mut Window,
 9595        cx: &mut Context<Self>,
 9596    ) {
 9597        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9598
 9599        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9600        let buffer = self.buffer.read(cx).snapshot(cx);
 9601
 9602        let mut edits = Vec::new();
 9603        let mut unfold_ranges = Vec::new();
 9604        let mut refold_creases = Vec::new();
 9605
 9606        let selections = self.selections.all::<Point>(cx);
 9607        let mut selections = selections.iter().peekable();
 9608        let mut contiguous_row_selections = Vec::new();
 9609        let mut new_selections = Vec::new();
 9610
 9611        while let Some(selection) = selections.next() {
 9612            // Find all the selections that span a contiguous row range
 9613            let (start_row, end_row) = consume_contiguous_rows(
 9614                &mut contiguous_row_selections,
 9615                selection,
 9616                &display_map,
 9617                &mut selections,
 9618            );
 9619
 9620            // Move the text spanned by the row range to be after the last line of the row range
 9621            if end_row.0 <= buffer.max_point().row {
 9622                let range_to_move =
 9623                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 9624                let insertion_point = display_map
 9625                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 9626                    .0;
 9627
 9628                // Don't move lines across excerpt boundaries
 9629                if buffer
 9630                    .excerpt_containing(range_to_move.start..insertion_point)
 9631                    .is_some()
 9632                {
 9633                    let mut text = String::from("\n");
 9634                    text.extend(buffer.text_for_range(range_to_move.clone()));
 9635                    text.pop(); // Drop trailing newline
 9636                    edits.push((
 9637                        buffer.anchor_after(range_to_move.start)
 9638                            ..buffer.anchor_before(range_to_move.end),
 9639                        String::new(),
 9640                    ));
 9641                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9642                    edits.push((insertion_anchor..insertion_anchor, text));
 9643
 9644                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 9645
 9646                    // Move selections down
 9647                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9648                        |mut selection| {
 9649                            selection.start.row += row_delta;
 9650                            selection.end.row += row_delta;
 9651                            selection
 9652                        },
 9653                    ));
 9654
 9655                    // Move folds down
 9656                    unfold_ranges.push(range_to_move.clone());
 9657                    for fold in display_map.folds_in_range(
 9658                        buffer.anchor_before(range_to_move.start)
 9659                            ..buffer.anchor_after(range_to_move.end),
 9660                    ) {
 9661                        let mut start = fold.range.start.to_point(&buffer);
 9662                        let mut end = fold.range.end.to_point(&buffer);
 9663                        start.row += row_delta;
 9664                        end.row += row_delta;
 9665                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9666                    }
 9667                }
 9668            }
 9669
 9670            // If we didn't move line(s), preserve the existing selections
 9671            new_selections.append(&mut contiguous_row_selections);
 9672        }
 9673
 9674        self.transact(window, cx, |this, window, cx| {
 9675            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9676            this.buffer.update(cx, |buffer, cx| {
 9677                for (range, text) in edits {
 9678                    buffer.edit([(range, text)], None, cx);
 9679                }
 9680            });
 9681            this.fold_creases(refold_creases, true, window, cx);
 9682            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9683                s.select(new_selections)
 9684            });
 9685        });
 9686    }
 9687
 9688    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 9689        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9690        let text_layout_details = &self.text_layout_details(window);
 9691        self.transact(window, cx, |this, window, cx| {
 9692            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9693                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 9694                s.move_with(|display_map, selection| {
 9695                    if !selection.is_empty() {
 9696                        return;
 9697                    }
 9698
 9699                    let mut head = selection.head();
 9700                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 9701                    if head.column() == display_map.line_len(head.row()) {
 9702                        transpose_offset = display_map
 9703                            .buffer_snapshot
 9704                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9705                    }
 9706
 9707                    if transpose_offset == 0 {
 9708                        return;
 9709                    }
 9710
 9711                    *head.column_mut() += 1;
 9712                    head = display_map.clip_point(head, Bias::Right);
 9713                    let goal = SelectionGoal::HorizontalPosition(
 9714                        display_map
 9715                            .x_for_display_point(head, text_layout_details)
 9716                            .into(),
 9717                    );
 9718                    selection.collapse_to(head, goal);
 9719
 9720                    let transpose_start = display_map
 9721                        .buffer_snapshot
 9722                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9723                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 9724                        let transpose_end = display_map
 9725                            .buffer_snapshot
 9726                            .clip_offset(transpose_offset + 1, Bias::Right);
 9727                        if let Some(ch) =
 9728                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 9729                        {
 9730                            edits.push((transpose_start..transpose_offset, String::new()));
 9731                            edits.push((transpose_end..transpose_end, ch.to_string()));
 9732                        }
 9733                    }
 9734                });
 9735                edits
 9736            });
 9737            this.buffer
 9738                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 9739            let selections = this.selections.all::<usize>(cx);
 9740            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9741                s.select(selections);
 9742            });
 9743        });
 9744    }
 9745
 9746    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 9747        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9748        self.rewrap_impl(RewrapOptions::default(), cx)
 9749    }
 9750
 9751    pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
 9752        let buffer = self.buffer.read(cx).snapshot(cx);
 9753        let selections = self.selections.all::<Point>(cx);
 9754        let mut selections = selections.iter().peekable();
 9755
 9756        let mut edits = Vec::new();
 9757        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 9758
 9759        while let Some(selection) = selections.next() {
 9760            let mut start_row = selection.start.row;
 9761            let mut end_row = selection.end.row;
 9762
 9763            // Skip selections that overlap with a range that has already been rewrapped.
 9764            let selection_range = start_row..end_row;
 9765            if rewrapped_row_ranges
 9766                .iter()
 9767                .any(|range| range.overlaps(&selection_range))
 9768            {
 9769                continue;
 9770            }
 9771
 9772            let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
 9773
 9774            // Since not all lines in the selection may be at the same indent
 9775            // level, choose the indent size that is the most common between all
 9776            // of the lines.
 9777            //
 9778            // If there is a tie, we use the deepest indent.
 9779            let (indent_size, indent_end) = {
 9780                let mut indent_size_occurrences = HashMap::default();
 9781                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 9782
 9783                for row in start_row..=end_row {
 9784                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 9785                    rows_by_indent_size.entry(indent).or_default().push(row);
 9786                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 9787                }
 9788
 9789                let indent_size = indent_size_occurrences
 9790                    .into_iter()
 9791                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 9792                    .map(|(indent, _)| indent)
 9793                    .unwrap_or_default();
 9794                let row = rows_by_indent_size[&indent_size][0];
 9795                let indent_end = Point::new(row, indent_size.len);
 9796
 9797                (indent_size, indent_end)
 9798            };
 9799
 9800            let mut line_prefix = indent_size.chars().collect::<String>();
 9801
 9802            let mut inside_comment = false;
 9803            if let Some(comment_prefix) =
 9804                buffer
 9805                    .language_scope_at(selection.head())
 9806                    .and_then(|language| {
 9807                        language
 9808                            .line_comment_prefixes()
 9809                            .iter()
 9810                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 9811                            .cloned()
 9812                    })
 9813            {
 9814                line_prefix.push_str(&comment_prefix);
 9815                inside_comment = true;
 9816            }
 9817
 9818            let language_settings = buffer.language_settings_at(selection.head(), cx);
 9819            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 9820                RewrapBehavior::InComments => inside_comment,
 9821                RewrapBehavior::InSelections => !selection.is_empty(),
 9822                RewrapBehavior::Anywhere => true,
 9823            };
 9824
 9825            let should_rewrap = options.override_language_settings
 9826                || allow_rewrap_based_on_language
 9827                || self.hard_wrap.is_some();
 9828            if !should_rewrap {
 9829                continue;
 9830            }
 9831
 9832            if selection.is_empty() {
 9833                'expand_upwards: while start_row > 0 {
 9834                    let prev_row = start_row - 1;
 9835                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 9836                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 9837                    {
 9838                        start_row = prev_row;
 9839                    } else {
 9840                        break 'expand_upwards;
 9841                    }
 9842                }
 9843
 9844                'expand_downwards: while end_row < buffer.max_point().row {
 9845                    let next_row = end_row + 1;
 9846                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 9847                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 9848                    {
 9849                        end_row = next_row;
 9850                    } else {
 9851                        break 'expand_downwards;
 9852                    }
 9853                }
 9854            }
 9855
 9856            let start = Point::new(start_row, 0);
 9857            let start_offset = start.to_offset(&buffer);
 9858            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 9859            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 9860            let Some(lines_without_prefixes) = selection_text
 9861                .lines()
 9862                .map(|line| {
 9863                    line.strip_prefix(&line_prefix)
 9864                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 9865                        .ok_or_else(|| {
 9866                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 9867                        })
 9868                })
 9869                .collect::<Result<Vec<_>, _>>()
 9870                .log_err()
 9871            else {
 9872                continue;
 9873            };
 9874
 9875            let wrap_column = self.hard_wrap.unwrap_or_else(|| {
 9876                buffer
 9877                    .language_settings_at(Point::new(start_row, 0), cx)
 9878                    .preferred_line_length as usize
 9879            });
 9880            let wrapped_text = wrap_with_prefix(
 9881                line_prefix,
 9882                lines_without_prefixes.join("\n"),
 9883                wrap_column,
 9884                tab_size,
 9885                options.preserve_existing_whitespace,
 9886            );
 9887
 9888            // TODO: should always use char-based diff while still supporting cursor behavior that
 9889            // matches vim.
 9890            let mut diff_options = DiffOptions::default();
 9891            if options.override_language_settings {
 9892                diff_options.max_word_diff_len = 0;
 9893                diff_options.max_word_diff_line_count = 0;
 9894            } else {
 9895                diff_options.max_word_diff_len = usize::MAX;
 9896                diff_options.max_word_diff_line_count = usize::MAX;
 9897            }
 9898
 9899            for (old_range, new_text) in
 9900                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
 9901            {
 9902                let edit_start = buffer.anchor_after(start_offset + old_range.start);
 9903                let edit_end = buffer.anchor_after(start_offset + old_range.end);
 9904                edits.push((edit_start..edit_end, new_text));
 9905            }
 9906
 9907            rewrapped_row_ranges.push(start_row..=end_row);
 9908        }
 9909
 9910        self.buffer
 9911            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 9912    }
 9913
 9914    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 9915        let mut text = String::new();
 9916        let buffer = self.buffer.read(cx).snapshot(cx);
 9917        let mut selections = self.selections.all::<Point>(cx);
 9918        let mut clipboard_selections = Vec::with_capacity(selections.len());
 9919        {
 9920            let max_point = buffer.max_point();
 9921            let mut is_first = true;
 9922            for selection in &mut selections {
 9923                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 9924                if is_entire_line {
 9925                    selection.start = Point::new(selection.start.row, 0);
 9926                    if !selection.is_empty() && selection.end.column == 0 {
 9927                        selection.end = cmp::min(max_point, selection.end);
 9928                    } else {
 9929                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 9930                    }
 9931                    selection.goal = SelectionGoal::None;
 9932                }
 9933                if is_first {
 9934                    is_first = false;
 9935                } else {
 9936                    text += "\n";
 9937                }
 9938                let mut len = 0;
 9939                for chunk in buffer.text_for_range(selection.start..selection.end) {
 9940                    text.push_str(chunk);
 9941                    len += chunk.len();
 9942                }
 9943                clipboard_selections.push(ClipboardSelection {
 9944                    len,
 9945                    is_entire_line,
 9946                    first_line_indent: buffer
 9947                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 9948                        .len,
 9949                });
 9950            }
 9951        }
 9952
 9953        self.transact(window, cx, |this, window, cx| {
 9954            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9955                s.select(selections);
 9956            });
 9957            this.insert("", window, cx);
 9958        });
 9959        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 9960    }
 9961
 9962    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 9963        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9964        let item = self.cut_common(window, cx);
 9965        cx.write_to_clipboard(item);
 9966    }
 9967
 9968    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 9969        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9970        self.change_selections(None, window, cx, |s| {
 9971            s.move_with(|snapshot, sel| {
 9972                if sel.is_empty() {
 9973                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 9974                }
 9975            });
 9976        });
 9977        let item = self.cut_common(window, cx);
 9978        cx.set_global(KillRing(item))
 9979    }
 9980
 9981    pub fn kill_ring_yank(
 9982        &mut self,
 9983        _: &KillRingYank,
 9984        window: &mut Window,
 9985        cx: &mut Context<Self>,
 9986    ) {
 9987        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9988        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 9989            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 9990                (kill_ring.text().to_string(), kill_ring.metadata_json())
 9991            } else {
 9992                return;
 9993            }
 9994        } else {
 9995            return;
 9996        };
 9997        self.do_paste(&text, metadata, false, window, cx);
 9998    }
 9999
10000    pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10001        self.do_copy(true, cx);
10002    }
10003
10004    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10005        self.do_copy(false, cx);
10006    }
10007
10008    fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10009        let selections = self.selections.all::<Point>(cx);
10010        let buffer = self.buffer.read(cx).read(cx);
10011        let mut text = String::new();
10012
10013        let mut clipboard_selections = Vec::with_capacity(selections.len());
10014        {
10015            let max_point = buffer.max_point();
10016            let mut is_first = true;
10017            for selection in &selections {
10018                let mut start = selection.start;
10019                let mut end = selection.end;
10020                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10021                if is_entire_line {
10022                    start = Point::new(start.row, 0);
10023                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
10024                }
10025
10026                let mut trimmed_selections = Vec::new();
10027                if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10028                    let row = MultiBufferRow(start.row);
10029                    let first_indent = buffer.indent_size_for_line(row);
10030                    if first_indent.len == 0 || start.column > first_indent.len {
10031                        trimmed_selections.push(start..end);
10032                    } else {
10033                        trimmed_selections.push(
10034                            Point::new(row.0, first_indent.len)
10035                                ..Point::new(row.0, buffer.line_len(row)),
10036                        );
10037                        for row in start.row + 1..=end.row {
10038                            let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10039                            if row_indent_size.len >= first_indent.len {
10040                                trimmed_selections.push(
10041                                    Point::new(row, first_indent.len)
10042                                        ..Point::new(row, buffer.line_len(MultiBufferRow(row))),
10043                                );
10044                            } else {
10045                                trimmed_selections.clear();
10046                                trimmed_selections.push(start..end);
10047                                break;
10048                            }
10049                        }
10050                    }
10051                } else {
10052                    trimmed_selections.push(start..end);
10053                }
10054
10055                for trimmed_range in trimmed_selections {
10056                    if is_first {
10057                        is_first = false;
10058                    } else {
10059                        text += "\n";
10060                    }
10061                    let mut len = 0;
10062                    for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10063                        text.push_str(chunk);
10064                        len += chunk.len();
10065                    }
10066                    clipboard_selections.push(ClipboardSelection {
10067                        len,
10068                        is_entire_line,
10069                        first_line_indent: buffer
10070                            .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10071                            .len,
10072                    });
10073                }
10074            }
10075        }
10076
10077        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10078            text,
10079            clipboard_selections,
10080        ));
10081    }
10082
10083    pub fn do_paste(
10084        &mut self,
10085        text: &String,
10086        clipboard_selections: Option<Vec<ClipboardSelection>>,
10087        handle_entire_lines: bool,
10088        window: &mut Window,
10089        cx: &mut Context<Self>,
10090    ) {
10091        if self.read_only(cx) {
10092            return;
10093        }
10094
10095        let clipboard_text = Cow::Borrowed(text);
10096
10097        self.transact(window, cx, |this, window, cx| {
10098            if let Some(mut clipboard_selections) = clipboard_selections {
10099                let old_selections = this.selections.all::<usize>(cx);
10100                let all_selections_were_entire_line =
10101                    clipboard_selections.iter().all(|s| s.is_entire_line);
10102                let first_selection_indent_column =
10103                    clipboard_selections.first().map(|s| s.first_line_indent);
10104                if clipboard_selections.len() != old_selections.len() {
10105                    clipboard_selections.drain(..);
10106                }
10107                let cursor_offset = this.selections.last::<usize>(cx).head();
10108                let mut auto_indent_on_paste = true;
10109
10110                this.buffer.update(cx, |buffer, cx| {
10111                    let snapshot = buffer.read(cx);
10112                    auto_indent_on_paste = snapshot
10113                        .language_settings_at(cursor_offset, cx)
10114                        .auto_indent_on_paste;
10115
10116                    let mut start_offset = 0;
10117                    let mut edits = Vec::new();
10118                    let mut original_indent_columns = Vec::new();
10119                    for (ix, selection) in old_selections.iter().enumerate() {
10120                        let to_insert;
10121                        let entire_line;
10122                        let original_indent_column;
10123                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10124                            let end_offset = start_offset + clipboard_selection.len;
10125                            to_insert = &clipboard_text[start_offset..end_offset];
10126                            entire_line = clipboard_selection.is_entire_line;
10127                            start_offset = end_offset + 1;
10128                            original_indent_column = Some(clipboard_selection.first_line_indent);
10129                        } else {
10130                            to_insert = clipboard_text.as_str();
10131                            entire_line = all_selections_were_entire_line;
10132                            original_indent_column = first_selection_indent_column
10133                        }
10134
10135                        // If the corresponding selection was empty when this slice of the
10136                        // clipboard text was written, then the entire line containing the
10137                        // selection was copied. If this selection is also currently empty,
10138                        // then paste the line before the current line of the buffer.
10139                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
10140                            let column = selection.start.to_point(&snapshot).column as usize;
10141                            let line_start = selection.start - column;
10142                            line_start..line_start
10143                        } else {
10144                            selection.range()
10145                        };
10146
10147                        edits.push((range, to_insert));
10148                        original_indent_columns.push(original_indent_column);
10149                    }
10150                    drop(snapshot);
10151
10152                    buffer.edit(
10153                        edits,
10154                        if auto_indent_on_paste {
10155                            Some(AutoindentMode::Block {
10156                                original_indent_columns,
10157                            })
10158                        } else {
10159                            None
10160                        },
10161                        cx,
10162                    );
10163                });
10164
10165                let selections = this.selections.all::<usize>(cx);
10166                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10167                    s.select(selections)
10168                });
10169            } else {
10170                this.insert(&clipboard_text, window, cx);
10171            }
10172        });
10173    }
10174
10175    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10176        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10177        if let Some(item) = cx.read_from_clipboard() {
10178            let entries = item.entries();
10179
10180            match entries.first() {
10181                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10182                // of all the pasted entries.
10183                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10184                    .do_paste(
10185                        clipboard_string.text(),
10186                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10187                        true,
10188                        window,
10189                        cx,
10190                    ),
10191                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10192            }
10193        }
10194    }
10195
10196    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10197        if self.read_only(cx) {
10198            return;
10199        }
10200
10201        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10202
10203        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10204            if let Some((selections, _)) =
10205                self.selection_history.transaction(transaction_id).cloned()
10206            {
10207                self.change_selections(None, window, cx, |s| {
10208                    s.select_anchors(selections.to_vec());
10209                });
10210            } else {
10211                log::error!(
10212                    "No entry in selection_history found for undo. \
10213                     This may correspond to a bug where undo does not update the selection. \
10214                     If this is occurring, please add details to \
10215                     https://github.com/zed-industries/zed/issues/22692"
10216                );
10217            }
10218            self.request_autoscroll(Autoscroll::fit(), cx);
10219            self.unmark_text(window, cx);
10220            self.refresh_inline_completion(true, false, window, cx);
10221            cx.emit(EditorEvent::Edited { transaction_id });
10222            cx.emit(EditorEvent::TransactionUndone { transaction_id });
10223        }
10224    }
10225
10226    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10227        if self.read_only(cx) {
10228            return;
10229        }
10230
10231        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10232
10233        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10234            if let Some((_, Some(selections))) =
10235                self.selection_history.transaction(transaction_id).cloned()
10236            {
10237                self.change_selections(None, window, cx, |s| {
10238                    s.select_anchors(selections.to_vec());
10239                });
10240            } else {
10241                log::error!(
10242                    "No entry in selection_history found for redo. \
10243                     This may correspond to a bug where undo does not update the selection. \
10244                     If this is occurring, please add details to \
10245                     https://github.com/zed-industries/zed/issues/22692"
10246                );
10247            }
10248            self.request_autoscroll(Autoscroll::fit(), cx);
10249            self.unmark_text(window, cx);
10250            self.refresh_inline_completion(true, false, window, cx);
10251            cx.emit(EditorEvent::Edited { transaction_id });
10252        }
10253    }
10254
10255    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10256        self.buffer
10257            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10258    }
10259
10260    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10261        self.buffer
10262            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10263    }
10264
10265    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10266        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10267        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10268            s.move_with(|map, selection| {
10269                let cursor = if selection.is_empty() {
10270                    movement::left(map, selection.start)
10271                } else {
10272                    selection.start
10273                };
10274                selection.collapse_to(cursor, SelectionGoal::None);
10275            });
10276        })
10277    }
10278
10279    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10280        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10281        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10282            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10283        })
10284    }
10285
10286    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10287        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10288        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10289            s.move_with(|map, selection| {
10290                let cursor = if selection.is_empty() {
10291                    movement::right(map, selection.end)
10292                } else {
10293                    selection.end
10294                };
10295                selection.collapse_to(cursor, SelectionGoal::None)
10296            });
10297        })
10298    }
10299
10300    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10301        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10302        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10303            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10304        })
10305    }
10306
10307    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10308        if self.take_rename(true, window, cx).is_some() {
10309            return;
10310        }
10311
10312        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10313            cx.propagate();
10314            return;
10315        }
10316
10317        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10318
10319        let text_layout_details = &self.text_layout_details(window);
10320        let selection_count = self.selections.count();
10321        let first_selection = self.selections.first_anchor();
10322
10323        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10324            s.move_with(|map, selection| {
10325                if !selection.is_empty() {
10326                    selection.goal = SelectionGoal::None;
10327                }
10328                let (cursor, goal) = movement::up(
10329                    map,
10330                    selection.start,
10331                    selection.goal,
10332                    false,
10333                    text_layout_details,
10334                );
10335                selection.collapse_to(cursor, goal);
10336            });
10337        });
10338
10339        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10340        {
10341            cx.propagate();
10342        }
10343    }
10344
10345    pub fn move_up_by_lines(
10346        &mut self,
10347        action: &MoveUpByLines,
10348        window: &mut Window,
10349        cx: &mut Context<Self>,
10350    ) {
10351        if self.take_rename(true, window, cx).is_some() {
10352            return;
10353        }
10354
10355        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10356            cx.propagate();
10357            return;
10358        }
10359
10360        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10361
10362        let text_layout_details = &self.text_layout_details(window);
10363
10364        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10365            s.move_with(|map, selection| {
10366                if !selection.is_empty() {
10367                    selection.goal = SelectionGoal::None;
10368                }
10369                let (cursor, goal) = movement::up_by_rows(
10370                    map,
10371                    selection.start,
10372                    action.lines,
10373                    selection.goal,
10374                    false,
10375                    text_layout_details,
10376                );
10377                selection.collapse_to(cursor, goal);
10378            });
10379        })
10380    }
10381
10382    pub fn move_down_by_lines(
10383        &mut self,
10384        action: &MoveDownByLines,
10385        window: &mut Window,
10386        cx: &mut Context<Self>,
10387    ) {
10388        if self.take_rename(true, window, cx).is_some() {
10389            return;
10390        }
10391
10392        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10393            cx.propagate();
10394            return;
10395        }
10396
10397        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10398
10399        let text_layout_details = &self.text_layout_details(window);
10400
10401        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10402            s.move_with(|map, selection| {
10403                if !selection.is_empty() {
10404                    selection.goal = SelectionGoal::None;
10405                }
10406                let (cursor, goal) = movement::down_by_rows(
10407                    map,
10408                    selection.start,
10409                    action.lines,
10410                    selection.goal,
10411                    false,
10412                    text_layout_details,
10413                );
10414                selection.collapse_to(cursor, goal);
10415            });
10416        })
10417    }
10418
10419    pub fn select_down_by_lines(
10420        &mut self,
10421        action: &SelectDownByLines,
10422        window: &mut Window,
10423        cx: &mut Context<Self>,
10424    ) {
10425        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10426        let text_layout_details = &self.text_layout_details(window);
10427        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10428            s.move_heads_with(|map, head, goal| {
10429                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10430            })
10431        })
10432    }
10433
10434    pub fn select_up_by_lines(
10435        &mut self,
10436        action: &SelectUpByLines,
10437        window: &mut Window,
10438        cx: &mut Context<Self>,
10439    ) {
10440        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10441        let text_layout_details = &self.text_layout_details(window);
10442        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10443            s.move_heads_with(|map, head, goal| {
10444                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10445            })
10446        })
10447    }
10448
10449    pub fn select_page_up(
10450        &mut self,
10451        _: &SelectPageUp,
10452        window: &mut Window,
10453        cx: &mut Context<Self>,
10454    ) {
10455        let Some(row_count) = self.visible_row_count() else {
10456            return;
10457        };
10458
10459        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10460
10461        let text_layout_details = &self.text_layout_details(window);
10462
10463        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10464            s.move_heads_with(|map, head, goal| {
10465                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10466            })
10467        })
10468    }
10469
10470    pub fn move_page_up(
10471        &mut self,
10472        action: &MovePageUp,
10473        window: &mut Window,
10474        cx: &mut Context<Self>,
10475    ) {
10476        if self.take_rename(true, window, cx).is_some() {
10477            return;
10478        }
10479
10480        if self
10481            .context_menu
10482            .borrow_mut()
10483            .as_mut()
10484            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10485            .unwrap_or(false)
10486        {
10487            return;
10488        }
10489
10490        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10491            cx.propagate();
10492            return;
10493        }
10494
10495        let Some(row_count) = self.visible_row_count() else {
10496            return;
10497        };
10498
10499        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10500
10501        let autoscroll = if action.center_cursor {
10502            Autoscroll::center()
10503        } else {
10504            Autoscroll::fit()
10505        };
10506
10507        let text_layout_details = &self.text_layout_details(window);
10508
10509        self.change_selections(Some(autoscroll), window, cx, |s| {
10510            s.move_with(|map, selection| {
10511                if !selection.is_empty() {
10512                    selection.goal = SelectionGoal::None;
10513                }
10514                let (cursor, goal) = movement::up_by_rows(
10515                    map,
10516                    selection.end,
10517                    row_count,
10518                    selection.goal,
10519                    false,
10520                    text_layout_details,
10521                );
10522                selection.collapse_to(cursor, goal);
10523            });
10524        });
10525    }
10526
10527    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10528        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10529        let text_layout_details = &self.text_layout_details(window);
10530        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10531            s.move_heads_with(|map, head, goal| {
10532                movement::up(map, head, goal, false, text_layout_details)
10533            })
10534        })
10535    }
10536
10537    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10538        self.take_rename(true, window, cx);
10539
10540        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10541            cx.propagate();
10542            return;
10543        }
10544
10545        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10546
10547        let text_layout_details = &self.text_layout_details(window);
10548        let selection_count = self.selections.count();
10549        let first_selection = self.selections.first_anchor();
10550
10551        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10552            s.move_with(|map, selection| {
10553                if !selection.is_empty() {
10554                    selection.goal = SelectionGoal::None;
10555                }
10556                let (cursor, goal) = movement::down(
10557                    map,
10558                    selection.end,
10559                    selection.goal,
10560                    false,
10561                    text_layout_details,
10562                );
10563                selection.collapse_to(cursor, goal);
10564            });
10565        });
10566
10567        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10568        {
10569            cx.propagate();
10570        }
10571    }
10572
10573    pub fn select_page_down(
10574        &mut self,
10575        _: &SelectPageDown,
10576        window: &mut Window,
10577        cx: &mut Context<Self>,
10578    ) {
10579        let Some(row_count) = self.visible_row_count() else {
10580            return;
10581        };
10582
10583        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10584
10585        let text_layout_details = &self.text_layout_details(window);
10586
10587        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10588            s.move_heads_with(|map, head, goal| {
10589                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10590            })
10591        })
10592    }
10593
10594    pub fn move_page_down(
10595        &mut self,
10596        action: &MovePageDown,
10597        window: &mut Window,
10598        cx: &mut Context<Self>,
10599    ) {
10600        if self.take_rename(true, window, cx).is_some() {
10601            return;
10602        }
10603
10604        if self
10605            .context_menu
10606            .borrow_mut()
10607            .as_mut()
10608            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10609            .unwrap_or(false)
10610        {
10611            return;
10612        }
10613
10614        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10615            cx.propagate();
10616            return;
10617        }
10618
10619        let Some(row_count) = self.visible_row_count() else {
10620            return;
10621        };
10622
10623        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10624
10625        let autoscroll = if action.center_cursor {
10626            Autoscroll::center()
10627        } else {
10628            Autoscroll::fit()
10629        };
10630
10631        let text_layout_details = &self.text_layout_details(window);
10632        self.change_selections(Some(autoscroll), window, cx, |s| {
10633            s.move_with(|map, selection| {
10634                if !selection.is_empty() {
10635                    selection.goal = SelectionGoal::None;
10636                }
10637                let (cursor, goal) = movement::down_by_rows(
10638                    map,
10639                    selection.end,
10640                    row_count,
10641                    selection.goal,
10642                    false,
10643                    text_layout_details,
10644                );
10645                selection.collapse_to(cursor, goal);
10646            });
10647        });
10648    }
10649
10650    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10651        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10652        let text_layout_details = &self.text_layout_details(window);
10653        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10654            s.move_heads_with(|map, head, goal| {
10655                movement::down(map, head, goal, false, text_layout_details)
10656            })
10657        });
10658    }
10659
10660    pub fn context_menu_first(
10661        &mut self,
10662        _: &ContextMenuFirst,
10663        _window: &mut Window,
10664        cx: &mut Context<Self>,
10665    ) {
10666        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10667            context_menu.select_first(self.completion_provider.as_deref(), cx);
10668        }
10669    }
10670
10671    pub fn context_menu_prev(
10672        &mut self,
10673        _: &ContextMenuPrevious,
10674        _window: &mut Window,
10675        cx: &mut Context<Self>,
10676    ) {
10677        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10678            context_menu.select_prev(self.completion_provider.as_deref(), cx);
10679        }
10680    }
10681
10682    pub fn context_menu_next(
10683        &mut self,
10684        _: &ContextMenuNext,
10685        _window: &mut Window,
10686        cx: &mut Context<Self>,
10687    ) {
10688        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10689            context_menu.select_next(self.completion_provider.as_deref(), cx);
10690        }
10691    }
10692
10693    pub fn context_menu_last(
10694        &mut self,
10695        _: &ContextMenuLast,
10696        _window: &mut Window,
10697        cx: &mut Context<Self>,
10698    ) {
10699        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10700            context_menu.select_last(self.completion_provider.as_deref(), cx);
10701        }
10702    }
10703
10704    pub fn move_to_previous_word_start(
10705        &mut self,
10706        _: &MoveToPreviousWordStart,
10707        window: &mut Window,
10708        cx: &mut Context<Self>,
10709    ) {
10710        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10711        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10712            s.move_cursors_with(|map, head, _| {
10713                (
10714                    movement::previous_word_start(map, head),
10715                    SelectionGoal::None,
10716                )
10717            });
10718        })
10719    }
10720
10721    pub fn move_to_previous_subword_start(
10722        &mut self,
10723        _: &MoveToPreviousSubwordStart,
10724        window: &mut Window,
10725        cx: &mut Context<Self>,
10726    ) {
10727        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10728        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10729            s.move_cursors_with(|map, head, _| {
10730                (
10731                    movement::previous_subword_start(map, head),
10732                    SelectionGoal::None,
10733                )
10734            });
10735        })
10736    }
10737
10738    pub fn select_to_previous_word_start(
10739        &mut self,
10740        _: &SelectToPreviousWordStart,
10741        window: &mut Window,
10742        cx: &mut Context<Self>,
10743    ) {
10744        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10745        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10746            s.move_heads_with(|map, head, _| {
10747                (
10748                    movement::previous_word_start(map, head),
10749                    SelectionGoal::None,
10750                )
10751            });
10752        })
10753    }
10754
10755    pub fn select_to_previous_subword_start(
10756        &mut self,
10757        _: &SelectToPreviousSubwordStart,
10758        window: &mut Window,
10759        cx: &mut Context<Self>,
10760    ) {
10761        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10762        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10763            s.move_heads_with(|map, head, _| {
10764                (
10765                    movement::previous_subword_start(map, head),
10766                    SelectionGoal::None,
10767                )
10768            });
10769        })
10770    }
10771
10772    pub fn delete_to_previous_word_start(
10773        &mut self,
10774        action: &DeleteToPreviousWordStart,
10775        window: &mut Window,
10776        cx: &mut Context<Self>,
10777    ) {
10778        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10779        self.transact(window, cx, |this, window, cx| {
10780            this.select_autoclose_pair(window, cx);
10781            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10782                s.move_with(|map, selection| {
10783                    if selection.is_empty() {
10784                        let cursor = if action.ignore_newlines {
10785                            movement::previous_word_start(map, selection.head())
10786                        } else {
10787                            movement::previous_word_start_or_newline(map, selection.head())
10788                        };
10789                        selection.set_head(cursor, SelectionGoal::None);
10790                    }
10791                });
10792            });
10793            this.insert("", window, cx);
10794        });
10795    }
10796
10797    pub fn delete_to_previous_subword_start(
10798        &mut self,
10799        _: &DeleteToPreviousSubwordStart,
10800        window: &mut Window,
10801        cx: &mut Context<Self>,
10802    ) {
10803        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10804        self.transact(window, cx, |this, window, cx| {
10805            this.select_autoclose_pair(window, cx);
10806            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10807                s.move_with(|map, selection| {
10808                    if selection.is_empty() {
10809                        let cursor = movement::previous_subword_start(map, selection.head());
10810                        selection.set_head(cursor, SelectionGoal::None);
10811                    }
10812                });
10813            });
10814            this.insert("", window, cx);
10815        });
10816    }
10817
10818    pub fn move_to_next_word_end(
10819        &mut self,
10820        _: &MoveToNextWordEnd,
10821        window: &mut Window,
10822        cx: &mut Context<Self>,
10823    ) {
10824        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10825        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10826            s.move_cursors_with(|map, head, _| {
10827                (movement::next_word_end(map, head), SelectionGoal::None)
10828            });
10829        })
10830    }
10831
10832    pub fn move_to_next_subword_end(
10833        &mut self,
10834        _: &MoveToNextSubwordEnd,
10835        window: &mut Window,
10836        cx: &mut Context<Self>,
10837    ) {
10838        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10839        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10840            s.move_cursors_with(|map, head, _| {
10841                (movement::next_subword_end(map, head), SelectionGoal::None)
10842            });
10843        })
10844    }
10845
10846    pub fn select_to_next_word_end(
10847        &mut self,
10848        _: &SelectToNextWordEnd,
10849        window: &mut Window,
10850        cx: &mut Context<Self>,
10851    ) {
10852        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10853        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10854            s.move_heads_with(|map, head, _| {
10855                (movement::next_word_end(map, head), SelectionGoal::None)
10856            });
10857        })
10858    }
10859
10860    pub fn select_to_next_subword_end(
10861        &mut self,
10862        _: &SelectToNextSubwordEnd,
10863        window: &mut Window,
10864        cx: &mut Context<Self>,
10865    ) {
10866        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10867        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10868            s.move_heads_with(|map, head, _| {
10869                (movement::next_subword_end(map, head), SelectionGoal::None)
10870            });
10871        })
10872    }
10873
10874    pub fn delete_to_next_word_end(
10875        &mut self,
10876        action: &DeleteToNextWordEnd,
10877        window: &mut Window,
10878        cx: &mut Context<Self>,
10879    ) {
10880        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10881        self.transact(window, cx, |this, window, cx| {
10882            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10883                s.move_with(|map, selection| {
10884                    if selection.is_empty() {
10885                        let cursor = if action.ignore_newlines {
10886                            movement::next_word_end(map, selection.head())
10887                        } else {
10888                            movement::next_word_end_or_newline(map, selection.head())
10889                        };
10890                        selection.set_head(cursor, SelectionGoal::None);
10891                    }
10892                });
10893            });
10894            this.insert("", window, cx);
10895        });
10896    }
10897
10898    pub fn delete_to_next_subword_end(
10899        &mut self,
10900        _: &DeleteToNextSubwordEnd,
10901        window: &mut Window,
10902        cx: &mut Context<Self>,
10903    ) {
10904        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10905        self.transact(window, cx, |this, window, cx| {
10906            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10907                s.move_with(|map, selection| {
10908                    if selection.is_empty() {
10909                        let cursor = movement::next_subword_end(map, selection.head());
10910                        selection.set_head(cursor, SelectionGoal::None);
10911                    }
10912                });
10913            });
10914            this.insert("", window, cx);
10915        });
10916    }
10917
10918    pub fn move_to_beginning_of_line(
10919        &mut self,
10920        action: &MoveToBeginningOfLine,
10921        window: &mut Window,
10922        cx: &mut Context<Self>,
10923    ) {
10924        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10925        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10926            s.move_cursors_with(|map, head, _| {
10927                (
10928                    movement::indented_line_beginning(
10929                        map,
10930                        head,
10931                        action.stop_at_soft_wraps,
10932                        action.stop_at_indent,
10933                    ),
10934                    SelectionGoal::None,
10935                )
10936            });
10937        })
10938    }
10939
10940    pub fn select_to_beginning_of_line(
10941        &mut self,
10942        action: &SelectToBeginningOfLine,
10943        window: &mut Window,
10944        cx: &mut Context<Self>,
10945    ) {
10946        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10947        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10948            s.move_heads_with(|map, head, _| {
10949                (
10950                    movement::indented_line_beginning(
10951                        map,
10952                        head,
10953                        action.stop_at_soft_wraps,
10954                        action.stop_at_indent,
10955                    ),
10956                    SelectionGoal::None,
10957                )
10958            });
10959        });
10960    }
10961
10962    pub fn delete_to_beginning_of_line(
10963        &mut self,
10964        action: &DeleteToBeginningOfLine,
10965        window: &mut Window,
10966        cx: &mut Context<Self>,
10967    ) {
10968        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10969        self.transact(window, cx, |this, window, cx| {
10970            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10971                s.move_with(|_, selection| {
10972                    selection.reversed = true;
10973                });
10974            });
10975
10976            this.select_to_beginning_of_line(
10977                &SelectToBeginningOfLine {
10978                    stop_at_soft_wraps: false,
10979                    stop_at_indent: action.stop_at_indent,
10980                },
10981                window,
10982                cx,
10983            );
10984            this.backspace(&Backspace, window, cx);
10985        });
10986    }
10987
10988    pub fn move_to_end_of_line(
10989        &mut self,
10990        action: &MoveToEndOfLine,
10991        window: &mut Window,
10992        cx: &mut Context<Self>,
10993    ) {
10994        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10995        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10996            s.move_cursors_with(|map, head, _| {
10997                (
10998                    movement::line_end(map, head, action.stop_at_soft_wraps),
10999                    SelectionGoal::None,
11000                )
11001            });
11002        })
11003    }
11004
11005    pub fn select_to_end_of_line(
11006        &mut self,
11007        action: &SelectToEndOfLine,
11008        window: &mut Window,
11009        cx: &mut Context<Self>,
11010    ) {
11011        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11012        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11013            s.move_heads_with(|map, head, _| {
11014                (
11015                    movement::line_end(map, head, action.stop_at_soft_wraps),
11016                    SelectionGoal::None,
11017                )
11018            });
11019        })
11020    }
11021
11022    pub fn delete_to_end_of_line(
11023        &mut self,
11024        _: &DeleteToEndOfLine,
11025        window: &mut Window,
11026        cx: &mut Context<Self>,
11027    ) {
11028        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11029        self.transact(window, cx, |this, window, cx| {
11030            this.select_to_end_of_line(
11031                &SelectToEndOfLine {
11032                    stop_at_soft_wraps: false,
11033                },
11034                window,
11035                cx,
11036            );
11037            this.delete(&Delete, window, cx);
11038        });
11039    }
11040
11041    pub fn cut_to_end_of_line(
11042        &mut self,
11043        _: &CutToEndOfLine,
11044        window: &mut Window,
11045        cx: &mut Context<Self>,
11046    ) {
11047        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11048        self.transact(window, cx, |this, window, cx| {
11049            this.select_to_end_of_line(
11050                &SelectToEndOfLine {
11051                    stop_at_soft_wraps: false,
11052                },
11053                window,
11054                cx,
11055            );
11056            this.cut(&Cut, window, cx);
11057        });
11058    }
11059
11060    pub fn move_to_start_of_paragraph(
11061        &mut self,
11062        _: &MoveToStartOfParagraph,
11063        window: &mut Window,
11064        cx: &mut Context<Self>,
11065    ) {
11066        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11067            cx.propagate();
11068            return;
11069        }
11070        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11071        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11072            s.move_with(|map, selection| {
11073                selection.collapse_to(
11074                    movement::start_of_paragraph(map, selection.head(), 1),
11075                    SelectionGoal::None,
11076                )
11077            });
11078        })
11079    }
11080
11081    pub fn move_to_end_of_paragraph(
11082        &mut self,
11083        _: &MoveToEndOfParagraph,
11084        window: &mut Window,
11085        cx: &mut Context<Self>,
11086    ) {
11087        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11088            cx.propagate();
11089            return;
11090        }
11091        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11092        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11093            s.move_with(|map, selection| {
11094                selection.collapse_to(
11095                    movement::end_of_paragraph(map, selection.head(), 1),
11096                    SelectionGoal::None,
11097                )
11098            });
11099        })
11100    }
11101
11102    pub fn select_to_start_of_paragraph(
11103        &mut self,
11104        _: &SelectToStartOfParagraph,
11105        window: &mut Window,
11106        cx: &mut Context<Self>,
11107    ) {
11108        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11109            cx.propagate();
11110            return;
11111        }
11112        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11113        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11114            s.move_heads_with(|map, head, _| {
11115                (
11116                    movement::start_of_paragraph(map, head, 1),
11117                    SelectionGoal::None,
11118                )
11119            });
11120        })
11121    }
11122
11123    pub fn select_to_end_of_paragraph(
11124        &mut self,
11125        _: &SelectToEndOfParagraph,
11126        window: &mut Window,
11127        cx: &mut Context<Self>,
11128    ) {
11129        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11130            cx.propagate();
11131            return;
11132        }
11133        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11134        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11135            s.move_heads_with(|map, head, _| {
11136                (
11137                    movement::end_of_paragraph(map, head, 1),
11138                    SelectionGoal::None,
11139                )
11140            });
11141        })
11142    }
11143
11144    pub fn move_to_start_of_excerpt(
11145        &mut self,
11146        _: &MoveToStartOfExcerpt,
11147        window: &mut Window,
11148        cx: &mut Context<Self>,
11149    ) {
11150        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11151            cx.propagate();
11152            return;
11153        }
11154        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11155        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11156            s.move_with(|map, selection| {
11157                selection.collapse_to(
11158                    movement::start_of_excerpt(
11159                        map,
11160                        selection.head(),
11161                        workspace::searchable::Direction::Prev,
11162                    ),
11163                    SelectionGoal::None,
11164                )
11165            });
11166        })
11167    }
11168
11169    pub fn move_to_start_of_next_excerpt(
11170        &mut self,
11171        _: &MoveToStartOfNextExcerpt,
11172        window: &mut Window,
11173        cx: &mut Context<Self>,
11174    ) {
11175        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11176            cx.propagate();
11177            return;
11178        }
11179
11180        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11181            s.move_with(|map, selection| {
11182                selection.collapse_to(
11183                    movement::start_of_excerpt(
11184                        map,
11185                        selection.head(),
11186                        workspace::searchable::Direction::Next,
11187                    ),
11188                    SelectionGoal::None,
11189                )
11190            });
11191        })
11192    }
11193
11194    pub fn move_to_end_of_excerpt(
11195        &mut self,
11196        _: &MoveToEndOfExcerpt,
11197        window: &mut Window,
11198        cx: &mut Context<Self>,
11199    ) {
11200        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11201            cx.propagate();
11202            return;
11203        }
11204        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11205        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11206            s.move_with(|map, selection| {
11207                selection.collapse_to(
11208                    movement::end_of_excerpt(
11209                        map,
11210                        selection.head(),
11211                        workspace::searchable::Direction::Next,
11212                    ),
11213                    SelectionGoal::None,
11214                )
11215            });
11216        })
11217    }
11218
11219    pub fn move_to_end_of_previous_excerpt(
11220        &mut self,
11221        _: &MoveToEndOfPreviousExcerpt,
11222        window: &mut Window,
11223        cx: &mut Context<Self>,
11224    ) {
11225        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11226            cx.propagate();
11227            return;
11228        }
11229        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11230        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11231            s.move_with(|map, selection| {
11232                selection.collapse_to(
11233                    movement::end_of_excerpt(
11234                        map,
11235                        selection.head(),
11236                        workspace::searchable::Direction::Prev,
11237                    ),
11238                    SelectionGoal::None,
11239                )
11240            });
11241        })
11242    }
11243
11244    pub fn select_to_start_of_excerpt(
11245        &mut self,
11246        _: &SelectToStartOfExcerpt,
11247        window: &mut Window,
11248        cx: &mut Context<Self>,
11249    ) {
11250        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11251            cx.propagate();
11252            return;
11253        }
11254        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11255        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11256            s.move_heads_with(|map, head, _| {
11257                (
11258                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11259                    SelectionGoal::None,
11260                )
11261            });
11262        })
11263    }
11264
11265    pub fn select_to_start_of_next_excerpt(
11266        &mut self,
11267        _: &SelectToStartOfNextExcerpt,
11268        window: &mut Window,
11269        cx: &mut Context<Self>,
11270    ) {
11271        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11272            cx.propagate();
11273            return;
11274        }
11275        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11276        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11277            s.move_heads_with(|map, head, _| {
11278                (
11279                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11280                    SelectionGoal::None,
11281                )
11282            });
11283        })
11284    }
11285
11286    pub fn select_to_end_of_excerpt(
11287        &mut self,
11288        _: &SelectToEndOfExcerpt,
11289        window: &mut Window,
11290        cx: &mut Context<Self>,
11291    ) {
11292        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11293            cx.propagate();
11294            return;
11295        }
11296        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11297        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11298            s.move_heads_with(|map, head, _| {
11299                (
11300                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11301                    SelectionGoal::None,
11302                )
11303            });
11304        })
11305    }
11306
11307    pub fn select_to_end_of_previous_excerpt(
11308        &mut self,
11309        _: &SelectToEndOfPreviousExcerpt,
11310        window: &mut Window,
11311        cx: &mut Context<Self>,
11312    ) {
11313        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11314            cx.propagate();
11315            return;
11316        }
11317        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11318        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11319            s.move_heads_with(|map, head, _| {
11320                (
11321                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11322                    SelectionGoal::None,
11323                )
11324            });
11325        })
11326    }
11327
11328    pub fn move_to_beginning(
11329        &mut self,
11330        _: &MoveToBeginning,
11331        window: &mut Window,
11332        cx: &mut Context<Self>,
11333    ) {
11334        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11335            cx.propagate();
11336            return;
11337        }
11338        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11339        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11340            s.select_ranges(vec![0..0]);
11341        });
11342    }
11343
11344    pub fn select_to_beginning(
11345        &mut self,
11346        _: &SelectToBeginning,
11347        window: &mut Window,
11348        cx: &mut Context<Self>,
11349    ) {
11350        let mut selection = self.selections.last::<Point>(cx);
11351        selection.set_head(Point::zero(), SelectionGoal::None);
11352        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11353        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11354            s.select(vec![selection]);
11355        });
11356    }
11357
11358    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11359        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11360            cx.propagate();
11361            return;
11362        }
11363        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11364        let cursor = self.buffer.read(cx).read(cx).len();
11365        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11366            s.select_ranges(vec![cursor..cursor])
11367        });
11368    }
11369
11370    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11371        self.nav_history = nav_history;
11372    }
11373
11374    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11375        self.nav_history.as_ref()
11376    }
11377
11378    pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11379        self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11380    }
11381
11382    fn push_to_nav_history(
11383        &mut self,
11384        cursor_anchor: Anchor,
11385        new_position: Option<Point>,
11386        is_deactivate: bool,
11387        cx: &mut Context<Self>,
11388    ) {
11389        if let Some(nav_history) = self.nav_history.as_mut() {
11390            let buffer = self.buffer.read(cx).read(cx);
11391            let cursor_position = cursor_anchor.to_point(&buffer);
11392            let scroll_state = self.scroll_manager.anchor();
11393            let scroll_top_row = scroll_state.top_row(&buffer);
11394            drop(buffer);
11395
11396            if let Some(new_position) = new_position {
11397                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11398                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11399                    return;
11400                }
11401            }
11402
11403            nav_history.push(
11404                Some(NavigationData {
11405                    cursor_anchor,
11406                    cursor_position,
11407                    scroll_anchor: scroll_state,
11408                    scroll_top_row,
11409                }),
11410                cx,
11411            );
11412            cx.emit(EditorEvent::PushedToNavHistory {
11413                anchor: cursor_anchor,
11414                is_deactivate,
11415            })
11416        }
11417    }
11418
11419    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11420        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11421        let buffer = self.buffer.read(cx).snapshot(cx);
11422        let mut selection = self.selections.first::<usize>(cx);
11423        selection.set_head(buffer.len(), SelectionGoal::None);
11424        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11425            s.select(vec![selection]);
11426        });
11427    }
11428
11429    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11430        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11431        let end = self.buffer.read(cx).read(cx).len();
11432        self.change_selections(None, window, cx, |s| {
11433            s.select_ranges(vec![0..end]);
11434        });
11435    }
11436
11437    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11438        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11439        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11440        let mut selections = self.selections.all::<Point>(cx);
11441        let max_point = display_map.buffer_snapshot.max_point();
11442        for selection in &mut selections {
11443            let rows = selection.spanned_rows(true, &display_map);
11444            selection.start = Point::new(rows.start.0, 0);
11445            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11446            selection.reversed = false;
11447        }
11448        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11449            s.select(selections);
11450        });
11451    }
11452
11453    pub fn split_selection_into_lines(
11454        &mut self,
11455        _: &SplitSelectionIntoLines,
11456        window: &mut Window,
11457        cx: &mut Context<Self>,
11458    ) {
11459        let selections = self
11460            .selections
11461            .all::<Point>(cx)
11462            .into_iter()
11463            .map(|selection| selection.start..selection.end)
11464            .collect::<Vec<_>>();
11465        self.unfold_ranges(&selections, true, true, cx);
11466
11467        let mut new_selection_ranges = Vec::new();
11468        {
11469            let buffer = self.buffer.read(cx).read(cx);
11470            for selection in selections {
11471                for row in selection.start.row..selection.end.row {
11472                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11473                    new_selection_ranges.push(cursor..cursor);
11474                }
11475
11476                let is_multiline_selection = selection.start.row != selection.end.row;
11477                // Don't insert last one if it's a multi-line selection ending at the start of a line,
11478                // so this action feels more ergonomic when paired with other selection operations
11479                let should_skip_last = is_multiline_selection && selection.end.column == 0;
11480                if !should_skip_last {
11481                    new_selection_ranges.push(selection.end..selection.end);
11482                }
11483            }
11484        }
11485        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11486            s.select_ranges(new_selection_ranges);
11487        });
11488    }
11489
11490    pub fn add_selection_above(
11491        &mut self,
11492        _: &AddSelectionAbove,
11493        window: &mut Window,
11494        cx: &mut Context<Self>,
11495    ) {
11496        self.add_selection(true, window, cx);
11497    }
11498
11499    pub fn add_selection_below(
11500        &mut self,
11501        _: &AddSelectionBelow,
11502        window: &mut Window,
11503        cx: &mut Context<Self>,
11504    ) {
11505        self.add_selection(false, window, cx);
11506    }
11507
11508    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11509        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11510
11511        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11512        let mut selections = self.selections.all::<Point>(cx);
11513        let text_layout_details = self.text_layout_details(window);
11514        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11515            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11516            let range = oldest_selection.display_range(&display_map).sorted();
11517
11518            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11519            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11520            let positions = start_x.min(end_x)..start_x.max(end_x);
11521
11522            selections.clear();
11523            let mut stack = Vec::new();
11524            for row in range.start.row().0..=range.end.row().0 {
11525                if let Some(selection) = self.selections.build_columnar_selection(
11526                    &display_map,
11527                    DisplayRow(row),
11528                    &positions,
11529                    oldest_selection.reversed,
11530                    &text_layout_details,
11531                ) {
11532                    stack.push(selection.id);
11533                    selections.push(selection);
11534                }
11535            }
11536
11537            if above {
11538                stack.reverse();
11539            }
11540
11541            AddSelectionsState { above, stack }
11542        });
11543
11544        let last_added_selection = *state.stack.last().unwrap();
11545        let mut new_selections = Vec::new();
11546        if above == state.above {
11547            let end_row = if above {
11548                DisplayRow(0)
11549            } else {
11550                display_map.max_point().row()
11551            };
11552
11553            'outer: for selection in selections {
11554                if selection.id == last_added_selection {
11555                    let range = selection.display_range(&display_map).sorted();
11556                    debug_assert_eq!(range.start.row(), range.end.row());
11557                    let mut row = range.start.row();
11558                    let positions =
11559                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11560                            px(start)..px(end)
11561                        } else {
11562                            let start_x =
11563                                display_map.x_for_display_point(range.start, &text_layout_details);
11564                            let end_x =
11565                                display_map.x_for_display_point(range.end, &text_layout_details);
11566                            start_x.min(end_x)..start_x.max(end_x)
11567                        };
11568
11569                    while row != end_row {
11570                        if above {
11571                            row.0 -= 1;
11572                        } else {
11573                            row.0 += 1;
11574                        }
11575
11576                        if let Some(new_selection) = self.selections.build_columnar_selection(
11577                            &display_map,
11578                            row,
11579                            &positions,
11580                            selection.reversed,
11581                            &text_layout_details,
11582                        ) {
11583                            state.stack.push(new_selection.id);
11584                            if above {
11585                                new_selections.push(new_selection);
11586                                new_selections.push(selection);
11587                            } else {
11588                                new_selections.push(selection);
11589                                new_selections.push(new_selection);
11590                            }
11591
11592                            continue 'outer;
11593                        }
11594                    }
11595                }
11596
11597                new_selections.push(selection);
11598            }
11599        } else {
11600            new_selections = selections;
11601            new_selections.retain(|s| s.id != last_added_selection);
11602            state.stack.pop();
11603        }
11604
11605        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11606            s.select(new_selections);
11607        });
11608        if state.stack.len() > 1 {
11609            self.add_selections_state = Some(state);
11610        }
11611    }
11612
11613    pub fn select_next_match_internal(
11614        &mut self,
11615        display_map: &DisplaySnapshot,
11616        replace_newest: bool,
11617        autoscroll: Option<Autoscroll>,
11618        window: &mut Window,
11619        cx: &mut Context<Self>,
11620    ) -> Result<()> {
11621        fn select_next_match_ranges(
11622            this: &mut Editor,
11623            range: Range<usize>,
11624            replace_newest: bool,
11625            auto_scroll: Option<Autoscroll>,
11626            window: &mut Window,
11627            cx: &mut Context<Editor>,
11628        ) {
11629            this.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
11630            this.change_selections(auto_scroll, window, cx, |s| {
11631                if replace_newest {
11632                    s.delete(s.newest_anchor().id);
11633                }
11634                s.insert_range(range.clone());
11635            });
11636        }
11637
11638        let buffer = &display_map.buffer_snapshot;
11639        let mut selections = self.selections.all::<usize>(cx);
11640        if let Some(mut select_next_state) = self.select_next_state.take() {
11641            let query = &select_next_state.query;
11642            if !select_next_state.done {
11643                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11644                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11645                let mut next_selected_range = None;
11646
11647                let bytes_after_last_selection =
11648                    buffer.bytes_in_range(last_selection.end..buffer.len());
11649                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11650                let query_matches = query
11651                    .stream_find_iter(bytes_after_last_selection)
11652                    .map(|result| (last_selection.end, result))
11653                    .chain(
11654                        query
11655                            .stream_find_iter(bytes_before_first_selection)
11656                            .map(|result| (0, result)),
11657                    );
11658
11659                for (start_offset, query_match) in query_matches {
11660                    let query_match = query_match.unwrap(); // can only fail due to I/O
11661                    let offset_range =
11662                        start_offset + query_match.start()..start_offset + query_match.end();
11663                    let display_range = offset_range.start.to_display_point(display_map)
11664                        ..offset_range.end.to_display_point(display_map);
11665
11666                    if !select_next_state.wordwise
11667                        || (!movement::is_inside_word(display_map, display_range.start)
11668                            && !movement::is_inside_word(display_map, display_range.end))
11669                    {
11670                        // TODO: This is n^2, because we might check all the selections
11671                        if !selections
11672                            .iter()
11673                            .any(|selection| selection.range().overlaps(&offset_range))
11674                        {
11675                            next_selected_range = Some(offset_range);
11676                            break;
11677                        }
11678                    }
11679                }
11680
11681                if let Some(next_selected_range) = next_selected_range {
11682                    select_next_match_ranges(
11683                        self,
11684                        next_selected_range,
11685                        replace_newest,
11686                        autoscroll,
11687                        window,
11688                        cx,
11689                    );
11690                } else {
11691                    select_next_state.done = true;
11692                }
11693            }
11694
11695            self.select_next_state = Some(select_next_state);
11696        } else {
11697            let mut only_carets = true;
11698            let mut same_text_selected = true;
11699            let mut selected_text = None;
11700
11701            let mut selections_iter = selections.iter().peekable();
11702            while let Some(selection) = selections_iter.next() {
11703                if selection.start != selection.end {
11704                    only_carets = false;
11705                }
11706
11707                if same_text_selected {
11708                    if selected_text.is_none() {
11709                        selected_text =
11710                            Some(buffer.text_for_range(selection.range()).collect::<String>());
11711                    }
11712
11713                    if let Some(next_selection) = selections_iter.peek() {
11714                        if next_selection.range().len() == selection.range().len() {
11715                            let next_selected_text = buffer
11716                                .text_for_range(next_selection.range())
11717                                .collect::<String>();
11718                            if Some(next_selected_text) != selected_text {
11719                                same_text_selected = false;
11720                                selected_text = None;
11721                            }
11722                        } else {
11723                            same_text_selected = false;
11724                            selected_text = None;
11725                        }
11726                    }
11727                }
11728            }
11729
11730            if only_carets {
11731                for selection in &mut selections {
11732                    let word_range = movement::surrounding_word(
11733                        display_map,
11734                        selection.start.to_display_point(display_map),
11735                    );
11736                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
11737                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
11738                    selection.goal = SelectionGoal::None;
11739                    selection.reversed = false;
11740                    select_next_match_ranges(
11741                        self,
11742                        selection.start..selection.end,
11743                        replace_newest,
11744                        autoscroll,
11745                        window,
11746                        cx,
11747                    );
11748                }
11749
11750                if selections.len() == 1 {
11751                    let selection = selections
11752                        .last()
11753                        .expect("ensured that there's only one selection");
11754                    let query = buffer
11755                        .text_for_range(selection.start..selection.end)
11756                        .collect::<String>();
11757                    let is_empty = query.is_empty();
11758                    let select_state = SelectNextState {
11759                        query: AhoCorasick::new(&[query])?,
11760                        wordwise: true,
11761                        done: is_empty,
11762                    };
11763                    self.select_next_state = Some(select_state);
11764                } else {
11765                    self.select_next_state = None;
11766                }
11767            } else if let Some(selected_text) = selected_text {
11768                self.select_next_state = Some(SelectNextState {
11769                    query: AhoCorasick::new(&[selected_text])?,
11770                    wordwise: false,
11771                    done: false,
11772                });
11773                self.select_next_match_internal(
11774                    display_map,
11775                    replace_newest,
11776                    autoscroll,
11777                    window,
11778                    cx,
11779                )?;
11780            }
11781        }
11782        Ok(())
11783    }
11784
11785    pub fn select_all_matches(
11786        &mut self,
11787        _action: &SelectAllMatches,
11788        window: &mut Window,
11789        cx: &mut Context<Self>,
11790    ) -> Result<()> {
11791        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11792
11793        self.push_to_selection_history();
11794        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11795
11796        self.select_next_match_internal(&display_map, false, None, window, cx)?;
11797        let Some(select_next_state) = self.select_next_state.as_mut() else {
11798            return Ok(());
11799        };
11800        if select_next_state.done {
11801            return Ok(());
11802        }
11803
11804        let mut new_selections = Vec::new();
11805
11806        let reversed = self.selections.oldest::<usize>(cx).reversed;
11807        let buffer = &display_map.buffer_snapshot;
11808        let query_matches = select_next_state
11809            .query
11810            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11811
11812        for query_match in query_matches.into_iter() {
11813            let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
11814            let offset_range = if reversed {
11815                query_match.end()..query_match.start()
11816            } else {
11817                query_match.start()..query_match.end()
11818            };
11819            let display_range = offset_range.start.to_display_point(&display_map)
11820                ..offset_range.end.to_display_point(&display_map);
11821
11822            if !select_next_state.wordwise
11823                || (!movement::is_inside_word(&display_map, display_range.start)
11824                    && !movement::is_inside_word(&display_map, display_range.end))
11825            {
11826                new_selections.push(offset_range.start..offset_range.end);
11827            }
11828        }
11829
11830        select_next_state.done = true;
11831        self.unfold_ranges(&new_selections.clone(), false, false, cx);
11832        self.change_selections(None, window, cx, |selections| {
11833            selections.select_ranges(new_selections)
11834        });
11835
11836        Ok(())
11837    }
11838
11839    pub fn select_next(
11840        &mut self,
11841        action: &SelectNext,
11842        window: &mut Window,
11843        cx: &mut Context<Self>,
11844    ) -> Result<()> {
11845        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11846        self.push_to_selection_history();
11847        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11848        self.select_next_match_internal(
11849            &display_map,
11850            action.replace_newest,
11851            Some(Autoscroll::newest()),
11852            window,
11853            cx,
11854        )?;
11855        Ok(())
11856    }
11857
11858    pub fn select_previous(
11859        &mut self,
11860        action: &SelectPrevious,
11861        window: &mut Window,
11862        cx: &mut Context<Self>,
11863    ) -> Result<()> {
11864        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11865        self.push_to_selection_history();
11866        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11867        let buffer = &display_map.buffer_snapshot;
11868        let mut selections = self.selections.all::<usize>(cx);
11869        if let Some(mut select_prev_state) = self.select_prev_state.take() {
11870            let query = &select_prev_state.query;
11871            if !select_prev_state.done {
11872                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11873                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11874                let mut next_selected_range = None;
11875                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
11876                let bytes_before_last_selection =
11877                    buffer.reversed_bytes_in_range(0..last_selection.start);
11878                let bytes_after_first_selection =
11879                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
11880                let query_matches = query
11881                    .stream_find_iter(bytes_before_last_selection)
11882                    .map(|result| (last_selection.start, result))
11883                    .chain(
11884                        query
11885                            .stream_find_iter(bytes_after_first_selection)
11886                            .map(|result| (buffer.len(), result)),
11887                    );
11888                for (end_offset, query_match) in query_matches {
11889                    let query_match = query_match.unwrap(); // can only fail due to I/O
11890                    let offset_range =
11891                        end_offset - query_match.end()..end_offset - query_match.start();
11892                    let display_range = offset_range.start.to_display_point(&display_map)
11893                        ..offset_range.end.to_display_point(&display_map);
11894
11895                    if !select_prev_state.wordwise
11896                        || (!movement::is_inside_word(&display_map, display_range.start)
11897                            && !movement::is_inside_word(&display_map, display_range.end))
11898                    {
11899                        next_selected_range = Some(offset_range);
11900                        break;
11901                    }
11902                }
11903
11904                if let Some(next_selected_range) = next_selected_range {
11905                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
11906                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11907                        if action.replace_newest {
11908                            s.delete(s.newest_anchor().id);
11909                        }
11910                        s.insert_range(next_selected_range);
11911                    });
11912                } else {
11913                    select_prev_state.done = true;
11914                }
11915            }
11916
11917            self.select_prev_state = Some(select_prev_state);
11918        } else {
11919            let mut only_carets = true;
11920            let mut same_text_selected = true;
11921            let mut selected_text = None;
11922
11923            let mut selections_iter = selections.iter().peekable();
11924            while let Some(selection) = selections_iter.next() {
11925                if selection.start != selection.end {
11926                    only_carets = false;
11927                }
11928
11929                if same_text_selected {
11930                    if selected_text.is_none() {
11931                        selected_text =
11932                            Some(buffer.text_for_range(selection.range()).collect::<String>());
11933                    }
11934
11935                    if let Some(next_selection) = selections_iter.peek() {
11936                        if next_selection.range().len() == selection.range().len() {
11937                            let next_selected_text = buffer
11938                                .text_for_range(next_selection.range())
11939                                .collect::<String>();
11940                            if Some(next_selected_text) != selected_text {
11941                                same_text_selected = false;
11942                                selected_text = None;
11943                            }
11944                        } else {
11945                            same_text_selected = false;
11946                            selected_text = None;
11947                        }
11948                    }
11949                }
11950            }
11951
11952            if only_carets {
11953                for selection in &mut selections {
11954                    let word_range = movement::surrounding_word(
11955                        &display_map,
11956                        selection.start.to_display_point(&display_map),
11957                    );
11958                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
11959                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
11960                    selection.goal = SelectionGoal::None;
11961                    selection.reversed = false;
11962                }
11963                if selections.len() == 1 {
11964                    let selection = selections
11965                        .last()
11966                        .expect("ensured that there's only one selection");
11967                    let query = buffer
11968                        .text_for_range(selection.start..selection.end)
11969                        .collect::<String>();
11970                    let is_empty = query.is_empty();
11971                    let select_state = SelectNextState {
11972                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
11973                        wordwise: true,
11974                        done: is_empty,
11975                    };
11976                    self.select_prev_state = Some(select_state);
11977                } else {
11978                    self.select_prev_state = None;
11979                }
11980
11981                self.unfold_ranges(
11982                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
11983                    false,
11984                    true,
11985                    cx,
11986                );
11987                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11988                    s.select(selections);
11989                });
11990            } else if let Some(selected_text) = selected_text {
11991                self.select_prev_state = Some(SelectNextState {
11992                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
11993                    wordwise: false,
11994                    done: false,
11995                });
11996                self.select_previous(action, window, cx)?;
11997            }
11998        }
11999        Ok(())
12000    }
12001
12002    pub fn toggle_comments(
12003        &mut self,
12004        action: &ToggleComments,
12005        window: &mut Window,
12006        cx: &mut Context<Self>,
12007    ) {
12008        if self.read_only(cx) {
12009            return;
12010        }
12011        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12012        let text_layout_details = &self.text_layout_details(window);
12013        self.transact(window, cx, |this, window, cx| {
12014            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12015            let mut edits = Vec::new();
12016            let mut selection_edit_ranges = Vec::new();
12017            let mut last_toggled_row = None;
12018            let snapshot = this.buffer.read(cx).read(cx);
12019            let empty_str: Arc<str> = Arc::default();
12020            let mut suffixes_inserted = Vec::new();
12021            let ignore_indent = action.ignore_indent;
12022
12023            fn comment_prefix_range(
12024                snapshot: &MultiBufferSnapshot,
12025                row: MultiBufferRow,
12026                comment_prefix: &str,
12027                comment_prefix_whitespace: &str,
12028                ignore_indent: bool,
12029            ) -> Range<Point> {
12030                let indent_size = if ignore_indent {
12031                    0
12032                } else {
12033                    snapshot.indent_size_for_line(row).len
12034                };
12035
12036                let start = Point::new(row.0, indent_size);
12037
12038                let mut line_bytes = snapshot
12039                    .bytes_in_range(start..snapshot.max_point())
12040                    .flatten()
12041                    .copied();
12042
12043                // If this line currently begins with the line comment prefix, then record
12044                // the range containing the prefix.
12045                if line_bytes
12046                    .by_ref()
12047                    .take(comment_prefix.len())
12048                    .eq(comment_prefix.bytes())
12049                {
12050                    // Include any whitespace that matches the comment prefix.
12051                    let matching_whitespace_len = line_bytes
12052                        .zip(comment_prefix_whitespace.bytes())
12053                        .take_while(|(a, b)| a == b)
12054                        .count() as u32;
12055                    let end = Point::new(
12056                        start.row,
12057                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12058                    );
12059                    start..end
12060                } else {
12061                    start..start
12062                }
12063            }
12064
12065            fn comment_suffix_range(
12066                snapshot: &MultiBufferSnapshot,
12067                row: MultiBufferRow,
12068                comment_suffix: &str,
12069                comment_suffix_has_leading_space: bool,
12070            ) -> Range<Point> {
12071                let end = Point::new(row.0, snapshot.line_len(row));
12072                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12073
12074                let mut line_end_bytes = snapshot
12075                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12076                    .flatten()
12077                    .copied();
12078
12079                let leading_space_len = if suffix_start_column > 0
12080                    && line_end_bytes.next() == Some(b' ')
12081                    && comment_suffix_has_leading_space
12082                {
12083                    1
12084                } else {
12085                    0
12086                };
12087
12088                // If this line currently begins with the line comment prefix, then record
12089                // the range containing the prefix.
12090                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12091                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
12092                    start..end
12093                } else {
12094                    end..end
12095                }
12096            }
12097
12098            // TODO: Handle selections that cross excerpts
12099            for selection in &mut selections {
12100                let start_column = snapshot
12101                    .indent_size_for_line(MultiBufferRow(selection.start.row))
12102                    .len;
12103                let language = if let Some(language) =
12104                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12105                {
12106                    language
12107                } else {
12108                    continue;
12109                };
12110
12111                selection_edit_ranges.clear();
12112
12113                // If multiple selections contain a given row, avoid processing that
12114                // row more than once.
12115                let mut start_row = MultiBufferRow(selection.start.row);
12116                if last_toggled_row == Some(start_row) {
12117                    start_row = start_row.next_row();
12118                }
12119                let end_row =
12120                    if selection.end.row > selection.start.row && selection.end.column == 0 {
12121                        MultiBufferRow(selection.end.row - 1)
12122                    } else {
12123                        MultiBufferRow(selection.end.row)
12124                    };
12125                last_toggled_row = Some(end_row);
12126
12127                if start_row > end_row {
12128                    continue;
12129                }
12130
12131                // If the language has line comments, toggle those.
12132                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12133
12134                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12135                if ignore_indent {
12136                    full_comment_prefixes = full_comment_prefixes
12137                        .into_iter()
12138                        .map(|s| Arc::from(s.trim_end()))
12139                        .collect();
12140                }
12141
12142                if !full_comment_prefixes.is_empty() {
12143                    let first_prefix = full_comment_prefixes
12144                        .first()
12145                        .expect("prefixes is non-empty");
12146                    let prefix_trimmed_lengths = full_comment_prefixes
12147                        .iter()
12148                        .map(|p| p.trim_end_matches(' ').len())
12149                        .collect::<SmallVec<[usize; 4]>>();
12150
12151                    let mut all_selection_lines_are_comments = true;
12152
12153                    for row in start_row.0..=end_row.0 {
12154                        let row = MultiBufferRow(row);
12155                        if start_row < end_row && snapshot.is_line_blank(row) {
12156                            continue;
12157                        }
12158
12159                        let prefix_range = full_comment_prefixes
12160                            .iter()
12161                            .zip(prefix_trimmed_lengths.iter().copied())
12162                            .map(|(prefix, trimmed_prefix_len)| {
12163                                comment_prefix_range(
12164                                    snapshot.deref(),
12165                                    row,
12166                                    &prefix[..trimmed_prefix_len],
12167                                    &prefix[trimmed_prefix_len..],
12168                                    ignore_indent,
12169                                )
12170                            })
12171                            .max_by_key(|range| range.end.column - range.start.column)
12172                            .expect("prefixes is non-empty");
12173
12174                        if prefix_range.is_empty() {
12175                            all_selection_lines_are_comments = false;
12176                        }
12177
12178                        selection_edit_ranges.push(prefix_range);
12179                    }
12180
12181                    if all_selection_lines_are_comments {
12182                        edits.extend(
12183                            selection_edit_ranges
12184                                .iter()
12185                                .cloned()
12186                                .map(|range| (range, empty_str.clone())),
12187                        );
12188                    } else {
12189                        let min_column = selection_edit_ranges
12190                            .iter()
12191                            .map(|range| range.start.column)
12192                            .min()
12193                            .unwrap_or(0);
12194                        edits.extend(selection_edit_ranges.iter().map(|range| {
12195                            let position = Point::new(range.start.row, min_column);
12196                            (position..position, first_prefix.clone())
12197                        }));
12198                    }
12199                } else if let Some((full_comment_prefix, comment_suffix)) =
12200                    language.block_comment_delimiters()
12201                {
12202                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12203                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12204                    let prefix_range = comment_prefix_range(
12205                        snapshot.deref(),
12206                        start_row,
12207                        comment_prefix,
12208                        comment_prefix_whitespace,
12209                        ignore_indent,
12210                    );
12211                    let suffix_range = comment_suffix_range(
12212                        snapshot.deref(),
12213                        end_row,
12214                        comment_suffix.trim_start_matches(' '),
12215                        comment_suffix.starts_with(' '),
12216                    );
12217
12218                    if prefix_range.is_empty() || suffix_range.is_empty() {
12219                        edits.push((
12220                            prefix_range.start..prefix_range.start,
12221                            full_comment_prefix.clone(),
12222                        ));
12223                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12224                        suffixes_inserted.push((end_row, comment_suffix.len()));
12225                    } else {
12226                        edits.push((prefix_range, empty_str.clone()));
12227                        edits.push((suffix_range, empty_str.clone()));
12228                    }
12229                } else {
12230                    continue;
12231                }
12232            }
12233
12234            drop(snapshot);
12235            this.buffer.update(cx, |buffer, cx| {
12236                buffer.edit(edits, None, cx);
12237            });
12238
12239            // Adjust selections so that they end before any comment suffixes that
12240            // were inserted.
12241            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12242            let mut selections = this.selections.all::<Point>(cx);
12243            let snapshot = this.buffer.read(cx).read(cx);
12244            for selection in &mut selections {
12245                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12246                    match row.cmp(&MultiBufferRow(selection.end.row)) {
12247                        Ordering::Less => {
12248                            suffixes_inserted.next();
12249                            continue;
12250                        }
12251                        Ordering::Greater => break,
12252                        Ordering::Equal => {
12253                            if selection.end.column == snapshot.line_len(row) {
12254                                if selection.is_empty() {
12255                                    selection.start.column -= suffix_len as u32;
12256                                }
12257                                selection.end.column -= suffix_len as u32;
12258                            }
12259                            break;
12260                        }
12261                    }
12262                }
12263            }
12264
12265            drop(snapshot);
12266            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12267                s.select(selections)
12268            });
12269
12270            let selections = this.selections.all::<Point>(cx);
12271            let selections_on_single_row = selections.windows(2).all(|selections| {
12272                selections[0].start.row == selections[1].start.row
12273                    && selections[0].end.row == selections[1].end.row
12274                    && selections[0].start.row == selections[0].end.row
12275            });
12276            let selections_selecting = selections
12277                .iter()
12278                .any(|selection| selection.start != selection.end);
12279            let advance_downwards = action.advance_downwards
12280                && selections_on_single_row
12281                && !selections_selecting
12282                && !matches!(this.mode, EditorMode::SingleLine { .. });
12283
12284            if advance_downwards {
12285                let snapshot = this.buffer.read(cx).snapshot(cx);
12286
12287                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12288                    s.move_cursors_with(|display_snapshot, display_point, _| {
12289                        let mut point = display_point.to_point(display_snapshot);
12290                        point.row += 1;
12291                        point = snapshot.clip_point(point, Bias::Left);
12292                        let display_point = point.to_display_point(display_snapshot);
12293                        let goal = SelectionGoal::HorizontalPosition(
12294                            display_snapshot
12295                                .x_for_display_point(display_point, text_layout_details)
12296                                .into(),
12297                        );
12298                        (display_point, goal)
12299                    })
12300                });
12301            }
12302        });
12303    }
12304
12305    pub fn select_enclosing_symbol(
12306        &mut self,
12307        _: &SelectEnclosingSymbol,
12308        window: &mut Window,
12309        cx: &mut Context<Self>,
12310    ) {
12311        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12312
12313        let buffer = self.buffer.read(cx).snapshot(cx);
12314        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12315
12316        fn update_selection(
12317            selection: &Selection<usize>,
12318            buffer_snap: &MultiBufferSnapshot,
12319        ) -> Option<Selection<usize>> {
12320            let cursor = selection.head();
12321            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12322            for symbol in symbols.iter().rev() {
12323                let start = symbol.range.start.to_offset(buffer_snap);
12324                let end = symbol.range.end.to_offset(buffer_snap);
12325                let new_range = start..end;
12326                if start < selection.start || end > selection.end {
12327                    return Some(Selection {
12328                        id: selection.id,
12329                        start: new_range.start,
12330                        end: new_range.end,
12331                        goal: SelectionGoal::None,
12332                        reversed: selection.reversed,
12333                    });
12334                }
12335            }
12336            None
12337        }
12338
12339        let mut selected_larger_symbol = false;
12340        let new_selections = old_selections
12341            .iter()
12342            .map(|selection| match update_selection(selection, &buffer) {
12343                Some(new_selection) => {
12344                    if new_selection.range() != selection.range() {
12345                        selected_larger_symbol = true;
12346                    }
12347                    new_selection
12348                }
12349                None => selection.clone(),
12350            })
12351            .collect::<Vec<_>>();
12352
12353        if selected_larger_symbol {
12354            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12355                s.select(new_selections);
12356            });
12357        }
12358    }
12359
12360    pub fn select_larger_syntax_node(
12361        &mut self,
12362        _: &SelectLargerSyntaxNode,
12363        window: &mut Window,
12364        cx: &mut Context<Self>,
12365    ) {
12366        let Some(visible_row_count) = self.visible_row_count() else {
12367            return;
12368        };
12369        let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12370        if old_selections.is_empty() {
12371            return;
12372        }
12373
12374        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12375
12376        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12377        let buffer = self.buffer.read(cx).snapshot(cx);
12378
12379        let mut selected_larger_node = false;
12380        let mut new_selections = old_selections
12381            .iter()
12382            .map(|selection| {
12383                let old_range = selection.start..selection.end;
12384                let mut new_range = old_range.clone();
12385                let mut new_node = None;
12386                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
12387                {
12388                    new_node = Some(node);
12389                    new_range = match containing_range {
12390                        MultiOrSingleBufferOffsetRange::Single(_) => break,
12391                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
12392                    };
12393                    if !display_map.intersects_fold(new_range.start)
12394                        && !display_map.intersects_fold(new_range.end)
12395                    {
12396                        break;
12397                    }
12398                }
12399
12400                if let Some(node) = new_node {
12401                    // Log the ancestor, to support using this action as a way to explore TreeSitter
12402                    // nodes. Parent and grandparent are also logged because this operation will not
12403                    // visit nodes that have the same range as their parent.
12404                    log::info!("Node: {node:?}");
12405                    let parent = node.parent();
12406                    log::info!("Parent: {parent:?}");
12407                    let grandparent = parent.and_then(|x| x.parent());
12408                    log::info!("Grandparent: {grandparent:?}");
12409                }
12410
12411                selected_larger_node |= new_range != old_range;
12412                Selection {
12413                    id: selection.id,
12414                    start: new_range.start,
12415                    end: new_range.end,
12416                    goal: SelectionGoal::None,
12417                    reversed: selection.reversed,
12418                }
12419            })
12420            .collect::<Vec<_>>();
12421
12422        if !selected_larger_node {
12423            return; // don't put this call in the history
12424        }
12425
12426        // scroll based on transformation done to the last selection created by the user
12427        let (last_old, last_new) = old_selections
12428            .last()
12429            .zip(new_selections.last().cloned())
12430            .expect("old_selections isn't empty");
12431
12432        // revert selection
12433        let is_selection_reversed = {
12434            let should_newest_selection_be_reversed = last_old.start != last_new.start;
12435            new_selections.last_mut().expect("checked above").reversed =
12436                should_newest_selection_be_reversed;
12437            should_newest_selection_be_reversed
12438        };
12439
12440        if selected_larger_node {
12441            self.select_syntax_node_history.disable_clearing = true;
12442            self.change_selections(None, window, cx, |s| {
12443                s.select(new_selections.clone());
12444            });
12445            self.select_syntax_node_history.disable_clearing = false;
12446        }
12447
12448        let start_row = last_new.start.to_display_point(&display_map).row().0;
12449        let end_row = last_new.end.to_display_point(&display_map).row().0;
12450        let selection_height = end_row - start_row + 1;
12451        let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12452
12453        let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
12454        let scroll_behavior = if fits_on_the_screen {
12455            self.request_autoscroll(Autoscroll::fit(), cx);
12456            SelectSyntaxNodeScrollBehavior::FitSelection
12457        } else if is_selection_reversed {
12458            self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12459            SelectSyntaxNodeScrollBehavior::CursorTop
12460        } else {
12461            self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12462            SelectSyntaxNodeScrollBehavior::CursorBottom
12463        };
12464
12465        self.select_syntax_node_history.push((
12466            old_selections,
12467            scroll_behavior,
12468            is_selection_reversed,
12469        ));
12470    }
12471
12472    pub fn select_smaller_syntax_node(
12473        &mut self,
12474        _: &SelectSmallerSyntaxNode,
12475        window: &mut Window,
12476        cx: &mut Context<Self>,
12477    ) {
12478        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12479
12480        if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12481            self.select_syntax_node_history.pop()
12482        {
12483            if let Some(selection) = selections.last_mut() {
12484                selection.reversed = is_selection_reversed;
12485            }
12486
12487            self.select_syntax_node_history.disable_clearing = true;
12488            self.change_selections(None, window, cx, |s| {
12489                s.select(selections.to_vec());
12490            });
12491            self.select_syntax_node_history.disable_clearing = false;
12492
12493            match scroll_behavior {
12494                SelectSyntaxNodeScrollBehavior::CursorTop => {
12495                    self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12496                }
12497                SelectSyntaxNodeScrollBehavior::FitSelection => {
12498                    self.request_autoscroll(Autoscroll::fit(), cx);
12499                }
12500                SelectSyntaxNodeScrollBehavior::CursorBottom => {
12501                    self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12502                }
12503            }
12504        }
12505    }
12506
12507    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12508        if !EditorSettings::get_global(cx).gutter.runnables {
12509            self.clear_tasks();
12510            return Task::ready(());
12511        }
12512        let project = self.project.as_ref().map(Entity::downgrade);
12513        let task_sources = self.lsp_task_sources(cx);
12514        cx.spawn_in(window, async move |editor, cx| {
12515            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12516            let Some(project) = project.and_then(|p| p.upgrade()) else {
12517                return;
12518            };
12519            let Ok(display_snapshot) = editor.update(cx, |this, cx| {
12520                this.display_map.update(cx, |map, cx| map.snapshot(cx))
12521            }) else {
12522                return;
12523            };
12524
12525            let hide_runnables = project
12526                .update(cx, |project, cx| {
12527                    // Do not display any test indicators in non-dev server remote projects.
12528                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12529                })
12530                .unwrap_or(true);
12531            if hide_runnables {
12532                return;
12533            }
12534            let new_rows =
12535                cx.background_spawn({
12536                    let snapshot = display_snapshot.clone();
12537                    async move {
12538                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12539                    }
12540                })
12541                    .await;
12542            let Ok(lsp_tasks) =
12543                cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
12544            else {
12545                return;
12546            };
12547            let lsp_tasks = lsp_tasks.await;
12548
12549            let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
12550                lsp_tasks
12551                    .into_iter()
12552                    .flat_map(|(kind, tasks)| {
12553                        tasks.into_iter().filter_map(move |(location, task)| {
12554                            Some((kind.clone(), location?, task))
12555                        })
12556                    })
12557                    .fold(HashMap::default(), |mut acc, (kind, location, task)| {
12558                        let buffer = location.target.buffer;
12559                        let buffer_snapshot = buffer.read(cx).snapshot();
12560                        let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
12561                            |(excerpt_id, snapshot, _)| {
12562                                if snapshot.remote_id() == buffer_snapshot.remote_id() {
12563                                    display_snapshot
12564                                        .buffer_snapshot
12565                                        .anchor_in_excerpt(excerpt_id, location.target.range.start)
12566                                } else {
12567                                    None
12568                                }
12569                            },
12570                        );
12571                        if let Some(offset) = offset {
12572                            let task_buffer_range =
12573                                location.target.range.to_point(&buffer_snapshot);
12574                            let context_buffer_range =
12575                                task_buffer_range.to_offset(&buffer_snapshot);
12576                            let context_range = BufferOffset(context_buffer_range.start)
12577                                ..BufferOffset(context_buffer_range.end);
12578
12579                            acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
12580                                .or_insert_with(|| RunnableTasks {
12581                                    templates: Vec::new(),
12582                                    offset,
12583                                    column: task_buffer_range.start.column,
12584                                    extra_variables: HashMap::default(),
12585                                    context_range,
12586                                })
12587                                .templates
12588                                .push((kind, task.original_task().clone()));
12589                        }
12590
12591                        acc
12592                    })
12593            }) else {
12594                return;
12595            };
12596
12597            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12598            editor
12599                .update(cx, |editor, _| {
12600                    editor.clear_tasks();
12601                    for (key, mut value) in rows {
12602                        if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
12603                            value.templates.extend(lsp_tasks.templates);
12604                        }
12605
12606                        editor.insert_tasks(key, value);
12607                    }
12608                    for (key, value) in lsp_tasks_by_rows {
12609                        editor.insert_tasks(key, value);
12610                    }
12611                })
12612                .ok();
12613        })
12614    }
12615    fn fetch_runnable_ranges(
12616        snapshot: &DisplaySnapshot,
12617        range: Range<Anchor>,
12618    ) -> Vec<language::RunnableRange> {
12619        snapshot.buffer_snapshot.runnable_ranges(range).collect()
12620    }
12621
12622    fn runnable_rows(
12623        project: Entity<Project>,
12624        snapshot: DisplaySnapshot,
12625        runnable_ranges: Vec<RunnableRange>,
12626        mut cx: AsyncWindowContext,
12627    ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
12628        runnable_ranges
12629            .into_iter()
12630            .filter_map(|mut runnable| {
12631                let tasks = cx
12632                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12633                    .ok()?;
12634                if tasks.is_empty() {
12635                    return None;
12636                }
12637
12638                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12639
12640                let row = snapshot
12641                    .buffer_snapshot
12642                    .buffer_line_for_row(MultiBufferRow(point.row))?
12643                    .1
12644                    .start
12645                    .row;
12646
12647                let context_range =
12648                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12649                Some((
12650                    (runnable.buffer_id, row),
12651                    RunnableTasks {
12652                        templates: tasks,
12653                        offset: snapshot
12654                            .buffer_snapshot
12655                            .anchor_before(runnable.run_range.start),
12656                        context_range,
12657                        column: point.column,
12658                        extra_variables: runnable.extra_captures,
12659                    },
12660                ))
12661            })
12662            .collect()
12663    }
12664
12665    fn templates_with_tags(
12666        project: &Entity<Project>,
12667        runnable: &mut Runnable,
12668        cx: &mut App,
12669    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12670        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12671            let (worktree_id, file) = project
12672                .buffer_for_id(runnable.buffer, cx)
12673                .and_then(|buffer| buffer.read(cx).file())
12674                .map(|file| (file.worktree_id(cx), file.clone()))
12675                .unzip();
12676
12677            (
12678                project.task_store().read(cx).task_inventory().cloned(),
12679                worktree_id,
12680                file,
12681            )
12682        });
12683
12684        let mut templates_with_tags = mem::take(&mut runnable.tags)
12685            .into_iter()
12686            .flat_map(|RunnableTag(tag)| {
12687                inventory
12688                    .as_ref()
12689                    .into_iter()
12690                    .flat_map(|inventory| {
12691                        inventory.read(cx).list_tasks(
12692                            file.clone(),
12693                            Some(runnable.language.clone()),
12694                            worktree_id,
12695                            cx,
12696                        )
12697                    })
12698                    .filter(move |(_, template)| {
12699                        template.tags.iter().any(|source_tag| source_tag == &tag)
12700                    })
12701            })
12702            .sorted_by_key(|(kind, _)| kind.to_owned())
12703            .collect::<Vec<_>>();
12704        if let Some((leading_tag_source, _)) = templates_with_tags.first() {
12705            // Strongest source wins; if we have worktree tag binding, prefer that to
12706            // global and language bindings;
12707            // if we have a global binding, prefer that to language binding.
12708            let first_mismatch = templates_with_tags
12709                .iter()
12710                .position(|(tag_source, _)| tag_source != leading_tag_source);
12711            if let Some(index) = first_mismatch {
12712                templates_with_tags.truncate(index);
12713            }
12714        }
12715
12716        templates_with_tags
12717    }
12718
12719    pub fn move_to_enclosing_bracket(
12720        &mut self,
12721        _: &MoveToEnclosingBracket,
12722        window: &mut Window,
12723        cx: &mut Context<Self>,
12724    ) {
12725        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12726        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12727            s.move_offsets_with(|snapshot, selection| {
12728                let Some(enclosing_bracket_ranges) =
12729                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
12730                else {
12731                    return;
12732                };
12733
12734                let mut best_length = usize::MAX;
12735                let mut best_inside = false;
12736                let mut best_in_bracket_range = false;
12737                let mut best_destination = None;
12738                for (open, close) in enclosing_bracket_ranges {
12739                    let close = close.to_inclusive();
12740                    let length = close.end() - open.start;
12741                    let inside = selection.start >= open.end && selection.end <= *close.start();
12742                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
12743                        || close.contains(&selection.head());
12744
12745                    // If best is next to a bracket and current isn't, skip
12746                    if !in_bracket_range && best_in_bracket_range {
12747                        continue;
12748                    }
12749
12750                    // Prefer smaller lengths unless best is inside and current isn't
12751                    if length > best_length && (best_inside || !inside) {
12752                        continue;
12753                    }
12754
12755                    best_length = length;
12756                    best_inside = inside;
12757                    best_in_bracket_range = in_bracket_range;
12758                    best_destination = Some(
12759                        if close.contains(&selection.start) && close.contains(&selection.end) {
12760                            if inside { open.end } else { open.start }
12761                        } else if inside {
12762                            *close.start()
12763                        } else {
12764                            *close.end()
12765                        },
12766                    );
12767                }
12768
12769                if let Some(destination) = best_destination {
12770                    selection.collapse_to(destination, SelectionGoal::None);
12771                }
12772            })
12773        });
12774    }
12775
12776    pub fn undo_selection(
12777        &mut self,
12778        _: &UndoSelection,
12779        window: &mut Window,
12780        cx: &mut Context<Self>,
12781    ) {
12782        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12783        self.end_selection(window, cx);
12784        self.selection_history.mode = SelectionHistoryMode::Undoing;
12785        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
12786            self.change_selections(None, window, cx, |s| {
12787                s.select_anchors(entry.selections.to_vec())
12788            });
12789            self.select_next_state = entry.select_next_state;
12790            self.select_prev_state = entry.select_prev_state;
12791            self.add_selections_state = entry.add_selections_state;
12792            self.request_autoscroll(Autoscroll::newest(), cx);
12793        }
12794        self.selection_history.mode = SelectionHistoryMode::Normal;
12795    }
12796
12797    pub fn redo_selection(
12798        &mut self,
12799        _: &RedoSelection,
12800        window: &mut Window,
12801        cx: &mut Context<Self>,
12802    ) {
12803        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12804        self.end_selection(window, cx);
12805        self.selection_history.mode = SelectionHistoryMode::Redoing;
12806        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
12807            self.change_selections(None, window, cx, |s| {
12808                s.select_anchors(entry.selections.to_vec())
12809            });
12810            self.select_next_state = entry.select_next_state;
12811            self.select_prev_state = entry.select_prev_state;
12812            self.add_selections_state = entry.add_selections_state;
12813            self.request_autoscroll(Autoscroll::newest(), cx);
12814        }
12815        self.selection_history.mode = SelectionHistoryMode::Normal;
12816    }
12817
12818    pub fn expand_excerpts(
12819        &mut self,
12820        action: &ExpandExcerpts,
12821        _: &mut Window,
12822        cx: &mut Context<Self>,
12823    ) {
12824        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
12825    }
12826
12827    pub fn expand_excerpts_down(
12828        &mut self,
12829        action: &ExpandExcerptsDown,
12830        _: &mut Window,
12831        cx: &mut Context<Self>,
12832    ) {
12833        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
12834    }
12835
12836    pub fn expand_excerpts_up(
12837        &mut self,
12838        action: &ExpandExcerptsUp,
12839        _: &mut Window,
12840        cx: &mut Context<Self>,
12841    ) {
12842        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
12843    }
12844
12845    pub fn expand_excerpts_for_direction(
12846        &mut self,
12847        lines: u32,
12848        direction: ExpandExcerptDirection,
12849
12850        cx: &mut Context<Self>,
12851    ) {
12852        let selections = self.selections.disjoint_anchors();
12853
12854        let lines = if lines == 0 {
12855            EditorSettings::get_global(cx).expand_excerpt_lines
12856        } else {
12857            lines
12858        };
12859
12860        self.buffer.update(cx, |buffer, cx| {
12861            let snapshot = buffer.snapshot(cx);
12862            let mut excerpt_ids = selections
12863                .iter()
12864                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
12865                .collect::<Vec<_>>();
12866            excerpt_ids.sort();
12867            excerpt_ids.dedup();
12868            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
12869        })
12870    }
12871
12872    pub fn expand_excerpt(
12873        &mut self,
12874        excerpt: ExcerptId,
12875        direction: ExpandExcerptDirection,
12876        window: &mut Window,
12877        cx: &mut Context<Self>,
12878    ) {
12879        let current_scroll_position = self.scroll_position(cx);
12880        let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
12881        let mut should_scroll_up = false;
12882
12883        if direction == ExpandExcerptDirection::Down {
12884            let multi_buffer = self.buffer.read(cx);
12885            let snapshot = multi_buffer.snapshot(cx);
12886            if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
12887                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12888                    if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
12889                        let buffer_snapshot = buffer.read(cx).snapshot();
12890                        let excerpt_end_row =
12891                            Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
12892                        let last_row = buffer_snapshot.max_point().row;
12893                        let lines_below = last_row.saturating_sub(excerpt_end_row);
12894                        should_scroll_up = lines_below >= lines_to_expand;
12895                    }
12896                }
12897            }
12898        }
12899
12900        self.buffer.update(cx, |buffer, cx| {
12901            buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
12902        });
12903
12904        if should_scroll_up {
12905            let new_scroll_position =
12906                current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
12907            self.set_scroll_position(new_scroll_position, window, cx);
12908        }
12909    }
12910
12911    pub fn go_to_singleton_buffer_point(
12912        &mut self,
12913        point: Point,
12914        window: &mut Window,
12915        cx: &mut Context<Self>,
12916    ) {
12917        self.go_to_singleton_buffer_range(point..point, window, cx);
12918    }
12919
12920    pub fn go_to_singleton_buffer_range(
12921        &mut self,
12922        range: Range<Point>,
12923        window: &mut Window,
12924        cx: &mut Context<Self>,
12925    ) {
12926        let multibuffer = self.buffer().read(cx);
12927        let Some(buffer) = multibuffer.as_singleton() else {
12928            return;
12929        };
12930        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
12931            return;
12932        };
12933        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
12934            return;
12935        };
12936        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
12937            s.select_anchor_ranges([start..end])
12938        });
12939    }
12940
12941    fn go_to_diagnostic(
12942        &mut self,
12943        _: &GoToDiagnostic,
12944        window: &mut Window,
12945        cx: &mut Context<Self>,
12946    ) {
12947        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12948        self.go_to_diagnostic_impl(Direction::Next, window, cx)
12949    }
12950
12951    fn go_to_prev_diagnostic(
12952        &mut self,
12953        _: &GoToPreviousDiagnostic,
12954        window: &mut Window,
12955        cx: &mut Context<Self>,
12956    ) {
12957        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12958        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
12959    }
12960
12961    pub fn go_to_diagnostic_impl(
12962        &mut self,
12963        direction: Direction,
12964        window: &mut Window,
12965        cx: &mut Context<Self>,
12966    ) {
12967        let buffer = self.buffer.read(cx).snapshot(cx);
12968        let selection = self.selections.newest::<usize>(cx);
12969        // If there is an active Diagnostic Popover jump to its diagnostic instead.
12970        if direction == Direction::Next {
12971            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
12972                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
12973                    return;
12974                };
12975                self.activate_diagnostics(
12976                    buffer_id,
12977                    popover.local_diagnostic.diagnostic.group_id,
12978                    window,
12979                    cx,
12980                );
12981                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
12982                    let primary_range_start = active_diagnostics.primary_range.start;
12983                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12984                        let mut new_selection = s.newest_anchor().clone();
12985                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
12986                        s.select_anchors(vec![new_selection.clone()]);
12987                    });
12988                    self.refresh_inline_completion(false, true, window, cx);
12989                }
12990                return;
12991            }
12992        }
12993
12994        let active_group_id = self
12995            .active_diagnostics
12996            .as_ref()
12997            .map(|active_group| active_group.group_id);
12998        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
12999            active_diagnostics
13000                .primary_range
13001                .to_offset(&buffer)
13002                .to_inclusive()
13003        });
13004        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
13005            if active_primary_range.contains(&selection.head()) {
13006                *active_primary_range.start()
13007            } else {
13008                selection.head()
13009            }
13010        } else {
13011            selection.head()
13012        };
13013
13014        let snapshot = self.snapshot(window, cx);
13015        let primary_diagnostics_before = buffer
13016            .diagnostics_in_range::<usize>(0..search_start)
13017            .filter(|entry| entry.diagnostic.is_primary)
13018            .filter(|entry| entry.range.start != entry.range.end)
13019            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
13020            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
13021            .collect::<Vec<_>>();
13022        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
13023            primary_diagnostics_before
13024                .iter()
13025                .position(|entry| entry.diagnostic.group_id == active_group_id)
13026        });
13027
13028        let primary_diagnostics_after = buffer
13029            .diagnostics_in_range::<usize>(search_start..buffer.len())
13030            .filter(|entry| entry.diagnostic.is_primary)
13031            .filter(|entry| entry.range.start != entry.range.end)
13032            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
13033            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
13034            .collect::<Vec<_>>();
13035        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
13036            primary_diagnostics_after
13037                .iter()
13038                .enumerate()
13039                .rev()
13040                .find_map(|(i, entry)| {
13041                    if entry.diagnostic.group_id == active_group_id {
13042                        Some(i)
13043                    } else {
13044                        None
13045                    }
13046                })
13047        });
13048
13049        let next_primary_diagnostic = match direction {
13050            Direction::Prev => primary_diagnostics_before
13051                .iter()
13052                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
13053                .rev()
13054                .next(),
13055            Direction::Next => primary_diagnostics_after
13056                .iter()
13057                .skip(
13058                    last_same_group_diagnostic_after
13059                        .map(|index| index + 1)
13060                        .unwrap_or(0),
13061                )
13062                .next(),
13063        };
13064
13065        // Cycle around to the start of the buffer, potentially moving back to the start of
13066        // the currently active diagnostic.
13067        let cycle_around = || match direction {
13068            Direction::Prev => primary_diagnostics_after
13069                .iter()
13070                .rev()
13071                .chain(primary_diagnostics_before.iter().rev())
13072                .next(),
13073            Direction::Next => primary_diagnostics_before
13074                .iter()
13075                .chain(primary_diagnostics_after.iter())
13076                .next(),
13077        };
13078
13079        if let Some((primary_range, group_id)) = next_primary_diagnostic
13080            .or_else(cycle_around)
13081            .map(|entry| (&entry.range, entry.diagnostic.group_id))
13082        {
13083            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
13084                return;
13085            };
13086            self.activate_diagnostics(buffer_id, group_id, window, cx);
13087            if self.active_diagnostics.is_some() {
13088                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13089                    s.select(vec![Selection {
13090                        id: selection.id,
13091                        start: primary_range.start,
13092                        end: primary_range.start,
13093                        reversed: false,
13094                        goal: SelectionGoal::None,
13095                    }]);
13096                });
13097                self.refresh_inline_completion(false, true, window, cx);
13098            }
13099        }
13100    }
13101
13102    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13103        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13104        let snapshot = self.snapshot(window, cx);
13105        let selection = self.selections.newest::<Point>(cx);
13106        self.go_to_hunk_before_or_after_position(
13107            &snapshot,
13108            selection.head(),
13109            Direction::Next,
13110            window,
13111            cx,
13112        );
13113    }
13114
13115    pub fn go_to_hunk_before_or_after_position(
13116        &mut self,
13117        snapshot: &EditorSnapshot,
13118        position: Point,
13119        direction: Direction,
13120        window: &mut Window,
13121        cx: &mut Context<Editor>,
13122    ) {
13123        let row = if direction == Direction::Next {
13124            self.hunk_after_position(snapshot, position)
13125                .map(|hunk| hunk.row_range.start)
13126        } else {
13127            self.hunk_before_position(snapshot, position)
13128        };
13129
13130        if let Some(row) = row {
13131            let destination = Point::new(row.0, 0);
13132            let autoscroll = Autoscroll::center();
13133
13134            self.unfold_ranges(&[destination..destination], false, false, cx);
13135            self.change_selections(Some(autoscroll), window, cx, |s| {
13136                s.select_ranges([destination..destination]);
13137            });
13138        }
13139    }
13140
13141    fn hunk_after_position(
13142        &mut self,
13143        snapshot: &EditorSnapshot,
13144        position: Point,
13145    ) -> Option<MultiBufferDiffHunk> {
13146        snapshot
13147            .buffer_snapshot
13148            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13149            .find(|hunk| hunk.row_range.start.0 > position.row)
13150            .or_else(|| {
13151                snapshot
13152                    .buffer_snapshot
13153                    .diff_hunks_in_range(Point::zero()..position)
13154                    .find(|hunk| hunk.row_range.end.0 < position.row)
13155            })
13156    }
13157
13158    fn go_to_prev_hunk(
13159        &mut self,
13160        _: &GoToPreviousHunk,
13161        window: &mut Window,
13162        cx: &mut Context<Self>,
13163    ) {
13164        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13165        let snapshot = self.snapshot(window, cx);
13166        let selection = self.selections.newest::<Point>(cx);
13167        self.go_to_hunk_before_or_after_position(
13168            &snapshot,
13169            selection.head(),
13170            Direction::Prev,
13171            window,
13172            cx,
13173        );
13174    }
13175
13176    fn hunk_before_position(
13177        &mut self,
13178        snapshot: &EditorSnapshot,
13179        position: Point,
13180    ) -> Option<MultiBufferRow> {
13181        snapshot
13182            .buffer_snapshot
13183            .diff_hunk_before(position)
13184            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13185    }
13186
13187    fn go_to_line<T: 'static>(
13188        &mut self,
13189        position: Anchor,
13190        highlight_color: Option<Hsla>,
13191        window: &mut Window,
13192        cx: &mut Context<Self>,
13193    ) {
13194        let snapshot = self.snapshot(window, cx).display_snapshot;
13195        let position = position.to_point(&snapshot.buffer_snapshot);
13196        let start = snapshot
13197            .buffer_snapshot
13198            .clip_point(Point::new(position.row, 0), Bias::Left);
13199        let end = start + Point::new(1, 0);
13200        let start = snapshot.buffer_snapshot.anchor_before(start);
13201        let end = snapshot.buffer_snapshot.anchor_before(end);
13202
13203        self.highlight_rows::<T>(
13204            start..end,
13205            highlight_color
13206                .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13207            false,
13208            cx,
13209        );
13210        self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13211    }
13212
13213    pub fn go_to_definition(
13214        &mut self,
13215        _: &GoToDefinition,
13216        window: &mut Window,
13217        cx: &mut Context<Self>,
13218    ) -> Task<Result<Navigated>> {
13219        let definition =
13220            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13221        let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13222        cx.spawn_in(window, async move |editor, cx| {
13223            if definition.await? == Navigated::Yes {
13224                return Ok(Navigated::Yes);
13225            }
13226            match fallback_strategy {
13227                GoToDefinitionFallback::None => Ok(Navigated::No),
13228                GoToDefinitionFallback::FindAllReferences => {
13229                    match editor.update_in(cx, |editor, window, cx| {
13230                        editor.find_all_references(&FindAllReferences, window, cx)
13231                    })? {
13232                        Some(references) => references.await,
13233                        None => Ok(Navigated::No),
13234                    }
13235                }
13236            }
13237        })
13238    }
13239
13240    pub fn go_to_declaration(
13241        &mut self,
13242        _: &GoToDeclaration,
13243        window: &mut Window,
13244        cx: &mut Context<Self>,
13245    ) -> Task<Result<Navigated>> {
13246        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13247    }
13248
13249    pub fn go_to_declaration_split(
13250        &mut self,
13251        _: &GoToDeclaration,
13252        window: &mut Window,
13253        cx: &mut Context<Self>,
13254    ) -> Task<Result<Navigated>> {
13255        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13256    }
13257
13258    pub fn go_to_implementation(
13259        &mut self,
13260        _: &GoToImplementation,
13261        window: &mut Window,
13262        cx: &mut Context<Self>,
13263    ) -> Task<Result<Navigated>> {
13264        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13265    }
13266
13267    pub fn go_to_implementation_split(
13268        &mut self,
13269        _: &GoToImplementationSplit,
13270        window: &mut Window,
13271        cx: &mut Context<Self>,
13272    ) -> Task<Result<Navigated>> {
13273        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13274    }
13275
13276    pub fn go_to_type_definition(
13277        &mut self,
13278        _: &GoToTypeDefinition,
13279        window: &mut Window,
13280        cx: &mut Context<Self>,
13281    ) -> Task<Result<Navigated>> {
13282        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13283    }
13284
13285    pub fn go_to_definition_split(
13286        &mut self,
13287        _: &GoToDefinitionSplit,
13288        window: &mut Window,
13289        cx: &mut Context<Self>,
13290    ) -> Task<Result<Navigated>> {
13291        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13292    }
13293
13294    pub fn go_to_type_definition_split(
13295        &mut self,
13296        _: &GoToTypeDefinitionSplit,
13297        window: &mut Window,
13298        cx: &mut Context<Self>,
13299    ) -> Task<Result<Navigated>> {
13300        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13301    }
13302
13303    fn go_to_definition_of_kind(
13304        &mut self,
13305        kind: GotoDefinitionKind,
13306        split: bool,
13307        window: &mut Window,
13308        cx: &mut Context<Self>,
13309    ) -> Task<Result<Navigated>> {
13310        let Some(provider) = self.semantics_provider.clone() else {
13311            return Task::ready(Ok(Navigated::No));
13312        };
13313        let head = self.selections.newest::<usize>(cx).head();
13314        let buffer = self.buffer.read(cx);
13315        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13316            text_anchor
13317        } else {
13318            return Task::ready(Ok(Navigated::No));
13319        };
13320
13321        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13322            return Task::ready(Ok(Navigated::No));
13323        };
13324
13325        cx.spawn_in(window, async move |editor, cx| {
13326            let definitions = definitions.await?;
13327            let navigated = editor
13328                .update_in(cx, |editor, window, cx| {
13329                    editor.navigate_to_hover_links(
13330                        Some(kind),
13331                        definitions
13332                            .into_iter()
13333                            .filter(|location| {
13334                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13335                            })
13336                            .map(HoverLink::Text)
13337                            .collect::<Vec<_>>(),
13338                        split,
13339                        window,
13340                        cx,
13341                    )
13342                })?
13343                .await?;
13344            anyhow::Ok(navigated)
13345        })
13346    }
13347
13348    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13349        let selection = self.selections.newest_anchor();
13350        let head = selection.head();
13351        let tail = selection.tail();
13352
13353        let Some((buffer, start_position)) =
13354            self.buffer.read(cx).text_anchor_for_position(head, cx)
13355        else {
13356            return;
13357        };
13358
13359        let end_position = if head != tail {
13360            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13361                return;
13362            };
13363            Some(pos)
13364        } else {
13365            None
13366        };
13367
13368        let url_finder = cx.spawn_in(window, async move |editor, cx| {
13369            let url = if let Some(end_pos) = end_position {
13370                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13371            } else {
13372                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13373            };
13374
13375            if let Some(url) = url {
13376                editor.update(cx, |_, cx| {
13377                    cx.open_url(&url);
13378                })
13379            } else {
13380                Ok(())
13381            }
13382        });
13383
13384        url_finder.detach();
13385    }
13386
13387    pub fn open_selected_filename(
13388        &mut self,
13389        _: &OpenSelectedFilename,
13390        window: &mut Window,
13391        cx: &mut Context<Self>,
13392    ) {
13393        let Some(workspace) = self.workspace() else {
13394            return;
13395        };
13396
13397        let position = self.selections.newest_anchor().head();
13398
13399        let Some((buffer, buffer_position)) =
13400            self.buffer.read(cx).text_anchor_for_position(position, cx)
13401        else {
13402            return;
13403        };
13404
13405        let project = self.project.clone();
13406
13407        cx.spawn_in(window, async move |_, cx| {
13408            let result = find_file(&buffer, project, buffer_position, cx).await;
13409
13410            if let Some((_, path)) = result {
13411                workspace
13412                    .update_in(cx, |workspace, window, cx| {
13413                        workspace.open_resolved_path(path, window, cx)
13414                    })?
13415                    .await?;
13416            }
13417            anyhow::Ok(())
13418        })
13419        .detach();
13420    }
13421
13422    pub(crate) fn navigate_to_hover_links(
13423        &mut self,
13424        kind: Option<GotoDefinitionKind>,
13425        mut definitions: Vec<HoverLink>,
13426        split: bool,
13427        window: &mut Window,
13428        cx: &mut Context<Editor>,
13429    ) -> Task<Result<Navigated>> {
13430        // If there is one definition, just open it directly
13431        if definitions.len() == 1 {
13432            let definition = definitions.pop().unwrap();
13433
13434            enum TargetTaskResult {
13435                Location(Option<Location>),
13436                AlreadyNavigated,
13437            }
13438
13439            let target_task = match definition {
13440                HoverLink::Text(link) => {
13441                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13442                }
13443                HoverLink::InlayHint(lsp_location, server_id) => {
13444                    let computation =
13445                        self.compute_target_location(lsp_location, server_id, window, cx);
13446                    cx.background_spawn(async move {
13447                        let location = computation.await?;
13448                        Ok(TargetTaskResult::Location(location))
13449                    })
13450                }
13451                HoverLink::Url(url) => {
13452                    cx.open_url(&url);
13453                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13454                }
13455                HoverLink::File(path) => {
13456                    if let Some(workspace) = self.workspace() {
13457                        cx.spawn_in(window, async move |_, cx| {
13458                            workspace
13459                                .update_in(cx, |workspace, window, cx| {
13460                                    workspace.open_resolved_path(path, window, cx)
13461                                })?
13462                                .await
13463                                .map(|_| TargetTaskResult::AlreadyNavigated)
13464                        })
13465                    } else {
13466                        Task::ready(Ok(TargetTaskResult::Location(None)))
13467                    }
13468                }
13469            };
13470            cx.spawn_in(window, async move |editor, cx| {
13471                let target = match target_task.await.context("target resolution task")? {
13472                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13473                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
13474                    TargetTaskResult::Location(Some(target)) => target,
13475                };
13476
13477                editor.update_in(cx, |editor, window, cx| {
13478                    let Some(workspace) = editor.workspace() else {
13479                        return Navigated::No;
13480                    };
13481                    let pane = workspace.read(cx).active_pane().clone();
13482
13483                    let range = target.range.to_point(target.buffer.read(cx));
13484                    let range = editor.range_for_match(&range);
13485                    let range = collapse_multiline_range(range);
13486
13487                    if !split
13488                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13489                    {
13490                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13491                    } else {
13492                        window.defer(cx, move |window, cx| {
13493                            let target_editor: Entity<Self> =
13494                                workspace.update(cx, |workspace, cx| {
13495                                    let pane = if split {
13496                                        workspace.adjacent_pane(window, cx)
13497                                    } else {
13498                                        workspace.active_pane().clone()
13499                                    };
13500
13501                                    workspace.open_project_item(
13502                                        pane,
13503                                        target.buffer.clone(),
13504                                        true,
13505                                        true,
13506                                        window,
13507                                        cx,
13508                                    )
13509                                });
13510                            target_editor.update(cx, |target_editor, cx| {
13511                                // When selecting a definition in a different buffer, disable the nav history
13512                                // to avoid creating a history entry at the previous cursor location.
13513                                pane.update(cx, |pane, _| pane.disable_history());
13514                                target_editor.go_to_singleton_buffer_range(range, window, cx);
13515                                pane.update(cx, |pane, _| pane.enable_history());
13516                            });
13517                        });
13518                    }
13519                    Navigated::Yes
13520                })
13521            })
13522        } else if !definitions.is_empty() {
13523            cx.spawn_in(window, async move |editor, cx| {
13524                let (title, location_tasks, workspace) = editor
13525                    .update_in(cx, |editor, window, cx| {
13526                        let tab_kind = match kind {
13527                            Some(GotoDefinitionKind::Implementation) => "Implementations",
13528                            _ => "Definitions",
13529                        };
13530                        let title = definitions
13531                            .iter()
13532                            .find_map(|definition| match definition {
13533                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
13534                                    let buffer = origin.buffer.read(cx);
13535                                    format!(
13536                                        "{} for {}",
13537                                        tab_kind,
13538                                        buffer
13539                                            .text_for_range(origin.range.clone())
13540                                            .collect::<String>()
13541                                    )
13542                                }),
13543                                HoverLink::InlayHint(_, _) => None,
13544                                HoverLink::Url(_) => None,
13545                                HoverLink::File(_) => None,
13546                            })
13547                            .unwrap_or(tab_kind.to_string());
13548                        let location_tasks = definitions
13549                            .into_iter()
13550                            .map(|definition| match definition {
13551                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
13552                                HoverLink::InlayHint(lsp_location, server_id) => editor
13553                                    .compute_target_location(lsp_location, server_id, window, cx),
13554                                HoverLink::Url(_) => Task::ready(Ok(None)),
13555                                HoverLink::File(_) => Task::ready(Ok(None)),
13556                            })
13557                            .collect::<Vec<_>>();
13558                        (title, location_tasks, editor.workspace().clone())
13559                    })
13560                    .context("location tasks preparation")?;
13561
13562                let locations = future::join_all(location_tasks)
13563                    .await
13564                    .into_iter()
13565                    .filter_map(|location| location.transpose())
13566                    .collect::<Result<_>>()
13567                    .context("location tasks")?;
13568
13569                let Some(workspace) = workspace else {
13570                    return Ok(Navigated::No);
13571                };
13572                let opened = workspace
13573                    .update_in(cx, |workspace, window, cx| {
13574                        Self::open_locations_in_multibuffer(
13575                            workspace,
13576                            locations,
13577                            title,
13578                            split,
13579                            MultibufferSelectionMode::First,
13580                            window,
13581                            cx,
13582                        )
13583                    })
13584                    .ok();
13585
13586                anyhow::Ok(Navigated::from_bool(opened.is_some()))
13587            })
13588        } else {
13589            Task::ready(Ok(Navigated::No))
13590        }
13591    }
13592
13593    fn compute_target_location(
13594        &self,
13595        lsp_location: lsp::Location,
13596        server_id: LanguageServerId,
13597        window: &mut Window,
13598        cx: &mut Context<Self>,
13599    ) -> Task<anyhow::Result<Option<Location>>> {
13600        let Some(project) = self.project.clone() else {
13601            return Task::ready(Ok(None));
13602        };
13603
13604        cx.spawn_in(window, async move |editor, cx| {
13605            let location_task = editor.update(cx, |_, cx| {
13606                project.update(cx, |project, cx| {
13607                    let language_server_name = project
13608                        .language_server_statuses(cx)
13609                        .find(|(id, _)| server_id == *id)
13610                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13611                    language_server_name.map(|language_server_name| {
13612                        project.open_local_buffer_via_lsp(
13613                            lsp_location.uri.clone(),
13614                            server_id,
13615                            language_server_name,
13616                            cx,
13617                        )
13618                    })
13619                })
13620            })?;
13621            let location = match location_task {
13622                Some(task) => Some({
13623                    let target_buffer_handle = task.await.context("open local buffer")?;
13624                    let range = target_buffer_handle.update(cx, |target_buffer, _| {
13625                        let target_start = target_buffer
13626                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13627                        let target_end = target_buffer
13628                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13629                        target_buffer.anchor_after(target_start)
13630                            ..target_buffer.anchor_before(target_end)
13631                    })?;
13632                    Location {
13633                        buffer: target_buffer_handle,
13634                        range,
13635                    }
13636                }),
13637                None => None,
13638            };
13639            Ok(location)
13640        })
13641    }
13642
13643    pub fn find_all_references(
13644        &mut self,
13645        _: &FindAllReferences,
13646        window: &mut Window,
13647        cx: &mut Context<Self>,
13648    ) -> Option<Task<Result<Navigated>>> {
13649        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
13650
13651        let selection = self.selections.newest::<usize>(cx);
13652        let multi_buffer = self.buffer.read(cx);
13653        let head = selection.head();
13654
13655        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13656        let head_anchor = multi_buffer_snapshot.anchor_at(
13657            head,
13658            if head < selection.tail() {
13659                Bias::Right
13660            } else {
13661                Bias::Left
13662            },
13663        );
13664
13665        match self
13666            .find_all_references_task_sources
13667            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13668        {
13669            Ok(_) => {
13670                log::info!(
13671                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
13672                );
13673                return None;
13674            }
13675            Err(i) => {
13676                self.find_all_references_task_sources.insert(i, head_anchor);
13677            }
13678        }
13679
13680        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13681        let workspace = self.workspace()?;
13682        let project = workspace.read(cx).project().clone();
13683        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13684        Some(cx.spawn_in(window, async move |editor, cx| {
13685            let _cleanup = cx.on_drop(&editor, move |editor, _| {
13686                if let Ok(i) = editor
13687                    .find_all_references_task_sources
13688                    .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13689                {
13690                    editor.find_all_references_task_sources.remove(i);
13691                }
13692            });
13693
13694            let locations = references.await?;
13695            if locations.is_empty() {
13696                return anyhow::Ok(Navigated::No);
13697            }
13698
13699            workspace.update_in(cx, |workspace, window, cx| {
13700                let title = locations
13701                    .first()
13702                    .as_ref()
13703                    .map(|location| {
13704                        let buffer = location.buffer.read(cx);
13705                        format!(
13706                            "References to `{}`",
13707                            buffer
13708                                .text_for_range(location.range.clone())
13709                                .collect::<String>()
13710                        )
13711                    })
13712                    .unwrap();
13713                Self::open_locations_in_multibuffer(
13714                    workspace,
13715                    locations,
13716                    title,
13717                    false,
13718                    MultibufferSelectionMode::First,
13719                    window,
13720                    cx,
13721                );
13722                Navigated::Yes
13723            })
13724        }))
13725    }
13726
13727    /// Opens a multibuffer with the given project locations in it
13728    pub fn open_locations_in_multibuffer(
13729        workspace: &mut Workspace,
13730        mut locations: Vec<Location>,
13731        title: String,
13732        split: bool,
13733        multibuffer_selection_mode: MultibufferSelectionMode,
13734        window: &mut Window,
13735        cx: &mut Context<Workspace>,
13736    ) {
13737        // If there are multiple definitions, open them in a multibuffer
13738        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13739        let mut locations = locations.into_iter().peekable();
13740        let mut ranges: Vec<Range<Anchor>> = Vec::new();
13741        let capability = workspace.project().read(cx).capability();
13742
13743        let excerpt_buffer = cx.new(|cx| {
13744            let mut multibuffer = MultiBuffer::new(capability);
13745            while let Some(location) = locations.next() {
13746                let buffer = location.buffer.read(cx);
13747                let mut ranges_for_buffer = Vec::new();
13748                let range = location.range.to_point(buffer);
13749                ranges_for_buffer.push(range.clone());
13750
13751                while let Some(next_location) = locations.peek() {
13752                    if next_location.buffer == location.buffer {
13753                        ranges_for_buffer.push(next_location.range.to_point(buffer));
13754                        locations.next();
13755                    } else {
13756                        break;
13757                    }
13758                }
13759
13760                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
13761                let (new_ranges, _) = multibuffer.set_excerpts_for_path(
13762                    PathKey::for_buffer(&location.buffer, cx),
13763                    location.buffer.clone(),
13764                    ranges_for_buffer,
13765                    DEFAULT_MULTIBUFFER_CONTEXT,
13766                    cx,
13767                );
13768                ranges.extend(new_ranges)
13769            }
13770
13771            multibuffer.with_title(title)
13772        });
13773
13774        let editor = cx.new(|cx| {
13775            Editor::for_multibuffer(
13776                excerpt_buffer,
13777                Some(workspace.project().clone()),
13778                window,
13779                cx,
13780            )
13781        });
13782        editor.update(cx, |editor, cx| {
13783            match multibuffer_selection_mode {
13784                MultibufferSelectionMode::First => {
13785                    if let Some(first_range) = ranges.first() {
13786                        editor.change_selections(None, window, cx, |selections| {
13787                            selections.clear_disjoint();
13788                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
13789                        });
13790                    }
13791                    editor.highlight_background::<Self>(
13792                        &ranges,
13793                        |theme| theme.editor_highlighted_line_background,
13794                        cx,
13795                    );
13796                }
13797                MultibufferSelectionMode::All => {
13798                    editor.change_selections(None, window, cx, |selections| {
13799                        selections.clear_disjoint();
13800                        selections.select_anchor_ranges(ranges);
13801                    });
13802                }
13803            }
13804            editor.register_buffers_with_language_servers(cx);
13805        });
13806
13807        let item = Box::new(editor);
13808        let item_id = item.item_id();
13809
13810        if split {
13811            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
13812        } else {
13813            if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
13814                let (preview_item_id, preview_item_idx) =
13815                    workspace.active_pane().update(cx, |pane, _| {
13816                        (pane.preview_item_id(), pane.preview_item_idx())
13817                    });
13818
13819                workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
13820
13821                if let Some(preview_item_id) = preview_item_id {
13822                    workspace.active_pane().update(cx, |pane, cx| {
13823                        pane.remove_item(preview_item_id, false, false, window, cx);
13824                    });
13825                }
13826            } else {
13827                workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
13828            }
13829        }
13830        workspace.active_pane().update(cx, |pane, cx| {
13831            pane.set_preview_item_id(Some(item_id), cx);
13832        });
13833    }
13834
13835    pub fn rename(
13836        &mut self,
13837        _: &Rename,
13838        window: &mut Window,
13839        cx: &mut Context<Self>,
13840    ) -> Option<Task<Result<()>>> {
13841        use language::ToOffset as _;
13842
13843        let provider = self.semantics_provider.clone()?;
13844        let selection = self.selections.newest_anchor().clone();
13845        let (cursor_buffer, cursor_buffer_position) = self
13846            .buffer
13847            .read(cx)
13848            .text_anchor_for_position(selection.head(), cx)?;
13849        let (tail_buffer, cursor_buffer_position_end) = self
13850            .buffer
13851            .read(cx)
13852            .text_anchor_for_position(selection.tail(), cx)?;
13853        if tail_buffer != cursor_buffer {
13854            return None;
13855        }
13856
13857        let snapshot = cursor_buffer.read(cx).snapshot();
13858        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
13859        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
13860        let prepare_rename = provider
13861            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
13862            .unwrap_or_else(|| Task::ready(Ok(None)));
13863        drop(snapshot);
13864
13865        Some(cx.spawn_in(window, async move |this, cx| {
13866            let rename_range = if let Some(range) = prepare_rename.await? {
13867                Some(range)
13868            } else {
13869                this.update(cx, |this, cx| {
13870                    let buffer = this.buffer.read(cx).snapshot(cx);
13871                    let mut buffer_highlights = this
13872                        .document_highlights_for_position(selection.head(), &buffer)
13873                        .filter(|highlight| {
13874                            highlight.start.excerpt_id == selection.head().excerpt_id
13875                                && highlight.end.excerpt_id == selection.head().excerpt_id
13876                        });
13877                    buffer_highlights
13878                        .next()
13879                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
13880                })?
13881            };
13882            if let Some(rename_range) = rename_range {
13883                this.update_in(cx, |this, window, cx| {
13884                    let snapshot = cursor_buffer.read(cx).snapshot();
13885                    let rename_buffer_range = rename_range.to_offset(&snapshot);
13886                    let cursor_offset_in_rename_range =
13887                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
13888                    let cursor_offset_in_rename_range_end =
13889                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
13890
13891                    this.take_rename(false, window, cx);
13892                    let buffer = this.buffer.read(cx).read(cx);
13893                    let cursor_offset = selection.head().to_offset(&buffer);
13894                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
13895                    let rename_end = rename_start + rename_buffer_range.len();
13896                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
13897                    let mut old_highlight_id = None;
13898                    let old_name: Arc<str> = buffer
13899                        .chunks(rename_start..rename_end, true)
13900                        .map(|chunk| {
13901                            if old_highlight_id.is_none() {
13902                                old_highlight_id = chunk.syntax_highlight_id;
13903                            }
13904                            chunk.text
13905                        })
13906                        .collect::<String>()
13907                        .into();
13908
13909                    drop(buffer);
13910
13911                    // Position the selection in the rename editor so that it matches the current selection.
13912                    this.show_local_selections = false;
13913                    let rename_editor = cx.new(|cx| {
13914                        let mut editor = Editor::single_line(window, cx);
13915                        editor.buffer.update(cx, |buffer, cx| {
13916                            buffer.edit([(0..0, old_name.clone())], None, cx)
13917                        });
13918                        let rename_selection_range = match cursor_offset_in_rename_range
13919                            .cmp(&cursor_offset_in_rename_range_end)
13920                        {
13921                            Ordering::Equal => {
13922                                editor.select_all(&SelectAll, window, cx);
13923                                return editor;
13924                            }
13925                            Ordering::Less => {
13926                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
13927                            }
13928                            Ordering::Greater => {
13929                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
13930                            }
13931                        };
13932                        if rename_selection_range.end > old_name.len() {
13933                            editor.select_all(&SelectAll, window, cx);
13934                        } else {
13935                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13936                                s.select_ranges([rename_selection_range]);
13937                            });
13938                        }
13939                        editor
13940                    });
13941                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
13942                        if e == &EditorEvent::Focused {
13943                            cx.emit(EditorEvent::FocusedIn)
13944                        }
13945                    })
13946                    .detach();
13947
13948                    let write_highlights =
13949                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
13950                    let read_highlights =
13951                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
13952                    let ranges = write_highlights
13953                        .iter()
13954                        .flat_map(|(_, ranges)| ranges.iter())
13955                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
13956                        .cloned()
13957                        .collect();
13958
13959                    this.highlight_text::<Rename>(
13960                        ranges,
13961                        HighlightStyle {
13962                            fade_out: Some(0.6),
13963                            ..Default::default()
13964                        },
13965                        cx,
13966                    );
13967                    let rename_focus_handle = rename_editor.focus_handle(cx);
13968                    window.focus(&rename_focus_handle);
13969                    let block_id = this.insert_blocks(
13970                        [BlockProperties {
13971                            style: BlockStyle::Flex,
13972                            placement: BlockPlacement::Below(range.start),
13973                            height: Some(1),
13974                            render: Arc::new({
13975                                let rename_editor = rename_editor.clone();
13976                                move |cx: &mut BlockContext| {
13977                                    let mut text_style = cx.editor_style.text.clone();
13978                                    if let Some(highlight_style) = old_highlight_id
13979                                        .and_then(|h| h.style(&cx.editor_style.syntax))
13980                                    {
13981                                        text_style = text_style.highlight(highlight_style);
13982                                    }
13983                                    div()
13984                                        .block_mouse_down()
13985                                        .pl(cx.anchor_x)
13986                                        .child(EditorElement::new(
13987                                            &rename_editor,
13988                                            EditorStyle {
13989                                                background: cx.theme().system().transparent,
13990                                                local_player: cx.editor_style.local_player,
13991                                                text: text_style,
13992                                                scrollbar_width: cx.editor_style.scrollbar_width,
13993                                                syntax: cx.editor_style.syntax.clone(),
13994                                                status: cx.editor_style.status.clone(),
13995                                                inlay_hints_style: HighlightStyle {
13996                                                    font_weight: Some(FontWeight::BOLD),
13997                                                    ..make_inlay_hints_style(cx.app)
13998                                                },
13999                                                inline_completion_styles: make_suggestion_styles(
14000                                                    cx.app,
14001                                                ),
14002                                                ..EditorStyle::default()
14003                                            },
14004                                        ))
14005                                        .into_any_element()
14006                                }
14007                            }),
14008                            priority: 0,
14009                        }],
14010                        Some(Autoscroll::fit()),
14011                        cx,
14012                    )[0];
14013                    this.pending_rename = Some(RenameState {
14014                        range,
14015                        old_name,
14016                        editor: rename_editor,
14017                        block_id,
14018                    });
14019                })?;
14020            }
14021
14022            Ok(())
14023        }))
14024    }
14025
14026    pub fn confirm_rename(
14027        &mut self,
14028        _: &ConfirmRename,
14029        window: &mut Window,
14030        cx: &mut Context<Self>,
14031    ) -> Option<Task<Result<()>>> {
14032        let rename = self.take_rename(false, window, cx)?;
14033        let workspace = self.workspace()?.downgrade();
14034        let (buffer, start) = self
14035            .buffer
14036            .read(cx)
14037            .text_anchor_for_position(rename.range.start, cx)?;
14038        let (end_buffer, _) = self
14039            .buffer
14040            .read(cx)
14041            .text_anchor_for_position(rename.range.end, cx)?;
14042        if buffer != end_buffer {
14043            return None;
14044        }
14045
14046        let old_name = rename.old_name;
14047        let new_name = rename.editor.read(cx).text(cx);
14048
14049        let rename = self.semantics_provider.as_ref()?.perform_rename(
14050            &buffer,
14051            start,
14052            new_name.clone(),
14053            cx,
14054        )?;
14055
14056        Some(cx.spawn_in(window, async move |editor, cx| {
14057            let project_transaction = rename.await?;
14058            Self::open_project_transaction(
14059                &editor,
14060                workspace,
14061                project_transaction,
14062                format!("Rename: {}{}", old_name, new_name),
14063                cx,
14064            )
14065            .await?;
14066
14067            editor.update(cx, |editor, cx| {
14068                editor.refresh_document_highlights(cx);
14069            })?;
14070            Ok(())
14071        }))
14072    }
14073
14074    fn take_rename(
14075        &mut self,
14076        moving_cursor: bool,
14077        window: &mut Window,
14078        cx: &mut Context<Self>,
14079    ) -> Option<RenameState> {
14080        let rename = self.pending_rename.take()?;
14081        if rename.editor.focus_handle(cx).is_focused(window) {
14082            window.focus(&self.focus_handle);
14083        }
14084
14085        self.remove_blocks(
14086            [rename.block_id].into_iter().collect(),
14087            Some(Autoscroll::fit()),
14088            cx,
14089        );
14090        self.clear_highlights::<Rename>(cx);
14091        self.show_local_selections = true;
14092
14093        if moving_cursor {
14094            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14095                editor.selections.newest::<usize>(cx).head()
14096            });
14097
14098            // Update the selection to match the position of the selection inside
14099            // the rename editor.
14100            let snapshot = self.buffer.read(cx).read(cx);
14101            let rename_range = rename.range.to_offset(&snapshot);
14102            let cursor_in_editor = snapshot
14103                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14104                .min(rename_range.end);
14105            drop(snapshot);
14106
14107            self.change_selections(None, window, cx, |s| {
14108                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14109            });
14110        } else {
14111            self.refresh_document_highlights(cx);
14112        }
14113
14114        Some(rename)
14115    }
14116
14117    pub fn pending_rename(&self) -> Option<&RenameState> {
14118        self.pending_rename.as_ref()
14119    }
14120
14121    fn format(
14122        &mut self,
14123        _: &Format,
14124        window: &mut Window,
14125        cx: &mut Context<Self>,
14126    ) -> Option<Task<Result<()>>> {
14127        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14128
14129        let project = match &self.project {
14130            Some(project) => project.clone(),
14131            None => return None,
14132        };
14133
14134        Some(self.perform_format(
14135            project,
14136            FormatTrigger::Manual,
14137            FormatTarget::Buffers,
14138            window,
14139            cx,
14140        ))
14141    }
14142
14143    fn format_selections(
14144        &mut self,
14145        _: &FormatSelections,
14146        window: &mut Window,
14147        cx: &mut Context<Self>,
14148    ) -> Option<Task<Result<()>>> {
14149        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14150
14151        let project = match &self.project {
14152            Some(project) => project.clone(),
14153            None => return None,
14154        };
14155
14156        let ranges = self
14157            .selections
14158            .all_adjusted(cx)
14159            .into_iter()
14160            .map(|selection| selection.range())
14161            .collect_vec();
14162
14163        Some(self.perform_format(
14164            project,
14165            FormatTrigger::Manual,
14166            FormatTarget::Ranges(ranges),
14167            window,
14168            cx,
14169        ))
14170    }
14171
14172    fn perform_format(
14173        &mut self,
14174        project: Entity<Project>,
14175        trigger: FormatTrigger,
14176        target: FormatTarget,
14177        window: &mut Window,
14178        cx: &mut Context<Self>,
14179    ) -> Task<Result<()>> {
14180        let buffer = self.buffer.clone();
14181        let (buffers, target) = match target {
14182            FormatTarget::Buffers => {
14183                let mut buffers = buffer.read(cx).all_buffers();
14184                if trigger == FormatTrigger::Save {
14185                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
14186                }
14187                (buffers, LspFormatTarget::Buffers)
14188            }
14189            FormatTarget::Ranges(selection_ranges) => {
14190                let multi_buffer = buffer.read(cx);
14191                let snapshot = multi_buffer.read(cx);
14192                let mut buffers = HashSet::default();
14193                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14194                    BTreeMap::new();
14195                for selection_range in selection_ranges {
14196                    for (buffer, buffer_range, _) in
14197                        snapshot.range_to_buffer_ranges(selection_range)
14198                    {
14199                        let buffer_id = buffer.remote_id();
14200                        let start = buffer.anchor_before(buffer_range.start);
14201                        let end = buffer.anchor_after(buffer_range.end);
14202                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14203                        buffer_id_to_ranges
14204                            .entry(buffer_id)
14205                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14206                            .or_insert_with(|| vec![start..end]);
14207                    }
14208                }
14209                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14210            }
14211        };
14212
14213        let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14214        let selections_prev = transaction_id_prev
14215            .and_then(|transaction_id_prev| {
14216                // default to selections as they were after the last edit, if we have them,
14217                // instead of how they are now.
14218                // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14219                // will take you back to where you made the last edit, instead of staying where you scrolled
14220                self.selection_history
14221                    .transaction(transaction_id_prev)
14222                    .map(|t| t.0.clone())
14223            })
14224            .unwrap_or_else(|| {
14225                log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14226                self.selections.disjoint_anchors()
14227            });
14228
14229        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14230        let format = project.update(cx, |project, cx| {
14231            project.format(buffers, target, true, trigger, cx)
14232        });
14233
14234        cx.spawn_in(window, async move |editor, cx| {
14235            let transaction = futures::select_biased! {
14236                transaction = format.log_err().fuse() => transaction,
14237                () = timeout => {
14238                    log::warn!("timed out waiting for formatting");
14239                    None
14240                }
14241            };
14242
14243            buffer
14244                .update(cx, |buffer, cx| {
14245                    if let Some(transaction) = transaction {
14246                        if !buffer.is_singleton() {
14247                            buffer.push_transaction(&transaction.0, cx);
14248                        }
14249                    }
14250                    cx.notify();
14251                })
14252                .ok();
14253
14254            if let Some(transaction_id_now) =
14255                buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14256            {
14257                let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14258                if has_new_transaction {
14259                    _ = editor.update(cx, |editor, _| {
14260                        editor
14261                            .selection_history
14262                            .insert_transaction(transaction_id_now, selections_prev);
14263                    });
14264                }
14265            }
14266
14267            Ok(())
14268        })
14269    }
14270
14271    fn organize_imports(
14272        &mut self,
14273        _: &OrganizeImports,
14274        window: &mut Window,
14275        cx: &mut Context<Self>,
14276    ) -> Option<Task<Result<()>>> {
14277        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14278        let project = match &self.project {
14279            Some(project) => project.clone(),
14280            None => return None,
14281        };
14282        Some(self.perform_code_action_kind(
14283            project,
14284            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14285            window,
14286            cx,
14287        ))
14288    }
14289
14290    fn perform_code_action_kind(
14291        &mut self,
14292        project: Entity<Project>,
14293        kind: CodeActionKind,
14294        window: &mut Window,
14295        cx: &mut Context<Self>,
14296    ) -> Task<Result<()>> {
14297        let buffer = self.buffer.clone();
14298        let buffers = buffer.read(cx).all_buffers();
14299        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14300        let apply_action = project.update(cx, |project, cx| {
14301            project.apply_code_action_kind(buffers, kind, true, cx)
14302        });
14303        cx.spawn_in(window, async move |_, cx| {
14304            let transaction = futures::select_biased! {
14305                () = timeout => {
14306                    log::warn!("timed out waiting for executing code action");
14307                    None
14308                }
14309                transaction = apply_action.log_err().fuse() => transaction,
14310            };
14311            buffer
14312                .update(cx, |buffer, cx| {
14313                    // check if we need this
14314                    if let Some(transaction) = transaction {
14315                        if !buffer.is_singleton() {
14316                            buffer.push_transaction(&transaction.0, cx);
14317                        }
14318                    }
14319                    cx.notify();
14320                })
14321                .ok();
14322            Ok(())
14323        })
14324    }
14325
14326    fn restart_language_server(
14327        &mut self,
14328        _: &RestartLanguageServer,
14329        _: &mut Window,
14330        cx: &mut Context<Self>,
14331    ) {
14332        if let Some(project) = self.project.clone() {
14333            self.buffer.update(cx, |multi_buffer, cx| {
14334                project.update(cx, |project, cx| {
14335                    project.restart_language_servers_for_buffers(
14336                        multi_buffer.all_buffers().into_iter().collect(),
14337                        cx,
14338                    );
14339                });
14340            })
14341        }
14342    }
14343
14344    fn stop_language_server(
14345        &mut self,
14346        _: &StopLanguageServer,
14347        _: &mut Window,
14348        cx: &mut Context<Self>,
14349    ) {
14350        if let Some(project) = self.project.clone() {
14351            self.buffer.update(cx, |multi_buffer, cx| {
14352                project.update(cx, |project, cx| {
14353                    project.stop_language_servers_for_buffers(
14354                        multi_buffer.all_buffers().into_iter().collect(),
14355                        cx,
14356                    );
14357                    cx.emit(project::Event::RefreshInlayHints);
14358                });
14359            });
14360        }
14361    }
14362
14363    fn cancel_language_server_work(
14364        workspace: &mut Workspace,
14365        _: &actions::CancelLanguageServerWork,
14366        _: &mut Window,
14367        cx: &mut Context<Workspace>,
14368    ) {
14369        let project = workspace.project();
14370        let buffers = workspace
14371            .active_item(cx)
14372            .and_then(|item| item.act_as::<Editor>(cx))
14373            .map_or(HashSet::default(), |editor| {
14374                editor.read(cx).buffer.read(cx).all_buffers()
14375            });
14376        project.update(cx, |project, cx| {
14377            project.cancel_language_server_work_for_buffers(buffers, cx);
14378        });
14379    }
14380
14381    fn show_character_palette(
14382        &mut self,
14383        _: &ShowCharacterPalette,
14384        window: &mut Window,
14385        _: &mut Context<Self>,
14386    ) {
14387        window.show_character_palette();
14388    }
14389
14390    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14391        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
14392            let buffer = self.buffer.read(cx).snapshot(cx);
14393            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
14394            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
14395            let is_valid = buffer
14396                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14397                .any(|entry| {
14398                    entry.diagnostic.is_primary
14399                        && !entry.range.is_empty()
14400                        && entry.range.start == primary_range_start
14401                        && entry.diagnostic.message == active_diagnostics.primary_message
14402                });
14403
14404            if is_valid != active_diagnostics.is_valid {
14405                active_diagnostics.is_valid = is_valid;
14406                if is_valid {
14407                    let mut new_styles = HashMap::default();
14408                    for (block_id, diagnostic) in &active_diagnostics.blocks {
14409                        new_styles.insert(
14410                            *block_id,
14411                            diagnostic_block_renderer(diagnostic.clone(), None, true),
14412                        );
14413                    }
14414                    self.display_map.update(cx, |display_map, _cx| {
14415                        display_map.replace_blocks(new_styles);
14416                    });
14417                } else {
14418                    self.dismiss_diagnostics(cx);
14419                }
14420            }
14421        }
14422    }
14423
14424    fn activate_diagnostics(
14425        &mut self,
14426        buffer_id: BufferId,
14427        group_id: usize,
14428        window: &mut Window,
14429        cx: &mut Context<Self>,
14430    ) {
14431        self.dismiss_diagnostics(cx);
14432        let snapshot = self.snapshot(window, cx);
14433        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
14434            let buffer = self.buffer.read(cx).snapshot(cx);
14435
14436            let mut primary_range = None;
14437            let mut primary_message = None;
14438            let diagnostic_group = buffer
14439                .diagnostic_group(buffer_id, group_id)
14440                .filter_map(|entry| {
14441                    let start = entry.range.start;
14442                    let end = entry.range.end;
14443                    if snapshot.is_line_folded(MultiBufferRow(start.row))
14444                        && (start.row == end.row
14445                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
14446                    {
14447                        return None;
14448                    }
14449                    if entry.diagnostic.is_primary {
14450                        primary_range = Some(entry.range.clone());
14451                        primary_message = Some(entry.diagnostic.message.clone());
14452                    }
14453                    Some(entry)
14454                })
14455                .collect::<Vec<_>>();
14456            let primary_range = primary_range?;
14457            let primary_message = primary_message?;
14458
14459            let blocks = display_map
14460                .insert_blocks(
14461                    diagnostic_group.iter().map(|entry| {
14462                        let diagnostic = entry.diagnostic.clone();
14463                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
14464                        BlockProperties {
14465                            style: BlockStyle::Fixed,
14466                            placement: BlockPlacement::Below(
14467                                buffer.anchor_after(entry.range.start),
14468                            ),
14469                            height: Some(message_height),
14470                            render: diagnostic_block_renderer(diagnostic, None, true),
14471                            priority: 0,
14472                        }
14473                    }),
14474                    cx,
14475                )
14476                .into_iter()
14477                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
14478                .collect();
14479
14480            Some(ActiveDiagnosticGroup {
14481                primary_range: buffer.anchor_before(primary_range.start)
14482                    ..buffer.anchor_after(primary_range.end),
14483                primary_message,
14484                group_id,
14485                blocks,
14486                is_valid: true,
14487            })
14488        });
14489    }
14490
14491    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14492        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
14493            self.display_map.update(cx, |display_map, cx| {
14494                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
14495            });
14496            cx.notify();
14497        }
14498    }
14499
14500    /// Disable inline diagnostics rendering for this editor.
14501    pub fn disable_inline_diagnostics(&mut self) {
14502        self.inline_diagnostics_enabled = false;
14503        self.inline_diagnostics_update = Task::ready(());
14504        self.inline_diagnostics.clear();
14505    }
14506
14507    pub fn inline_diagnostics_enabled(&self) -> bool {
14508        self.inline_diagnostics_enabled
14509    }
14510
14511    pub fn show_inline_diagnostics(&self) -> bool {
14512        self.show_inline_diagnostics
14513    }
14514
14515    pub fn toggle_inline_diagnostics(
14516        &mut self,
14517        _: &ToggleInlineDiagnostics,
14518        window: &mut Window,
14519        cx: &mut Context<Editor>,
14520    ) {
14521        self.show_inline_diagnostics = !self.show_inline_diagnostics;
14522        self.refresh_inline_diagnostics(false, window, cx);
14523    }
14524
14525    fn refresh_inline_diagnostics(
14526        &mut self,
14527        debounce: bool,
14528        window: &mut Window,
14529        cx: &mut Context<Self>,
14530    ) {
14531        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14532            self.inline_diagnostics_update = Task::ready(());
14533            self.inline_diagnostics.clear();
14534            return;
14535        }
14536
14537        let debounce_ms = ProjectSettings::get_global(cx)
14538            .diagnostics
14539            .inline
14540            .update_debounce_ms;
14541        let debounce = if debounce && debounce_ms > 0 {
14542            Some(Duration::from_millis(debounce_ms))
14543        } else {
14544            None
14545        };
14546        self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14547            if let Some(debounce) = debounce {
14548                cx.background_executor().timer(debounce).await;
14549            }
14550            let Some(snapshot) = editor
14551                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14552                .ok()
14553            else {
14554                return;
14555            };
14556
14557            let new_inline_diagnostics = cx
14558                .background_spawn(async move {
14559                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14560                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14561                        let message = diagnostic_entry
14562                            .diagnostic
14563                            .message
14564                            .split_once('\n')
14565                            .map(|(line, _)| line)
14566                            .map(SharedString::new)
14567                            .unwrap_or_else(|| {
14568                                SharedString::from(diagnostic_entry.diagnostic.message)
14569                            });
14570                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14571                        let (Ok(i) | Err(i)) = inline_diagnostics
14572                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14573                        inline_diagnostics.insert(
14574                            i,
14575                            (
14576                                start_anchor,
14577                                InlineDiagnostic {
14578                                    message,
14579                                    group_id: diagnostic_entry.diagnostic.group_id,
14580                                    start: diagnostic_entry.range.start.to_point(&snapshot),
14581                                    is_primary: diagnostic_entry.diagnostic.is_primary,
14582                                    severity: diagnostic_entry.diagnostic.severity,
14583                                },
14584                            ),
14585                        );
14586                    }
14587                    inline_diagnostics
14588                })
14589                .await;
14590
14591            editor
14592                .update(cx, |editor, cx| {
14593                    editor.inline_diagnostics = new_inline_diagnostics;
14594                    cx.notify();
14595                })
14596                .ok();
14597        });
14598    }
14599
14600    pub fn set_selections_from_remote(
14601        &mut self,
14602        selections: Vec<Selection<Anchor>>,
14603        pending_selection: Option<Selection<Anchor>>,
14604        window: &mut Window,
14605        cx: &mut Context<Self>,
14606    ) {
14607        let old_cursor_position = self.selections.newest_anchor().head();
14608        self.selections.change_with(cx, |s| {
14609            s.select_anchors(selections);
14610            if let Some(pending_selection) = pending_selection {
14611                s.set_pending(pending_selection, SelectMode::Character);
14612            } else {
14613                s.clear_pending();
14614            }
14615        });
14616        self.selections_did_change(false, &old_cursor_position, true, window, cx);
14617    }
14618
14619    fn push_to_selection_history(&mut self) {
14620        self.selection_history.push(SelectionHistoryEntry {
14621            selections: self.selections.disjoint_anchors(),
14622            select_next_state: self.select_next_state.clone(),
14623            select_prev_state: self.select_prev_state.clone(),
14624            add_selections_state: self.add_selections_state.clone(),
14625        });
14626    }
14627
14628    pub fn transact(
14629        &mut self,
14630        window: &mut Window,
14631        cx: &mut Context<Self>,
14632        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14633    ) -> Option<TransactionId> {
14634        self.start_transaction_at(Instant::now(), window, cx);
14635        update(self, window, cx);
14636        self.end_transaction_at(Instant::now(), cx)
14637    }
14638
14639    pub fn start_transaction_at(
14640        &mut self,
14641        now: Instant,
14642        window: &mut Window,
14643        cx: &mut Context<Self>,
14644    ) {
14645        self.end_selection(window, cx);
14646        if let Some(tx_id) = self
14647            .buffer
14648            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14649        {
14650            self.selection_history
14651                .insert_transaction(tx_id, self.selections.disjoint_anchors());
14652            cx.emit(EditorEvent::TransactionBegun {
14653                transaction_id: tx_id,
14654            })
14655        }
14656    }
14657
14658    pub fn end_transaction_at(
14659        &mut self,
14660        now: Instant,
14661        cx: &mut Context<Self>,
14662    ) -> Option<TransactionId> {
14663        if let Some(transaction_id) = self
14664            .buffer
14665            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14666        {
14667            if let Some((_, end_selections)) =
14668                self.selection_history.transaction_mut(transaction_id)
14669            {
14670                *end_selections = Some(self.selections.disjoint_anchors());
14671            } else {
14672                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14673            }
14674
14675            cx.emit(EditorEvent::Edited { transaction_id });
14676            Some(transaction_id)
14677        } else {
14678            None
14679        }
14680    }
14681
14682    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14683        if self.selection_mark_mode {
14684            self.change_selections(None, window, cx, |s| {
14685                s.move_with(|_, sel| {
14686                    sel.collapse_to(sel.head(), SelectionGoal::None);
14687                });
14688            })
14689        }
14690        self.selection_mark_mode = true;
14691        cx.notify();
14692    }
14693
14694    pub fn swap_selection_ends(
14695        &mut self,
14696        _: &actions::SwapSelectionEnds,
14697        window: &mut Window,
14698        cx: &mut Context<Self>,
14699    ) {
14700        self.change_selections(None, window, cx, |s| {
14701            s.move_with(|_, sel| {
14702                if sel.start != sel.end {
14703                    sel.reversed = !sel.reversed
14704                }
14705            });
14706        });
14707        self.request_autoscroll(Autoscroll::newest(), cx);
14708        cx.notify();
14709    }
14710
14711    pub fn toggle_fold(
14712        &mut self,
14713        _: &actions::ToggleFold,
14714        window: &mut Window,
14715        cx: &mut Context<Self>,
14716    ) {
14717        if self.is_singleton(cx) {
14718            let selection = self.selections.newest::<Point>(cx);
14719
14720            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14721            let range = if selection.is_empty() {
14722                let point = selection.head().to_display_point(&display_map);
14723                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14724                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14725                    .to_point(&display_map);
14726                start..end
14727            } else {
14728                selection.range()
14729            };
14730            if display_map.folds_in_range(range).next().is_some() {
14731                self.unfold_lines(&Default::default(), window, cx)
14732            } else {
14733                self.fold(&Default::default(), window, cx)
14734            }
14735        } else {
14736            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14737            let buffer_ids: HashSet<_> = self
14738                .selections
14739                .disjoint_anchor_ranges()
14740                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14741                .collect();
14742
14743            let should_unfold = buffer_ids
14744                .iter()
14745                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14746
14747            for buffer_id in buffer_ids {
14748                if should_unfold {
14749                    self.unfold_buffer(buffer_id, cx);
14750                } else {
14751                    self.fold_buffer(buffer_id, cx);
14752                }
14753            }
14754        }
14755    }
14756
14757    pub fn toggle_fold_recursive(
14758        &mut self,
14759        _: &actions::ToggleFoldRecursive,
14760        window: &mut Window,
14761        cx: &mut Context<Self>,
14762    ) {
14763        let selection = self.selections.newest::<Point>(cx);
14764
14765        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14766        let range = if selection.is_empty() {
14767            let point = selection.head().to_display_point(&display_map);
14768            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14769            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14770                .to_point(&display_map);
14771            start..end
14772        } else {
14773            selection.range()
14774        };
14775        if display_map.folds_in_range(range).next().is_some() {
14776            self.unfold_recursive(&Default::default(), window, cx)
14777        } else {
14778            self.fold_recursive(&Default::default(), window, cx)
14779        }
14780    }
14781
14782    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
14783        if self.is_singleton(cx) {
14784            let mut to_fold = Vec::new();
14785            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14786            let selections = self.selections.all_adjusted(cx);
14787
14788            for selection in selections {
14789                let range = selection.range().sorted();
14790                let buffer_start_row = range.start.row;
14791
14792                if range.start.row != range.end.row {
14793                    let mut found = false;
14794                    let mut row = range.start.row;
14795                    while row <= range.end.row {
14796                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
14797                        {
14798                            found = true;
14799                            row = crease.range().end.row + 1;
14800                            to_fold.push(crease);
14801                        } else {
14802                            row += 1
14803                        }
14804                    }
14805                    if found {
14806                        continue;
14807                    }
14808                }
14809
14810                for row in (0..=range.start.row).rev() {
14811                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14812                        if crease.range().end.row >= buffer_start_row {
14813                            to_fold.push(crease);
14814                            if row <= range.start.row {
14815                                break;
14816                            }
14817                        }
14818                    }
14819                }
14820            }
14821
14822            self.fold_creases(to_fold, true, window, cx);
14823        } else {
14824            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14825            let buffer_ids = self
14826                .selections
14827                .disjoint_anchor_ranges()
14828                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14829                .collect::<HashSet<_>>();
14830            for buffer_id in buffer_ids {
14831                self.fold_buffer(buffer_id, cx);
14832            }
14833        }
14834    }
14835
14836    fn fold_at_level(
14837        &mut self,
14838        fold_at: &FoldAtLevel,
14839        window: &mut Window,
14840        cx: &mut Context<Self>,
14841    ) {
14842        if !self.buffer.read(cx).is_singleton() {
14843            return;
14844        }
14845
14846        let fold_at_level = fold_at.0;
14847        let snapshot = self.buffer.read(cx).snapshot(cx);
14848        let mut to_fold = Vec::new();
14849        let mut stack = vec![(0, snapshot.max_row().0, 1)];
14850
14851        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
14852            while start_row < end_row {
14853                match self
14854                    .snapshot(window, cx)
14855                    .crease_for_buffer_row(MultiBufferRow(start_row))
14856                {
14857                    Some(crease) => {
14858                        let nested_start_row = crease.range().start.row + 1;
14859                        let nested_end_row = crease.range().end.row;
14860
14861                        if current_level < fold_at_level {
14862                            stack.push((nested_start_row, nested_end_row, current_level + 1));
14863                        } else if current_level == fold_at_level {
14864                            to_fold.push(crease);
14865                        }
14866
14867                        start_row = nested_end_row + 1;
14868                    }
14869                    None => start_row += 1,
14870                }
14871            }
14872        }
14873
14874        self.fold_creases(to_fold, true, window, cx);
14875    }
14876
14877    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
14878        if self.buffer.read(cx).is_singleton() {
14879            let mut fold_ranges = Vec::new();
14880            let snapshot = self.buffer.read(cx).snapshot(cx);
14881
14882            for row in 0..snapshot.max_row().0 {
14883                if let Some(foldable_range) = self
14884                    .snapshot(window, cx)
14885                    .crease_for_buffer_row(MultiBufferRow(row))
14886                {
14887                    fold_ranges.push(foldable_range);
14888                }
14889            }
14890
14891            self.fold_creases(fold_ranges, true, window, cx);
14892        } else {
14893            self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
14894                editor
14895                    .update_in(cx, |editor, _, cx| {
14896                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14897                            editor.fold_buffer(buffer_id, cx);
14898                        }
14899                    })
14900                    .ok();
14901            });
14902        }
14903    }
14904
14905    pub fn fold_function_bodies(
14906        &mut self,
14907        _: &actions::FoldFunctionBodies,
14908        window: &mut Window,
14909        cx: &mut Context<Self>,
14910    ) {
14911        let snapshot = self.buffer.read(cx).snapshot(cx);
14912
14913        let ranges = snapshot
14914            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
14915            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
14916            .collect::<Vec<_>>();
14917
14918        let creases = ranges
14919            .into_iter()
14920            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
14921            .collect();
14922
14923        self.fold_creases(creases, true, window, cx);
14924    }
14925
14926    pub fn fold_recursive(
14927        &mut self,
14928        _: &actions::FoldRecursive,
14929        window: &mut Window,
14930        cx: &mut Context<Self>,
14931    ) {
14932        let mut to_fold = Vec::new();
14933        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14934        let selections = self.selections.all_adjusted(cx);
14935
14936        for selection in selections {
14937            let range = selection.range().sorted();
14938            let buffer_start_row = range.start.row;
14939
14940            if range.start.row != range.end.row {
14941                let mut found = false;
14942                for row in range.start.row..=range.end.row {
14943                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14944                        found = true;
14945                        to_fold.push(crease);
14946                    }
14947                }
14948                if found {
14949                    continue;
14950                }
14951            }
14952
14953            for row in (0..=range.start.row).rev() {
14954                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14955                    if crease.range().end.row >= buffer_start_row {
14956                        to_fold.push(crease);
14957                    } else {
14958                        break;
14959                    }
14960                }
14961            }
14962        }
14963
14964        self.fold_creases(to_fold, true, window, cx);
14965    }
14966
14967    pub fn fold_at(
14968        &mut self,
14969        buffer_row: MultiBufferRow,
14970        window: &mut Window,
14971        cx: &mut Context<Self>,
14972    ) {
14973        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14974
14975        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
14976            let autoscroll = self
14977                .selections
14978                .all::<Point>(cx)
14979                .iter()
14980                .any(|selection| crease.range().overlaps(&selection.range()));
14981
14982            self.fold_creases(vec![crease], autoscroll, window, cx);
14983        }
14984    }
14985
14986    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
14987        if self.is_singleton(cx) {
14988            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14989            let buffer = &display_map.buffer_snapshot;
14990            let selections = self.selections.all::<Point>(cx);
14991            let ranges = selections
14992                .iter()
14993                .map(|s| {
14994                    let range = s.display_range(&display_map).sorted();
14995                    let mut start = range.start.to_point(&display_map);
14996                    let mut end = range.end.to_point(&display_map);
14997                    start.column = 0;
14998                    end.column = buffer.line_len(MultiBufferRow(end.row));
14999                    start..end
15000                })
15001                .collect::<Vec<_>>();
15002
15003            self.unfold_ranges(&ranges, true, true, cx);
15004        } else {
15005            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15006            let buffer_ids = self
15007                .selections
15008                .disjoint_anchor_ranges()
15009                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15010                .collect::<HashSet<_>>();
15011            for buffer_id in buffer_ids {
15012                self.unfold_buffer(buffer_id, cx);
15013            }
15014        }
15015    }
15016
15017    pub fn unfold_recursive(
15018        &mut self,
15019        _: &UnfoldRecursive,
15020        _window: &mut Window,
15021        cx: &mut Context<Self>,
15022    ) {
15023        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15024        let selections = self.selections.all::<Point>(cx);
15025        let ranges = selections
15026            .iter()
15027            .map(|s| {
15028                let mut range = s.display_range(&display_map).sorted();
15029                *range.start.column_mut() = 0;
15030                *range.end.column_mut() = display_map.line_len(range.end.row());
15031                let start = range.start.to_point(&display_map);
15032                let end = range.end.to_point(&display_map);
15033                start..end
15034            })
15035            .collect::<Vec<_>>();
15036
15037        self.unfold_ranges(&ranges, true, true, cx);
15038    }
15039
15040    pub fn unfold_at(
15041        &mut self,
15042        buffer_row: MultiBufferRow,
15043        _window: &mut Window,
15044        cx: &mut Context<Self>,
15045    ) {
15046        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15047
15048        let intersection_range = Point::new(buffer_row.0, 0)
15049            ..Point::new(
15050                buffer_row.0,
15051                display_map.buffer_snapshot.line_len(buffer_row),
15052            );
15053
15054        let autoscroll = self
15055            .selections
15056            .all::<Point>(cx)
15057            .iter()
15058            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15059
15060        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15061    }
15062
15063    pub fn unfold_all(
15064        &mut self,
15065        _: &actions::UnfoldAll,
15066        _window: &mut Window,
15067        cx: &mut Context<Self>,
15068    ) {
15069        if self.buffer.read(cx).is_singleton() {
15070            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15071            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15072        } else {
15073            self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15074                editor
15075                    .update(cx, |editor, cx| {
15076                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15077                            editor.unfold_buffer(buffer_id, cx);
15078                        }
15079                    })
15080                    .ok();
15081            });
15082        }
15083    }
15084
15085    pub fn fold_selected_ranges(
15086        &mut self,
15087        _: &FoldSelectedRanges,
15088        window: &mut Window,
15089        cx: &mut Context<Self>,
15090    ) {
15091        let selections = self.selections.all_adjusted(cx);
15092        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15093        let ranges = selections
15094            .into_iter()
15095            .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15096            .collect::<Vec<_>>();
15097        self.fold_creases(ranges, true, window, cx);
15098    }
15099
15100    pub fn fold_ranges<T: ToOffset + Clone>(
15101        &mut self,
15102        ranges: Vec<Range<T>>,
15103        auto_scroll: bool,
15104        window: &mut Window,
15105        cx: &mut Context<Self>,
15106    ) {
15107        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15108        let ranges = ranges
15109            .into_iter()
15110            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15111            .collect::<Vec<_>>();
15112        self.fold_creases(ranges, auto_scroll, window, cx);
15113    }
15114
15115    pub fn fold_creases<T: ToOffset + Clone>(
15116        &mut self,
15117        creases: Vec<Crease<T>>,
15118        auto_scroll: bool,
15119        window: &mut Window,
15120        cx: &mut Context<Self>,
15121    ) {
15122        if creases.is_empty() {
15123            return;
15124        }
15125
15126        let mut buffers_affected = HashSet::default();
15127        let multi_buffer = self.buffer().read(cx);
15128        for crease in &creases {
15129            if let Some((_, buffer, _)) =
15130                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15131            {
15132                buffers_affected.insert(buffer.read(cx).remote_id());
15133            };
15134        }
15135
15136        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15137
15138        if auto_scroll {
15139            self.request_autoscroll(Autoscroll::fit(), cx);
15140        }
15141
15142        cx.notify();
15143
15144        if let Some(active_diagnostics) = self.active_diagnostics.take() {
15145            // Clear diagnostics block when folding a range that contains it.
15146            let snapshot = self.snapshot(window, cx);
15147            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
15148                drop(snapshot);
15149                self.active_diagnostics = Some(active_diagnostics);
15150                self.dismiss_diagnostics(cx);
15151            } else {
15152                self.active_diagnostics = Some(active_diagnostics);
15153            }
15154        }
15155
15156        self.scrollbar_marker_state.dirty = true;
15157        self.folds_did_change(cx);
15158    }
15159
15160    /// Removes any folds whose ranges intersect any of the given ranges.
15161    pub fn unfold_ranges<T: ToOffset + Clone>(
15162        &mut self,
15163        ranges: &[Range<T>],
15164        inclusive: bool,
15165        auto_scroll: bool,
15166        cx: &mut Context<Self>,
15167    ) {
15168        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15169            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15170        });
15171        self.folds_did_change(cx);
15172    }
15173
15174    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15175        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15176            return;
15177        }
15178        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15179        self.display_map.update(cx, |display_map, cx| {
15180            display_map.fold_buffers([buffer_id], cx)
15181        });
15182        cx.emit(EditorEvent::BufferFoldToggled {
15183            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15184            folded: true,
15185        });
15186        cx.notify();
15187    }
15188
15189    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15190        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15191            return;
15192        }
15193        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15194        self.display_map.update(cx, |display_map, cx| {
15195            display_map.unfold_buffers([buffer_id], cx);
15196        });
15197        cx.emit(EditorEvent::BufferFoldToggled {
15198            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15199            folded: false,
15200        });
15201        cx.notify();
15202    }
15203
15204    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15205        self.display_map.read(cx).is_buffer_folded(buffer)
15206    }
15207
15208    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15209        self.display_map.read(cx).folded_buffers()
15210    }
15211
15212    pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15213        self.display_map.update(cx, |display_map, cx| {
15214            display_map.disable_header_for_buffer(buffer_id, cx);
15215        });
15216        cx.notify();
15217    }
15218
15219    /// Removes any folds with the given ranges.
15220    pub fn remove_folds_with_type<T: ToOffset + Clone>(
15221        &mut self,
15222        ranges: &[Range<T>],
15223        type_id: TypeId,
15224        auto_scroll: bool,
15225        cx: &mut Context<Self>,
15226    ) {
15227        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15228            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15229        });
15230        self.folds_did_change(cx);
15231    }
15232
15233    fn remove_folds_with<T: ToOffset + Clone>(
15234        &mut self,
15235        ranges: &[Range<T>],
15236        auto_scroll: bool,
15237        cx: &mut Context<Self>,
15238        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15239    ) {
15240        if ranges.is_empty() {
15241            return;
15242        }
15243
15244        let mut buffers_affected = HashSet::default();
15245        let multi_buffer = self.buffer().read(cx);
15246        for range in ranges {
15247            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15248                buffers_affected.insert(buffer.read(cx).remote_id());
15249            };
15250        }
15251
15252        self.display_map.update(cx, update);
15253
15254        if auto_scroll {
15255            self.request_autoscroll(Autoscroll::fit(), cx);
15256        }
15257
15258        cx.notify();
15259        self.scrollbar_marker_state.dirty = true;
15260        self.active_indent_guides_state.dirty = true;
15261    }
15262
15263    pub fn update_fold_widths(
15264        &mut self,
15265        widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15266        cx: &mut Context<Self>,
15267    ) -> bool {
15268        self.display_map
15269            .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15270    }
15271
15272    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15273        self.display_map.read(cx).fold_placeholder.clone()
15274    }
15275
15276    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15277        self.buffer.update(cx, |buffer, cx| {
15278            buffer.set_all_diff_hunks_expanded(cx);
15279        });
15280    }
15281
15282    pub fn expand_all_diff_hunks(
15283        &mut self,
15284        _: &ExpandAllDiffHunks,
15285        _window: &mut Window,
15286        cx: &mut Context<Self>,
15287    ) {
15288        self.buffer.update(cx, |buffer, cx| {
15289            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15290        });
15291    }
15292
15293    pub fn toggle_selected_diff_hunks(
15294        &mut self,
15295        _: &ToggleSelectedDiffHunks,
15296        _window: &mut Window,
15297        cx: &mut Context<Self>,
15298    ) {
15299        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15300        self.toggle_diff_hunks_in_ranges(ranges, cx);
15301    }
15302
15303    pub fn diff_hunks_in_ranges<'a>(
15304        &'a self,
15305        ranges: &'a [Range<Anchor>],
15306        buffer: &'a MultiBufferSnapshot,
15307    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15308        ranges.iter().flat_map(move |range| {
15309            let end_excerpt_id = range.end.excerpt_id;
15310            let range = range.to_point(buffer);
15311            let mut peek_end = range.end;
15312            if range.end.row < buffer.max_row().0 {
15313                peek_end = Point::new(range.end.row + 1, 0);
15314            }
15315            buffer
15316                .diff_hunks_in_range(range.start..peek_end)
15317                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15318        })
15319    }
15320
15321    pub fn has_stageable_diff_hunks_in_ranges(
15322        &self,
15323        ranges: &[Range<Anchor>],
15324        snapshot: &MultiBufferSnapshot,
15325    ) -> bool {
15326        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15327        hunks.any(|hunk| hunk.status().has_secondary_hunk())
15328    }
15329
15330    pub fn toggle_staged_selected_diff_hunks(
15331        &mut self,
15332        _: &::git::ToggleStaged,
15333        _: &mut Window,
15334        cx: &mut Context<Self>,
15335    ) {
15336        let snapshot = self.buffer.read(cx).snapshot(cx);
15337        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15338        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15339        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15340    }
15341
15342    pub fn set_render_diff_hunk_controls(
15343        &mut self,
15344        render_diff_hunk_controls: RenderDiffHunkControlsFn,
15345        cx: &mut Context<Self>,
15346    ) {
15347        self.render_diff_hunk_controls = render_diff_hunk_controls;
15348        cx.notify();
15349    }
15350
15351    pub fn stage_and_next(
15352        &mut self,
15353        _: &::git::StageAndNext,
15354        window: &mut Window,
15355        cx: &mut Context<Self>,
15356    ) {
15357        self.do_stage_or_unstage_and_next(true, window, cx);
15358    }
15359
15360    pub fn unstage_and_next(
15361        &mut self,
15362        _: &::git::UnstageAndNext,
15363        window: &mut Window,
15364        cx: &mut Context<Self>,
15365    ) {
15366        self.do_stage_or_unstage_and_next(false, window, cx);
15367    }
15368
15369    pub fn stage_or_unstage_diff_hunks(
15370        &mut self,
15371        stage: bool,
15372        ranges: Vec<Range<Anchor>>,
15373        cx: &mut Context<Self>,
15374    ) {
15375        let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15376        cx.spawn(async move |this, cx| {
15377            task.await?;
15378            this.update(cx, |this, cx| {
15379                let snapshot = this.buffer.read(cx).snapshot(cx);
15380                let chunk_by = this
15381                    .diff_hunks_in_ranges(&ranges, &snapshot)
15382                    .chunk_by(|hunk| hunk.buffer_id);
15383                for (buffer_id, hunks) in &chunk_by {
15384                    this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15385                }
15386            })
15387        })
15388        .detach_and_log_err(cx);
15389    }
15390
15391    fn save_buffers_for_ranges_if_needed(
15392        &mut self,
15393        ranges: &[Range<Anchor>],
15394        cx: &mut Context<Editor>,
15395    ) -> Task<Result<()>> {
15396        let multibuffer = self.buffer.read(cx);
15397        let snapshot = multibuffer.read(cx);
15398        let buffer_ids: HashSet<_> = ranges
15399            .iter()
15400            .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15401            .collect();
15402        drop(snapshot);
15403
15404        let mut buffers = HashSet::default();
15405        for buffer_id in buffer_ids {
15406            if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15407                let buffer = buffer_entity.read(cx);
15408                if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15409                {
15410                    buffers.insert(buffer_entity);
15411                }
15412            }
15413        }
15414
15415        if let Some(project) = &self.project {
15416            project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15417        } else {
15418            Task::ready(Ok(()))
15419        }
15420    }
15421
15422    fn do_stage_or_unstage_and_next(
15423        &mut self,
15424        stage: bool,
15425        window: &mut Window,
15426        cx: &mut Context<Self>,
15427    ) {
15428        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15429
15430        if ranges.iter().any(|range| range.start != range.end) {
15431            self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15432            return;
15433        }
15434
15435        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15436        let snapshot = self.snapshot(window, cx);
15437        let position = self.selections.newest::<Point>(cx).head();
15438        let mut row = snapshot
15439            .buffer_snapshot
15440            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15441            .find(|hunk| hunk.row_range.start.0 > position.row)
15442            .map(|hunk| hunk.row_range.start);
15443
15444        let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15445        // Outside of the project diff editor, wrap around to the beginning.
15446        if !all_diff_hunks_expanded {
15447            row = row.or_else(|| {
15448                snapshot
15449                    .buffer_snapshot
15450                    .diff_hunks_in_range(Point::zero()..position)
15451                    .find(|hunk| hunk.row_range.end.0 < position.row)
15452                    .map(|hunk| hunk.row_range.start)
15453            });
15454        }
15455
15456        if let Some(row) = row {
15457            let destination = Point::new(row.0, 0);
15458            let autoscroll = Autoscroll::center();
15459
15460            self.unfold_ranges(&[destination..destination], false, false, cx);
15461            self.change_selections(Some(autoscroll), window, cx, |s| {
15462                s.select_ranges([destination..destination]);
15463            });
15464        }
15465    }
15466
15467    fn do_stage_or_unstage(
15468        &self,
15469        stage: bool,
15470        buffer_id: BufferId,
15471        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15472        cx: &mut App,
15473    ) -> Option<()> {
15474        let project = self.project.as_ref()?;
15475        let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15476        let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15477        let buffer_snapshot = buffer.read(cx).snapshot();
15478        let file_exists = buffer_snapshot
15479            .file()
15480            .is_some_and(|file| file.disk_state().exists());
15481        diff.update(cx, |diff, cx| {
15482            diff.stage_or_unstage_hunks(
15483                stage,
15484                &hunks
15485                    .map(|hunk| buffer_diff::DiffHunk {
15486                        buffer_range: hunk.buffer_range,
15487                        diff_base_byte_range: hunk.diff_base_byte_range,
15488                        secondary_status: hunk.secondary_status,
15489                        range: Point::zero()..Point::zero(), // unused
15490                    })
15491                    .collect::<Vec<_>>(),
15492                &buffer_snapshot,
15493                file_exists,
15494                cx,
15495            )
15496        });
15497        None
15498    }
15499
15500    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15501        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15502        self.buffer
15503            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15504    }
15505
15506    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
15507        self.buffer.update(cx, |buffer, cx| {
15508            let ranges = vec![Anchor::min()..Anchor::max()];
15509            if !buffer.all_diff_hunks_expanded()
15510                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
15511            {
15512                buffer.collapse_diff_hunks(ranges, cx);
15513                true
15514            } else {
15515                false
15516            }
15517        })
15518    }
15519
15520    fn toggle_diff_hunks_in_ranges(
15521        &mut self,
15522        ranges: Vec<Range<Anchor>>,
15523        cx: &mut Context<Editor>,
15524    ) {
15525        self.buffer.update(cx, |buffer, cx| {
15526            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
15527            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
15528        })
15529    }
15530
15531    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15532        self.buffer.update(cx, |buffer, cx| {
15533            let snapshot = buffer.snapshot(cx);
15534            let excerpt_id = range.end.excerpt_id;
15535            let point_range = range.to_point(&snapshot);
15536            let expand = !buffer.single_hunk_is_expanded(range, cx);
15537            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15538        })
15539    }
15540
15541    pub(crate) fn apply_all_diff_hunks(
15542        &mut self,
15543        _: &ApplyAllDiffHunks,
15544        window: &mut Window,
15545        cx: &mut Context<Self>,
15546    ) {
15547        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15548
15549        let buffers = self.buffer.read(cx).all_buffers();
15550        for branch_buffer in buffers {
15551            branch_buffer.update(cx, |branch_buffer, cx| {
15552                branch_buffer.merge_into_base(Vec::new(), cx);
15553            });
15554        }
15555
15556        if let Some(project) = self.project.clone() {
15557            self.save(true, project, window, cx).detach_and_log_err(cx);
15558        }
15559    }
15560
15561    pub(crate) fn apply_selected_diff_hunks(
15562        &mut self,
15563        _: &ApplyDiffHunk,
15564        window: &mut Window,
15565        cx: &mut Context<Self>,
15566    ) {
15567        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15568        let snapshot = self.snapshot(window, cx);
15569        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15570        let mut ranges_by_buffer = HashMap::default();
15571        self.transact(window, cx, |editor, _window, cx| {
15572            for hunk in hunks {
15573                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15574                    ranges_by_buffer
15575                        .entry(buffer.clone())
15576                        .or_insert_with(Vec::new)
15577                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15578                }
15579            }
15580
15581            for (buffer, ranges) in ranges_by_buffer {
15582                buffer.update(cx, |buffer, cx| {
15583                    buffer.merge_into_base(ranges, cx);
15584                });
15585            }
15586        });
15587
15588        if let Some(project) = self.project.clone() {
15589            self.save(true, project, window, cx).detach_and_log_err(cx);
15590        }
15591    }
15592
15593    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15594        if hovered != self.gutter_hovered {
15595            self.gutter_hovered = hovered;
15596            cx.notify();
15597        }
15598    }
15599
15600    pub fn insert_blocks(
15601        &mut self,
15602        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15603        autoscroll: Option<Autoscroll>,
15604        cx: &mut Context<Self>,
15605    ) -> Vec<CustomBlockId> {
15606        let blocks = self
15607            .display_map
15608            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15609        if let Some(autoscroll) = autoscroll {
15610            self.request_autoscroll(autoscroll, cx);
15611        }
15612        cx.notify();
15613        blocks
15614    }
15615
15616    pub fn resize_blocks(
15617        &mut self,
15618        heights: HashMap<CustomBlockId, u32>,
15619        autoscroll: Option<Autoscroll>,
15620        cx: &mut Context<Self>,
15621    ) {
15622        self.display_map
15623            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15624        if let Some(autoscroll) = autoscroll {
15625            self.request_autoscroll(autoscroll, cx);
15626        }
15627        cx.notify();
15628    }
15629
15630    pub fn replace_blocks(
15631        &mut self,
15632        renderers: HashMap<CustomBlockId, RenderBlock>,
15633        autoscroll: Option<Autoscroll>,
15634        cx: &mut Context<Self>,
15635    ) {
15636        self.display_map
15637            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15638        if let Some(autoscroll) = autoscroll {
15639            self.request_autoscroll(autoscroll, cx);
15640        }
15641        cx.notify();
15642    }
15643
15644    pub fn remove_blocks(
15645        &mut self,
15646        block_ids: HashSet<CustomBlockId>,
15647        autoscroll: Option<Autoscroll>,
15648        cx: &mut Context<Self>,
15649    ) {
15650        self.display_map.update(cx, |display_map, cx| {
15651            display_map.remove_blocks(block_ids, cx)
15652        });
15653        if let Some(autoscroll) = autoscroll {
15654            self.request_autoscroll(autoscroll, cx);
15655        }
15656        cx.notify();
15657    }
15658
15659    pub fn row_for_block(
15660        &self,
15661        block_id: CustomBlockId,
15662        cx: &mut Context<Self>,
15663    ) -> Option<DisplayRow> {
15664        self.display_map
15665            .update(cx, |map, cx| map.row_for_block(block_id, cx))
15666    }
15667
15668    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15669        self.focused_block = Some(focused_block);
15670    }
15671
15672    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15673        self.focused_block.take()
15674    }
15675
15676    pub fn insert_creases(
15677        &mut self,
15678        creases: impl IntoIterator<Item = Crease<Anchor>>,
15679        cx: &mut Context<Self>,
15680    ) -> Vec<CreaseId> {
15681        self.display_map
15682            .update(cx, |map, cx| map.insert_creases(creases, cx))
15683    }
15684
15685    pub fn remove_creases(
15686        &mut self,
15687        ids: impl IntoIterator<Item = CreaseId>,
15688        cx: &mut Context<Self>,
15689    ) {
15690        self.display_map
15691            .update(cx, |map, cx| map.remove_creases(ids, cx));
15692    }
15693
15694    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15695        self.display_map
15696            .update(cx, |map, cx| map.snapshot(cx))
15697            .longest_row()
15698    }
15699
15700    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15701        self.display_map
15702            .update(cx, |map, cx| map.snapshot(cx))
15703            .max_point()
15704    }
15705
15706    pub fn text(&self, cx: &App) -> String {
15707        self.buffer.read(cx).read(cx).text()
15708    }
15709
15710    pub fn is_empty(&self, cx: &App) -> bool {
15711        self.buffer.read(cx).read(cx).is_empty()
15712    }
15713
15714    pub fn text_option(&self, cx: &App) -> Option<String> {
15715        let text = self.text(cx);
15716        let text = text.trim();
15717
15718        if text.is_empty() {
15719            return None;
15720        }
15721
15722        Some(text.to_string())
15723    }
15724
15725    pub fn set_text(
15726        &mut self,
15727        text: impl Into<Arc<str>>,
15728        window: &mut Window,
15729        cx: &mut Context<Self>,
15730    ) {
15731        self.transact(window, cx, |this, _, cx| {
15732            this.buffer
15733                .read(cx)
15734                .as_singleton()
15735                .expect("you can only call set_text on editors for singleton buffers")
15736                .update(cx, |buffer, cx| buffer.set_text(text, cx));
15737        });
15738    }
15739
15740    pub fn display_text(&self, cx: &mut App) -> String {
15741        self.display_map
15742            .update(cx, |map, cx| map.snapshot(cx))
15743            .text()
15744    }
15745
15746    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15747        let mut wrap_guides = smallvec::smallvec![];
15748
15749        if self.show_wrap_guides == Some(false) {
15750            return wrap_guides;
15751        }
15752
15753        let settings = self.buffer.read(cx).language_settings(cx);
15754        if settings.show_wrap_guides {
15755            match self.soft_wrap_mode(cx) {
15756                SoftWrap::Column(soft_wrap) => {
15757                    wrap_guides.push((soft_wrap as usize, true));
15758                }
15759                SoftWrap::Bounded(soft_wrap) => {
15760                    wrap_guides.push((soft_wrap as usize, true));
15761                }
15762                SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15763            }
15764            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15765        }
15766
15767        wrap_guides
15768    }
15769
15770    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15771        let settings = self.buffer.read(cx).language_settings(cx);
15772        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15773        match mode {
15774            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
15775                SoftWrap::None
15776            }
15777            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
15778            language_settings::SoftWrap::PreferredLineLength => {
15779                SoftWrap::Column(settings.preferred_line_length)
15780            }
15781            language_settings::SoftWrap::Bounded => {
15782                SoftWrap::Bounded(settings.preferred_line_length)
15783            }
15784        }
15785    }
15786
15787    pub fn set_soft_wrap_mode(
15788        &mut self,
15789        mode: language_settings::SoftWrap,
15790
15791        cx: &mut Context<Self>,
15792    ) {
15793        self.soft_wrap_mode_override = Some(mode);
15794        cx.notify();
15795    }
15796
15797    pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
15798        self.hard_wrap = hard_wrap;
15799        cx.notify();
15800    }
15801
15802    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
15803        self.text_style_refinement = Some(style);
15804    }
15805
15806    /// called by the Element so we know what style we were most recently rendered with.
15807    pub(crate) fn set_style(
15808        &mut self,
15809        style: EditorStyle,
15810        window: &mut Window,
15811        cx: &mut Context<Self>,
15812    ) {
15813        let rem_size = window.rem_size();
15814        self.display_map.update(cx, |map, cx| {
15815            map.set_font(
15816                style.text.font(),
15817                style.text.font_size.to_pixels(rem_size),
15818                cx,
15819            )
15820        });
15821        self.style = Some(style);
15822    }
15823
15824    pub fn style(&self) -> Option<&EditorStyle> {
15825        self.style.as_ref()
15826    }
15827
15828    // Called by the element. This method is not designed to be called outside of the editor
15829    // element's layout code because it does not notify when rewrapping is computed synchronously.
15830    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
15831        self.display_map
15832            .update(cx, |map, cx| map.set_wrap_width(width, cx))
15833    }
15834
15835    pub fn set_soft_wrap(&mut self) {
15836        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
15837    }
15838
15839    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
15840        if self.soft_wrap_mode_override.is_some() {
15841            self.soft_wrap_mode_override.take();
15842        } else {
15843            let soft_wrap = match self.soft_wrap_mode(cx) {
15844                SoftWrap::GitDiff => return,
15845                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
15846                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
15847                    language_settings::SoftWrap::None
15848                }
15849            };
15850            self.soft_wrap_mode_override = Some(soft_wrap);
15851        }
15852        cx.notify();
15853    }
15854
15855    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
15856        let Some(workspace) = self.workspace() else {
15857            return;
15858        };
15859        let fs = workspace.read(cx).app_state().fs.clone();
15860        let current_show = TabBarSettings::get_global(cx).show;
15861        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
15862            setting.show = Some(!current_show);
15863        });
15864    }
15865
15866    pub fn toggle_indent_guides(
15867        &mut self,
15868        _: &ToggleIndentGuides,
15869        _: &mut Window,
15870        cx: &mut Context<Self>,
15871    ) {
15872        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
15873            self.buffer
15874                .read(cx)
15875                .language_settings(cx)
15876                .indent_guides
15877                .enabled
15878        });
15879        self.show_indent_guides = Some(!currently_enabled);
15880        cx.notify();
15881    }
15882
15883    fn should_show_indent_guides(&self) -> Option<bool> {
15884        self.show_indent_guides
15885    }
15886
15887    pub fn toggle_line_numbers(
15888        &mut self,
15889        _: &ToggleLineNumbers,
15890        _: &mut Window,
15891        cx: &mut Context<Self>,
15892    ) {
15893        let mut editor_settings = EditorSettings::get_global(cx).clone();
15894        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
15895        EditorSettings::override_global(editor_settings, cx);
15896    }
15897
15898    pub fn line_numbers_enabled(&self, cx: &App) -> bool {
15899        if let Some(show_line_numbers) = self.show_line_numbers {
15900            return show_line_numbers;
15901        }
15902        EditorSettings::get_global(cx).gutter.line_numbers
15903    }
15904
15905    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
15906        self.use_relative_line_numbers
15907            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
15908    }
15909
15910    pub fn toggle_relative_line_numbers(
15911        &mut self,
15912        _: &ToggleRelativeLineNumbers,
15913        _: &mut Window,
15914        cx: &mut Context<Self>,
15915    ) {
15916        let is_relative = self.should_use_relative_line_numbers(cx);
15917        self.set_relative_line_number(Some(!is_relative), cx)
15918    }
15919
15920    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
15921        self.use_relative_line_numbers = is_relative;
15922        cx.notify();
15923    }
15924
15925    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
15926        self.show_gutter = show_gutter;
15927        cx.notify();
15928    }
15929
15930    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
15931        self.show_scrollbars = show_scrollbars;
15932        cx.notify();
15933    }
15934
15935    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
15936        self.show_line_numbers = Some(show_line_numbers);
15937        cx.notify();
15938    }
15939
15940    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
15941        self.show_git_diff_gutter = Some(show_git_diff_gutter);
15942        cx.notify();
15943    }
15944
15945    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
15946        self.show_code_actions = Some(show_code_actions);
15947        cx.notify();
15948    }
15949
15950    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
15951        self.show_runnables = Some(show_runnables);
15952        cx.notify();
15953    }
15954
15955    pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
15956        self.show_breakpoints = Some(show_breakpoints);
15957        cx.notify();
15958    }
15959
15960    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
15961        if self.display_map.read(cx).masked != masked {
15962            self.display_map.update(cx, |map, _| map.masked = masked);
15963        }
15964        cx.notify()
15965    }
15966
15967    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
15968        self.show_wrap_guides = Some(show_wrap_guides);
15969        cx.notify();
15970    }
15971
15972    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
15973        self.show_indent_guides = Some(show_indent_guides);
15974        cx.notify();
15975    }
15976
15977    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
15978        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
15979            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
15980                if let Some(dir) = file.abs_path(cx).parent() {
15981                    return Some(dir.to_owned());
15982                }
15983            }
15984
15985            if let Some(project_path) = buffer.read(cx).project_path(cx) {
15986                return Some(project_path.path.to_path_buf());
15987            }
15988        }
15989
15990        None
15991    }
15992
15993    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
15994        self.active_excerpt(cx)?
15995            .1
15996            .read(cx)
15997            .file()
15998            .and_then(|f| f.as_local())
15999    }
16000
16001    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16002        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16003            let buffer = buffer.read(cx);
16004            if let Some(project_path) = buffer.project_path(cx) {
16005                let project = self.project.as_ref()?.read(cx);
16006                project.absolute_path(&project_path, cx)
16007            } else {
16008                buffer
16009                    .file()
16010                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16011            }
16012        })
16013    }
16014
16015    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16016        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16017            let project_path = buffer.read(cx).project_path(cx)?;
16018            let project = self.project.as_ref()?.read(cx);
16019            let entry = project.entry_for_path(&project_path, cx)?;
16020            let path = entry.path.to_path_buf();
16021            Some(path)
16022        })
16023    }
16024
16025    pub fn reveal_in_finder(
16026        &mut self,
16027        _: &RevealInFileManager,
16028        _window: &mut Window,
16029        cx: &mut Context<Self>,
16030    ) {
16031        if let Some(target) = self.target_file(cx) {
16032            cx.reveal_path(&target.abs_path(cx));
16033        }
16034    }
16035
16036    pub fn copy_path(
16037        &mut self,
16038        _: &zed_actions::workspace::CopyPath,
16039        _window: &mut Window,
16040        cx: &mut Context<Self>,
16041    ) {
16042        if let Some(path) = self.target_file_abs_path(cx) {
16043            if let Some(path) = path.to_str() {
16044                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16045            }
16046        }
16047    }
16048
16049    pub fn copy_relative_path(
16050        &mut self,
16051        _: &zed_actions::workspace::CopyRelativePath,
16052        _window: &mut Window,
16053        cx: &mut Context<Self>,
16054    ) {
16055        if let Some(path) = self.target_file_path(cx) {
16056            if let Some(path) = path.to_str() {
16057                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16058            }
16059        }
16060    }
16061
16062    pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16063        if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16064            buffer.read(cx).project_path(cx)
16065        } else {
16066            None
16067        }
16068    }
16069
16070    // Returns true if the editor handled a go-to-line request
16071    pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16072        maybe!({
16073            let breakpoint_store = self.breakpoint_store.as_ref()?;
16074
16075            let Some((_, _, active_position)) =
16076                breakpoint_store.read(cx).active_position().cloned()
16077            else {
16078                self.clear_row_highlights::<DebugCurrentRowHighlight>();
16079                return None;
16080            };
16081
16082            let snapshot = self
16083                .project
16084                .as_ref()?
16085                .read(cx)
16086                .buffer_for_id(active_position.buffer_id?, cx)?
16087                .read(cx)
16088                .snapshot();
16089
16090            let mut handled = false;
16091            for (id, ExcerptRange { context, .. }) in self
16092                .buffer
16093                .read(cx)
16094                .excerpts_for_buffer(active_position.buffer_id?, cx)
16095            {
16096                if context.start.cmp(&active_position, &snapshot).is_ge()
16097                    || context.end.cmp(&active_position, &snapshot).is_lt()
16098                {
16099                    continue;
16100                }
16101                let snapshot = self.buffer.read(cx).snapshot(cx);
16102                let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
16103
16104                handled = true;
16105                self.clear_row_highlights::<DebugCurrentRowHighlight>();
16106                self.go_to_line::<DebugCurrentRowHighlight>(
16107                    multibuffer_anchor,
16108                    Some(cx.theme().colors().editor_debugger_active_line_background),
16109                    window,
16110                    cx,
16111                );
16112
16113                cx.notify();
16114            }
16115            handled.then_some(())
16116        })
16117        .is_some()
16118    }
16119
16120    pub fn copy_file_name_without_extension(
16121        &mut self,
16122        _: &CopyFileNameWithoutExtension,
16123        _: &mut Window,
16124        cx: &mut Context<Self>,
16125    ) {
16126        if let Some(file) = self.target_file(cx) {
16127            if let Some(file_stem) = file.path().file_stem() {
16128                if let Some(name) = file_stem.to_str() {
16129                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16130                }
16131            }
16132        }
16133    }
16134
16135    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16136        if let Some(file) = self.target_file(cx) {
16137            if let Some(file_name) = file.path().file_name() {
16138                if let Some(name) = file_name.to_str() {
16139                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16140                }
16141            }
16142        }
16143    }
16144
16145    pub fn toggle_git_blame(
16146        &mut self,
16147        _: &::git::Blame,
16148        window: &mut Window,
16149        cx: &mut Context<Self>,
16150    ) {
16151        self.show_git_blame_gutter = !self.show_git_blame_gutter;
16152
16153        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16154            self.start_git_blame(true, window, cx);
16155        }
16156
16157        cx.notify();
16158    }
16159
16160    pub fn toggle_git_blame_inline(
16161        &mut self,
16162        _: &ToggleGitBlameInline,
16163        window: &mut Window,
16164        cx: &mut Context<Self>,
16165    ) {
16166        self.toggle_git_blame_inline_internal(true, window, cx);
16167        cx.notify();
16168    }
16169
16170    pub fn open_git_blame_commit(
16171        &mut self,
16172        _: &OpenGitBlameCommit,
16173        window: &mut Window,
16174        cx: &mut Context<Self>,
16175    ) {
16176        self.open_git_blame_commit_internal(window, cx);
16177    }
16178
16179    fn open_git_blame_commit_internal(
16180        &mut self,
16181        window: &mut Window,
16182        cx: &mut Context<Self>,
16183    ) -> Option<()> {
16184        let blame = self.blame.as_ref()?;
16185        let snapshot = self.snapshot(window, cx);
16186        let cursor = self.selections.newest::<Point>(cx).head();
16187        let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16188        let blame_entry = blame
16189            .update(cx, |blame, cx| {
16190                blame
16191                    .blame_for_rows(
16192                        &[RowInfo {
16193                            buffer_id: Some(buffer.remote_id()),
16194                            buffer_row: Some(point.row),
16195                            ..Default::default()
16196                        }],
16197                        cx,
16198                    )
16199                    .next()
16200            })
16201            .flatten()?;
16202        let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16203        let repo = blame.read(cx).repository(cx)?;
16204        let workspace = self.workspace()?.downgrade();
16205        renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16206        None
16207    }
16208
16209    pub fn git_blame_inline_enabled(&self) -> bool {
16210        self.git_blame_inline_enabled
16211    }
16212
16213    pub fn toggle_selection_menu(
16214        &mut self,
16215        _: &ToggleSelectionMenu,
16216        _: &mut Window,
16217        cx: &mut Context<Self>,
16218    ) {
16219        self.show_selection_menu = self
16220            .show_selection_menu
16221            .map(|show_selections_menu| !show_selections_menu)
16222            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16223
16224        cx.notify();
16225    }
16226
16227    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16228        self.show_selection_menu
16229            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16230    }
16231
16232    fn start_git_blame(
16233        &mut self,
16234        user_triggered: bool,
16235        window: &mut Window,
16236        cx: &mut Context<Self>,
16237    ) {
16238        if let Some(project) = self.project.as_ref() {
16239            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16240                return;
16241            };
16242
16243            if buffer.read(cx).file().is_none() {
16244                return;
16245            }
16246
16247            let focused = self.focus_handle(cx).contains_focused(window, cx);
16248
16249            let project = project.clone();
16250            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16251            self.blame_subscription =
16252                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16253            self.blame = Some(blame);
16254        }
16255    }
16256
16257    fn toggle_git_blame_inline_internal(
16258        &mut self,
16259        user_triggered: bool,
16260        window: &mut Window,
16261        cx: &mut Context<Self>,
16262    ) {
16263        if self.git_blame_inline_enabled {
16264            self.git_blame_inline_enabled = false;
16265            self.show_git_blame_inline = false;
16266            self.show_git_blame_inline_delay_task.take();
16267        } else {
16268            self.git_blame_inline_enabled = true;
16269            self.start_git_blame_inline(user_triggered, window, cx);
16270        }
16271
16272        cx.notify();
16273    }
16274
16275    fn start_git_blame_inline(
16276        &mut self,
16277        user_triggered: bool,
16278        window: &mut Window,
16279        cx: &mut Context<Self>,
16280    ) {
16281        self.start_git_blame(user_triggered, window, cx);
16282
16283        if ProjectSettings::get_global(cx)
16284            .git
16285            .inline_blame_delay()
16286            .is_some()
16287        {
16288            self.start_inline_blame_timer(window, cx);
16289        } else {
16290            self.show_git_blame_inline = true
16291        }
16292    }
16293
16294    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16295        self.blame.as_ref()
16296    }
16297
16298    pub fn show_git_blame_gutter(&self) -> bool {
16299        self.show_git_blame_gutter
16300    }
16301
16302    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16303        self.show_git_blame_gutter && self.has_blame_entries(cx)
16304    }
16305
16306    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16307        self.show_git_blame_inline
16308            && (self.focus_handle.is_focused(window)
16309                || self
16310                    .git_blame_inline_tooltip
16311                    .as_ref()
16312                    .and_then(|t| t.upgrade())
16313                    .is_some())
16314            && !self.newest_selection_head_on_empty_line(cx)
16315            && self.has_blame_entries(cx)
16316    }
16317
16318    fn has_blame_entries(&self, cx: &App) -> bool {
16319        self.blame()
16320            .map_or(false, |blame| blame.read(cx).has_generated_entries())
16321    }
16322
16323    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16324        let cursor_anchor = self.selections.newest_anchor().head();
16325
16326        let snapshot = self.buffer.read(cx).snapshot(cx);
16327        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16328
16329        snapshot.line_len(buffer_row) == 0
16330    }
16331
16332    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16333        let buffer_and_selection = maybe!({
16334            let selection = self.selections.newest::<Point>(cx);
16335            let selection_range = selection.range();
16336
16337            let multi_buffer = self.buffer().read(cx);
16338            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16339            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16340
16341            let (buffer, range, _) = if selection.reversed {
16342                buffer_ranges.first()
16343            } else {
16344                buffer_ranges.last()
16345            }?;
16346
16347            let selection = text::ToPoint::to_point(&range.start, &buffer).row
16348                ..text::ToPoint::to_point(&range.end, &buffer).row;
16349            Some((
16350                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16351                selection,
16352            ))
16353        });
16354
16355        let Some((buffer, selection)) = buffer_and_selection else {
16356            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16357        };
16358
16359        let Some(project) = self.project.as_ref() else {
16360            return Task::ready(Err(anyhow!("editor does not have project")));
16361        };
16362
16363        project.update(cx, |project, cx| {
16364            project.get_permalink_to_line(&buffer, selection, cx)
16365        })
16366    }
16367
16368    pub fn copy_permalink_to_line(
16369        &mut self,
16370        _: &CopyPermalinkToLine,
16371        window: &mut Window,
16372        cx: &mut Context<Self>,
16373    ) {
16374        let permalink_task = self.get_permalink_to_line(cx);
16375        let workspace = self.workspace();
16376
16377        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16378            Ok(permalink) => {
16379                cx.update(|_, cx| {
16380                    cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16381                })
16382                .ok();
16383            }
16384            Err(err) => {
16385                let message = format!("Failed to copy permalink: {err}");
16386
16387                Err::<(), anyhow::Error>(err).log_err();
16388
16389                if let Some(workspace) = workspace {
16390                    workspace
16391                        .update_in(cx, |workspace, _, cx| {
16392                            struct CopyPermalinkToLine;
16393
16394                            workspace.show_toast(
16395                                Toast::new(
16396                                    NotificationId::unique::<CopyPermalinkToLine>(),
16397                                    message,
16398                                ),
16399                                cx,
16400                            )
16401                        })
16402                        .ok();
16403                }
16404            }
16405        })
16406        .detach();
16407    }
16408
16409    pub fn copy_file_location(
16410        &mut self,
16411        _: &CopyFileLocation,
16412        _: &mut Window,
16413        cx: &mut Context<Self>,
16414    ) {
16415        let selection = self.selections.newest::<Point>(cx).start.row + 1;
16416        if let Some(file) = self.target_file(cx) {
16417            if let Some(path) = file.path().to_str() {
16418                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16419            }
16420        }
16421    }
16422
16423    pub fn open_permalink_to_line(
16424        &mut self,
16425        _: &OpenPermalinkToLine,
16426        window: &mut Window,
16427        cx: &mut Context<Self>,
16428    ) {
16429        let permalink_task = self.get_permalink_to_line(cx);
16430        let workspace = self.workspace();
16431
16432        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16433            Ok(permalink) => {
16434                cx.update(|_, cx| {
16435                    cx.open_url(permalink.as_ref());
16436                })
16437                .ok();
16438            }
16439            Err(err) => {
16440                let message = format!("Failed to open permalink: {err}");
16441
16442                Err::<(), anyhow::Error>(err).log_err();
16443
16444                if let Some(workspace) = workspace {
16445                    workspace
16446                        .update(cx, |workspace, cx| {
16447                            struct OpenPermalinkToLine;
16448
16449                            workspace.show_toast(
16450                                Toast::new(
16451                                    NotificationId::unique::<OpenPermalinkToLine>(),
16452                                    message,
16453                                ),
16454                                cx,
16455                            )
16456                        })
16457                        .ok();
16458                }
16459            }
16460        })
16461        .detach();
16462    }
16463
16464    pub fn insert_uuid_v4(
16465        &mut self,
16466        _: &InsertUuidV4,
16467        window: &mut Window,
16468        cx: &mut Context<Self>,
16469    ) {
16470        self.insert_uuid(UuidVersion::V4, window, cx);
16471    }
16472
16473    pub fn insert_uuid_v7(
16474        &mut self,
16475        _: &InsertUuidV7,
16476        window: &mut Window,
16477        cx: &mut Context<Self>,
16478    ) {
16479        self.insert_uuid(UuidVersion::V7, window, cx);
16480    }
16481
16482    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16483        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16484        self.transact(window, cx, |this, window, cx| {
16485            let edits = this
16486                .selections
16487                .all::<Point>(cx)
16488                .into_iter()
16489                .map(|selection| {
16490                    let uuid = match version {
16491                        UuidVersion::V4 => uuid::Uuid::new_v4(),
16492                        UuidVersion::V7 => uuid::Uuid::now_v7(),
16493                    };
16494
16495                    (selection.range(), uuid.to_string())
16496                });
16497            this.edit(edits, cx);
16498            this.refresh_inline_completion(true, false, window, cx);
16499        });
16500    }
16501
16502    pub fn open_selections_in_multibuffer(
16503        &mut self,
16504        _: &OpenSelectionsInMultibuffer,
16505        window: &mut Window,
16506        cx: &mut Context<Self>,
16507    ) {
16508        let multibuffer = self.buffer.read(cx);
16509
16510        let Some(buffer) = multibuffer.as_singleton() else {
16511            return;
16512        };
16513
16514        let Some(workspace) = self.workspace() else {
16515            return;
16516        };
16517
16518        let locations = self
16519            .selections
16520            .disjoint_anchors()
16521            .iter()
16522            .map(|range| Location {
16523                buffer: buffer.clone(),
16524                range: range.start.text_anchor..range.end.text_anchor,
16525            })
16526            .collect::<Vec<_>>();
16527
16528        let title = multibuffer.title(cx).to_string();
16529
16530        cx.spawn_in(window, async move |_, cx| {
16531            workspace.update_in(cx, |workspace, window, cx| {
16532                Self::open_locations_in_multibuffer(
16533                    workspace,
16534                    locations,
16535                    format!("Selections for '{title}'"),
16536                    false,
16537                    MultibufferSelectionMode::All,
16538                    window,
16539                    cx,
16540                );
16541            })
16542        })
16543        .detach();
16544    }
16545
16546    /// Adds a row highlight for the given range. If a row has multiple highlights, the
16547    /// last highlight added will be used.
16548    ///
16549    /// If the range ends at the beginning of a line, then that line will not be highlighted.
16550    pub fn highlight_rows<T: 'static>(
16551        &mut self,
16552        range: Range<Anchor>,
16553        color: Hsla,
16554        should_autoscroll: bool,
16555        cx: &mut Context<Self>,
16556    ) {
16557        let snapshot = self.buffer().read(cx).snapshot(cx);
16558        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16559        let ix = row_highlights.binary_search_by(|highlight| {
16560            Ordering::Equal
16561                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
16562                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
16563        });
16564
16565        if let Err(mut ix) = ix {
16566            let index = post_inc(&mut self.highlight_order);
16567
16568            // If this range intersects with the preceding highlight, then merge it with
16569            // the preceding highlight. Otherwise insert a new highlight.
16570            let mut merged = false;
16571            if ix > 0 {
16572                let prev_highlight = &mut row_highlights[ix - 1];
16573                if prev_highlight
16574                    .range
16575                    .end
16576                    .cmp(&range.start, &snapshot)
16577                    .is_ge()
16578                {
16579                    ix -= 1;
16580                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
16581                        prev_highlight.range.end = range.end;
16582                    }
16583                    merged = true;
16584                    prev_highlight.index = index;
16585                    prev_highlight.color = color;
16586                    prev_highlight.should_autoscroll = should_autoscroll;
16587                }
16588            }
16589
16590            if !merged {
16591                row_highlights.insert(
16592                    ix,
16593                    RowHighlight {
16594                        range: range.clone(),
16595                        index,
16596                        color,
16597                        should_autoscroll,
16598                    },
16599                );
16600            }
16601
16602            // If any of the following highlights intersect with this one, merge them.
16603            while let Some(next_highlight) = row_highlights.get(ix + 1) {
16604                let highlight = &row_highlights[ix];
16605                if next_highlight
16606                    .range
16607                    .start
16608                    .cmp(&highlight.range.end, &snapshot)
16609                    .is_le()
16610                {
16611                    if next_highlight
16612                        .range
16613                        .end
16614                        .cmp(&highlight.range.end, &snapshot)
16615                        .is_gt()
16616                    {
16617                        row_highlights[ix].range.end = next_highlight.range.end;
16618                    }
16619                    row_highlights.remove(ix + 1);
16620                } else {
16621                    break;
16622                }
16623            }
16624        }
16625    }
16626
16627    /// Remove any highlighted row ranges of the given type that intersect the
16628    /// given ranges.
16629    pub fn remove_highlighted_rows<T: 'static>(
16630        &mut self,
16631        ranges_to_remove: Vec<Range<Anchor>>,
16632        cx: &mut Context<Self>,
16633    ) {
16634        let snapshot = self.buffer().read(cx).snapshot(cx);
16635        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16636        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16637        row_highlights.retain(|highlight| {
16638            while let Some(range_to_remove) = ranges_to_remove.peek() {
16639                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16640                    Ordering::Less | Ordering::Equal => {
16641                        ranges_to_remove.next();
16642                    }
16643                    Ordering::Greater => {
16644                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16645                            Ordering::Less | Ordering::Equal => {
16646                                return false;
16647                            }
16648                            Ordering::Greater => break,
16649                        }
16650                    }
16651                }
16652            }
16653
16654            true
16655        })
16656    }
16657
16658    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16659    pub fn clear_row_highlights<T: 'static>(&mut self) {
16660        self.highlighted_rows.remove(&TypeId::of::<T>());
16661    }
16662
16663    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
16664    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
16665        self.highlighted_rows
16666            .get(&TypeId::of::<T>())
16667            .map_or(&[] as &[_], |vec| vec.as_slice())
16668            .iter()
16669            .map(|highlight| (highlight.range.clone(), highlight.color))
16670    }
16671
16672    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
16673    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
16674    /// Allows to ignore certain kinds of highlights.
16675    pub fn highlighted_display_rows(
16676        &self,
16677        window: &mut Window,
16678        cx: &mut App,
16679    ) -> BTreeMap<DisplayRow, LineHighlight> {
16680        let snapshot = self.snapshot(window, cx);
16681        let mut used_highlight_orders = HashMap::default();
16682        self.highlighted_rows
16683            .iter()
16684            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16685            .fold(
16686                BTreeMap::<DisplayRow, LineHighlight>::new(),
16687                |mut unique_rows, highlight| {
16688                    let start = highlight.range.start.to_display_point(&snapshot);
16689                    let end = highlight.range.end.to_display_point(&snapshot);
16690                    let start_row = start.row().0;
16691                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16692                        && end.column() == 0
16693                    {
16694                        end.row().0.saturating_sub(1)
16695                    } else {
16696                        end.row().0
16697                    };
16698                    for row in start_row..=end_row {
16699                        let used_index =
16700                            used_highlight_orders.entry(row).or_insert(highlight.index);
16701                        if highlight.index >= *used_index {
16702                            *used_index = highlight.index;
16703                            unique_rows.insert(DisplayRow(row), highlight.color.into());
16704                        }
16705                    }
16706                    unique_rows
16707                },
16708            )
16709    }
16710
16711    pub fn highlighted_display_row_for_autoscroll(
16712        &self,
16713        snapshot: &DisplaySnapshot,
16714    ) -> Option<DisplayRow> {
16715        self.highlighted_rows
16716            .values()
16717            .flat_map(|highlighted_rows| highlighted_rows.iter())
16718            .filter_map(|highlight| {
16719                if highlight.should_autoscroll {
16720                    Some(highlight.range.start.to_display_point(snapshot).row())
16721                } else {
16722                    None
16723                }
16724            })
16725            .min()
16726    }
16727
16728    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16729        self.highlight_background::<SearchWithinRange>(
16730            ranges,
16731            |colors| colors.editor_document_highlight_read_background,
16732            cx,
16733        )
16734    }
16735
16736    pub fn set_breadcrumb_header(&mut self, new_header: String) {
16737        self.breadcrumb_header = Some(new_header);
16738    }
16739
16740    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16741        self.clear_background_highlights::<SearchWithinRange>(cx);
16742    }
16743
16744    pub fn highlight_background<T: 'static>(
16745        &mut self,
16746        ranges: &[Range<Anchor>],
16747        color_fetcher: fn(&ThemeColors) -> Hsla,
16748        cx: &mut Context<Self>,
16749    ) {
16750        self.background_highlights
16751            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16752        self.scrollbar_marker_state.dirty = true;
16753        cx.notify();
16754    }
16755
16756    pub fn clear_background_highlights<T: 'static>(
16757        &mut self,
16758        cx: &mut Context<Self>,
16759    ) -> Option<BackgroundHighlight> {
16760        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16761        if !text_highlights.1.is_empty() {
16762            self.scrollbar_marker_state.dirty = true;
16763            cx.notify();
16764        }
16765        Some(text_highlights)
16766    }
16767
16768    pub fn highlight_gutter<T: 'static>(
16769        &mut self,
16770        ranges: &[Range<Anchor>],
16771        color_fetcher: fn(&App) -> Hsla,
16772        cx: &mut Context<Self>,
16773    ) {
16774        self.gutter_highlights
16775            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16776        cx.notify();
16777    }
16778
16779    pub fn clear_gutter_highlights<T: 'static>(
16780        &mut self,
16781        cx: &mut Context<Self>,
16782    ) -> Option<GutterHighlight> {
16783        cx.notify();
16784        self.gutter_highlights.remove(&TypeId::of::<T>())
16785    }
16786
16787    #[cfg(feature = "test-support")]
16788    pub fn all_text_background_highlights(
16789        &self,
16790        window: &mut Window,
16791        cx: &mut Context<Self>,
16792    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16793        let snapshot = self.snapshot(window, cx);
16794        let buffer = &snapshot.buffer_snapshot;
16795        let start = buffer.anchor_before(0);
16796        let end = buffer.anchor_after(buffer.len());
16797        let theme = cx.theme().colors();
16798        self.background_highlights_in_range(start..end, &snapshot, theme)
16799    }
16800
16801    #[cfg(feature = "test-support")]
16802    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
16803        let snapshot = self.buffer().read(cx).snapshot(cx);
16804
16805        let highlights = self
16806            .background_highlights
16807            .get(&TypeId::of::<items::BufferSearchHighlights>());
16808
16809        if let Some((_color, ranges)) = highlights {
16810            ranges
16811                .iter()
16812                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
16813                .collect_vec()
16814        } else {
16815            vec![]
16816        }
16817    }
16818
16819    fn document_highlights_for_position<'a>(
16820        &'a self,
16821        position: Anchor,
16822        buffer: &'a MultiBufferSnapshot,
16823    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
16824        let read_highlights = self
16825            .background_highlights
16826            .get(&TypeId::of::<DocumentHighlightRead>())
16827            .map(|h| &h.1);
16828        let write_highlights = self
16829            .background_highlights
16830            .get(&TypeId::of::<DocumentHighlightWrite>())
16831            .map(|h| &h.1);
16832        let left_position = position.bias_left(buffer);
16833        let right_position = position.bias_right(buffer);
16834        read_highlights
16835            .into_iter()
16836            .chain(write_highlights)
16837            .flat_map(move |ranges| {
16838                let start_ix = match ranges.binary_search_by(|probe| {
16839                    let cmp = probe.end.cmp(&left_position, buffer);
16840                    if cmp.is_ge() {
16841                        Ordering::Greater
16842                    } else {
16843                        Ordering::Less
16844                    }
16845                }) {
16846                    Ok(i) | Err(i) => i,
16847                };
16848
16849                ranges[start_ix..]
16850                    .iter()
16851                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
16852            })
16853    }
16854
16855    pub fn has_background_highlights<T: 'static>(&self) -> bool {
16856        self.background_highlights
16857            .get(&TypeId::of::<T>())
16858            .map_or(false, |(_, highlights)| !highlights.is_empty())
16859    }
16860
16861    pub fn background_highlights_in_range(
16862        &self,
16863        search_range: Range<Anchor>,
16864        display_snapshot: &DisplaySnapshot,
16865        theme: &ThemeColors,
16866    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16867        let mut results = Vec::new();
16868        for (color_fetcher, ranges) in self.background_highlights.values() {
16869            let color = color_fetcher(theme);
16870            let start_ix = match ranges.binary_search_by(|probe| {
16871                let cmp = probe
16872                    .end
16873                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16874                if cmp.is_gt() {
16875                    Ordering::Greater
16876                } else {
16877                    Ordering::Less
16878                }
16879            }) {
16880                Ok(i) | Err(i) => i,
16881            };
16882            for range in &ranges[start_ix..] {
16883                if range
16884                    .start
16885                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16886                    .is_ge()
16887                {
16888                    break;
16889                }
16890
16891                let start = range.start.to_display_point(display_snapshot);
16892                let end = range.end.to_display_point(display_snapshot);
16893                results.push((start..end, color))
16894            }
16895        }
16896        results
16897    }
16898
16899    pub fn background_highlight_row_ranges<T: 'static>(
16900        &self,
16901        search_range: Range<Anchor>,
16902        display_snapshot: &DisplaySnapshot,
16903        count: usize,
16904    ) -> Vec<RangeInclusive<DisplayPoint>> {
16905        let mut results = Vec::new();
16906        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
16907            return vec![];
16908        };
16909
16910        let start_ix = match ranges.binary_search_by(|probe| {
16911            let cmp = probe
16912                .end
16913                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16914            if cmp.is_gt() {
16915                Ordering::Greater
16916            } else {
16917                Ordering::Less
16918            }
16919        }) {
16920            Ok(i) | Err(i) => i,
16921        };
16922        let mut push_region = |start: Option<Point>, end: Option<Point>| {
16923            if let (Some(start_display), Some(end_display)) = (start, end) {
16924                results.push(
16925                    start_display.to_display_point(display_snapshot)
16926                        ..=end_display.to_display_point(display_snapshot),
16927                );
16928            }
16929        };
16930        let mut start_row: Option<Point> = None;
16931        let mut end_row: Option<Point> = None;
16932        if ranges.len() > count {
16933            return Vec::new();
16934        }
16935        for range in &ranges[start_ix..] {
16936            if range
16937                .start
16938                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16939                .is_ge()
16940            {
16941                break;
16942            }
16943            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
16944            if let Some(current_row) = &end_row {
16945                if end.row == current_row.row {
16946                    continue;
16947                }
16948            }
16949            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
16950            if start_row.is_none() {
16951                assert_eq!(end_row, None);
16952                start_row = Some(start);
16953                end_row = Some(end);
16954                continue;
16955            }
16956            if let Some(current_end) = end_row.as_mut() {
16957                if start.row > current_end.row + 1 {
16958                    push_region(start_row, end_row);
16959                    start_row = Some(start);
16960                    end_row = Some(end);
16961                } else {
16962                    // Merge two hunks.
16963                    *current_end = end;
16964                }
16965            } else {
16966                unreachable!();
16967            }
16968        }
16969        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
16970        push_region(start_row, end_row);
16971        results
16972    }
16973
16974    pub fn gutter_highlights_in_range(
16975        &self,
16976        search_range: Range<Anchor>,
16977        display_snapshot: &DisplaySnapshot,
16978        cx: &App,
16979    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16980        let mut results = Vec::new();
16981        for (color_fetcher, ranges) in self.gutter_highlights.values() {
16982            let color = color_fetcher(cx);
16983            let start_ix = match ranges.binary_search_by(|probe| {
16984                let cmp = probe
16985                    .end
16986                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16987                if cmp.is_gt() {
16988                    Ordering::Greater
16989                } else {
16990                    Ordering::Less
16991                }
16992            }) {
16993                Ok(i) | Err(i) => i,
16994            };
16995            for range in &ranges[start_ix..] {
16996                if range
16997                    .start
16998                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16999                    .is_ge()
17000                {
17001                    break;
17002                }
17003
17004                let start = range.start.to_display_point(display_snapshot);
17005                let end = range.end.to_display_point(display_snapshot);
17006                results.push((start..end, color))
17007            }
17008        }
17009        results
17010    }
17011
17012    /// Get the text ranges corresponding to the redaction query
17013    pub fn redacted_ranges(
17014        &self,
17015        search_range: Range<Anchor>,
17016        display_snapshot: &DisplaySnapshot,
17017        cx: &App,
17018    ) -> Vec<Range<DisplayPoint>> {
17019        display_snapshot
17020            .buffer_snapshot
17021            .redacted_ranges(search_range, |file| {
17022                if let Some(file) = file {
17023                    file.is_private()
17024                        && EditorSettings::get(
17025                            Some(SettingsLocation {
17026                                worktree_id: file.worktree_id(cx),
17027                                path: file.path().as_ref(),
17028                            }),
17029                            cx,
17030                        )
17031                        .redact_private_values
17032                } else {
17033                    false
17034                }
17035            })
17036            .map(|range| {
17037                range.start.to_display_point(display_snapshot)
17038                    ..range.end.to_display_point(display_snapshot)
17039            })
17040            .collect()
17041    }
17042
17043    pub fn highlight_text<T: 'static>(
17044        &mut self,
17045        ranges: Vec<Range<Anchor>>,
17046        style: HighlightStyle,
17047        cx: &mut Context<Self>,
17048    ) {
17049        self.display_map.update(cx, |map, _| {
17050            map.highlight_text(TypeId::of::<T>(), ranges, style)
17051        });
17052        cx.notify();
17053    }
17054
17055    pub(crate) fn highlight_inlays<T: 'static>(
17056        &mut self,
17057        highlights: Vec<InlayHighlight>,
17058        style: HighlightStyle,
17059        cx: &mut Context<Self>,
17060    ) {
17061        self.display_map.update(cx, |map, _| {
17062            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17063        });
17064        cx.notify();
17065    }
17066
17067    pub fn text_highlights<'a, T: 'static>(
17068        &'a self,
17069        cx: &'a App,
17070    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17071        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17072    }
17073
17074    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17075        let cleared = self
17076            .display_map
17077            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17078        if cleared {
17079            cx.notify();
17080        }
17081    }
17082
17083    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17084        (self.read_only(cx) || self.blink_manager.read(cx).visible())
17085            && self.focus_handle.is_focused(window)
17086    }
17087
17088    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17089        self.show_cursor_when_unfocused = is_enabled;
17090        cx.notify();
17091    }
17092
17093    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17094        cx.notify();
17095    }
17096
17097    fn on_buffer_event(
17098        &mut self,
17099        multibuffer: &Entity<MultiBuffer>,
17100        event: &multi_buffer::Event,
17101        window: &mut Window,
17102        cx: &mut Context<Self>,
17103    ) {
17104        match event {
17105            multi_buffer::Event::Edited {
17106                singleton_buffer_edited,
17107                edited_buffer: buffer_edited,
17108            } => {
17109                self.scrollbar_marker_state.dirty = true;
17110                self.active_indent_guides_state.dirty = true;
17111                self.refresh_active_diagnostics(cx);
17112                self.refresh_code_actions(window, cx);
17113                if self.has_active_inline_completion() {
17114                    self.update_visible_inline_completion(window, cx);
17115                }
17116                if let Some(buffer) = buffer_edited {
17117                    let buffer_id = buffer.read(cx).remote_id();
17118                    if !self.registered_buffers.contains_key(&buffer_id) {
17119                        if let Some(project) = self.project.as_ref() {
17120                            project.update(cx, |project, cx| {
17121                                self.registered_buffers.insert(
17122                                    buffer_id,
17123                                    project.register_buffer_with_language_servers(&buffer, cx),
17124                                );
17125                            })
17126                        }
17127                    }
17128                }
17129                cx.emit(EditorEvent::BufferEdited);
17130                cx.emit(SearchEvent::MatchesInvalidated);
17131                if *singleton_buffer_edited {
17132                    if let Some(project) = &self.project {
17133                        #[allow(clippy::mutable_key_type)]
17134                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17135                            multibuffer
17136                                .all_buffers()
17137                                .into_iter()
17138                                .filter_map(|buffer| {
17139                                    buffer.update(cx, |buffer, cx| {
17140                                        let language = buffer.language()?;
17141                                        let should_discard = project.update(cx, |project, cx| {
17142                                            project.is_local()
17143                                                && !project.has_language_servers_for(buffer, cx)
17144                                        });
17145                                        should_discard.not().then_some(language.clone())
17146                                    })
17147                                })
17148                                .collect::<HashSet<_>>()
17149                        });
17150                        if !languages_affected.is_empty() {
17151                            self.refresh_inlay_hints(
17152                                InlayHintRefreshReason::BufferEdited(languages_affected),
17153                                cx,
17154                            );
17155                        }
17156                    }
17157                }
17158
17159                let Some(project) = &self.project else { return };
17160                let (telemetry, is_via_ssh) = {
17161                    let project = project.read(cx);
17162                    let telemetry = project.client().telemetry().clone();
17163                    let is_via_ssh = project.is_via_ssh();
17164                    (telemetry, is_via_ssh)
17165                };
17166                refresh_linked_ranges(self, window, cx);
17167                telemetry.log_edit_event("editor", is_via_ssh);
17168            }
17169            multi_buffer::Event::ExcerptsAdded {
17170                buffer,
17171                predecessor,
17172                excerpts,
17173            } => {
17174                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17175                let buffer_id = buffer.read(cx).remote_id();
17176                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17177                    if let Some(project) = &self.project {
17178                        get_uncommitted_diff_for_buffer(
17179                            project,
17180                            [buffer.clone()],
17181                            self.buffer.clone(),
17182                            cx,
17183                        )
17184                        .detach();
17185                    }
17186                }
17187                cx.emit(EditorEvent::ExcerptsAdded {
17188                    buffer: buffer.clone(),
17189                    predecessor: *predecessor,
17190                    excerpts: excerpts.clone(),
17191                });
17192                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17193            }
17194            multi_buffer::Event::ExcerptsRemoved { ids } => {
17195                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17196                let buffer = self.buffer.read(cx);
17197                self.registered_buffers
17198                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17199                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17200                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
17201            }
17202            multi_buffer::Event::ExcerptsEdited {
17203                excerpt_ids,
17204                buffer_ids,
17205            } => {
17206                self.display_map.update(cx, |map, cx| {
17207                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
17208                });
17209                cx.emit(EditorEvent::ExcerptsEdited {
17210                    ids: excerpt_ids.clone(),
17211                })
17212            }
17213            multi_buffer::Event::ExcerptsExpanded { ids } => {
17214                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17215                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17216            }
17217            multi_buffer::Event::Reparsed(buffer_id) => {
17218                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17219                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17220
17221                cx.emit(EditorEvent::Reparsed(*buffer_id));
17222            }
17223            multi_buffer::Event::DiffHunksToggled => {
17224                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17225            }
17226            multi_buffer::Event::LanguageChanged(buffer_id) => {
17227                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17228                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17229                cx.emit(EditorEvent::Reparsed(*buffer_id));
17230                cx.notify();
17231            }
17232            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17233            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17234            multi_buffer::Event::FileHandleChanged
17235            | multi_buffer::Event::Reloaded
17236            | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17237            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17238            multi_buffer::Event::DiagnosticsUpdated => {
17239                self.refresh_active_diagnostics(cx);
17240                self.refresh_inline_diagnostics(true, window, cx);
17241                self.scrollbar_marker_state.dirty = true;
17242                cx.notify();
17243            }
17244            _ => {}
17245        };
17246    }
17247
17248    fn on_display_map_changed(
17249        &mut self,
17250        _: Entity<DisplayMap>,
17251        _: &mut Window,
17252        cx: &mut Context<Self>,
17253    ) {
17254        cx.notify();
17255    }
17256
17257    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17258        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17259        self.update_edit_prediction_settings(cx);
17260        self.refresh_inline_completion(true, false, window, cx);
17261        self.refresh_inlay_hints(
17262            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17263                self.selections.newest_anchor().head(),
17264                &self.buffer.read(cx).snapshot(cx),
17265                cx,
17266            )),
17267            cx,
17268        );
17269
17270        let old_cursor_shape = self.cursor_shape;
17271
17272        {
17273            let editor_settings = EditorSettings::get_global(cx);
17274            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17275            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17276            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17277            self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17278        }
17279
17280        if old_cursor_shape != self.cursor_shape {
17281            cx.emit(EditorEvent::CursorShapeChanged);
17282        }
17283
17284        let project_settings = ProjectSettings::get_global(cx);
17285        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17286
17287        if self.mode.is_full() {
17288            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17289            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17290            if self.show_inline_diagnostics != show_inline_diagnostics {
17291                self.show_inline_diagnostics = show_inline_diagnostics;
17292                self.refresh_inline_diagnostics(false, window, cx);
17293            }
17294
17295            if self.git_blame_inline_enabled != inline_blame_enabled {
17296                self.toggle_git_blame_inline_internal(false, window, cx);
17297            }
17298        }
17299
17300        cx.notify();
17301    }
17302
17303    pub fn set_searchable(&mut self, searchable: bool) {
17304        self.searchable = searchable;
17305    }
17306
17307    pub fn searchable(&self) -> bool {
17308        self.searchable
17309    }
17310
17311    fn open_proposed_changes_editor(
17312        &mut self,
17313        _: &OpenProposedChangesEditor,
17314        window: &mut Window,
17315        cx: &mut Context<Self>,
17316    ) {
17317        let Some(workspace) = self.workspace() else {
17318            cx.propagate();
17319            return;
17320        };
17321
17322        let selections = self.selections.all::<usize>(cx);
17323        let multi_buffer = self.buffer.read(cx);
17324        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17325        let mut new_selections_by_buffer = HashMap::default();
17326        for selection in selections {
17327            for (buffer, range, _) in
17328                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17329            {
17330                let mut range = range.to_point(buffer);
17331                range.start.column = 0;
17332                range.end.column = buffer.line_len(range.end.row);
17333                new_selections_by_buffer
17334                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17335                    .or_insert(Vec::new())
17336                    .push(range)
17337            }
17338        }
17339
17340        let proposed_changes_buffers = new_selections_by_buffer
17341            .into_iter()
17342            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17343            .collect::<Vec<_>>();
17344        let proposed_changes_editor = cx.new(|cx| {
17345            ProposedChangesEditor::new(
17346                "Proposed changes",
17347                proposed_changes_buffers,
17348                self.project.clone(),
17349                window,
17350                cx,
17351            )
17352        });
17353
17354        window.defer(cx, move |window, cx| {
17355            workspace.update(cx, |workspace, cx| {
17356                workspace.active_pane().update(cx, |pane, cx| {
17357                    pane.add_item(
17358                        Box::new(proposed_changes_editor),
17359                        true,
17360                        true,
17361                        None,
17362                        window,
17363                        cx,
17364                    );
17365                });
17366            });
17367        });
17368    }
17369
17370    pub fn open_excerpts_in_split(
17371        &mut self,
17372        _: &OpenExcerptsSplit,
17373        window: &mut Window,
17374        cx: &mut Context<Self>,
17375    ) {
17376        self.open_excerpts_common(None, true, window, cx)
17377    }
17378
17379    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
17380        self.open_excerpts_common(None, false, window, cx)
17381    }
17382
17383    fn open_excerpts_common(
17384        &mut self,
17385        jump_data: Option<JumpData>,
17386        split: bool,
17387        window: &mut Window,
17388        cx: &mut Context<Self>,
17389    ) {
17390        let Some(workspace) = self.workspace() else {
17391            cx.propagate();
17392            return;
17393        };
17394
17395        if self.buffer.read(cx).is_singleton() {
17396            cx.propagate();
17397            return;
17398        }
17399
17400        let mut new_selections_by_buffer = HashMap::default();
17401        match &jump_data {
17402            Some(JumpData::MultiBufferPoint {
17403                excerpt_id,
17404                position,
17405                anchor,
17406                line_offset_from_top,
17407            }) => {
17408                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
17409                if let Some(buffer) = multi_buffer_snapshot
17410                    .buffer_id_for_excerpt(*excerpt_id)
17411                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
17412                {
17413                    let buffer_snapshot = buffer.read(cx).snapshot();
17414                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
17415                        language::ToPoint::to_point(anchor, &buffer_snapshot)
17416                    } else {
17417                        buffer_snapshot.clip_point(*position, Bias::Left)
17418                    };
17419                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
17420                    new_selections_by_buffer.insert(
17421                        buffer,
17422                        (
17423                            vec![jump_to_offset..jump_to_offset],
17424                            Some(*line_offset_from_top),
17425                        ),
17426                    );
17427                }
17428            }
17429            Some(JumpData::MultiBufferRow {
17430                row,
17431                line_offset_from_top,
17432            }) => {
17433                let point = MultiBufferPoint::new(row.0, 0);
17434                if let Some((buffer, buffer_point, _)) =
17435                    self.buffer.read(cx).point_to_buffer_point(point, cx)
17436                {
17437                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
17438                    new_selections_by_buffer
17439                        .entry(buffer)
17440                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
17441                        .0
17442                        .push(buffer_offset..buffer_offset)
17443                }
17444            }
17445            None => {
17446                let selections = self.selections.all::<usize>(cx);
17447                let multi_buffer = self.buffer.read(cx);
17448                for selection in selections {
17449                    for (snapshot, range, _, anchor) in multi_buffer
17450                        .snapshot(cx)
17451                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
17452                    {
17453                        if let Some(anchor) = anchor {
17454                            // selection is in a deleted hunk
17455                            let Some(buffer_id) = anchor.buffer_id else {
17456                                continue;
17457                            };
17458                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
17459                                continue;
17460                            };
17461                            let offset = text::ToOffset::to_offset(
17462                                &anchor.text_anchor,
17463                                &buffer_handle.read(cx).snapshot(),
17464                            );
17465                            let range = offset..offset;
17466                            new_selections_by_buffer
17467                                .entry(buffer_handle)
17468                                .or_insert((Vec::new(), None))
17469                                .0
17470                                .push(range)
17471                        } else {
17472                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
17473                            else {
17474                                continue;
17475                            };
17476                            new_selections_by_buffer
17477                                .entry(buffer_handle)
17478                                .or_insert((Vec::new(), None))
17479                                .0
17480                                .push(range)
17481                        }
17482                    }
17483                }
17484            }
17485        }
17486
17487        new_selections_by_buffer
17488            .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
17489
17490        if new_selections_by_buffer.is_empty() {
17491            return;
17492        }
17493
17494        // We defer the pane interaction because we ourselves are a workspace item
17495        // and activating a new item causes the pane to call a method on us reentrantly,
17496        // which panics if we're on the stack.
17497        window.defer(cx, move |window, cx| {
17498            workspace.update(cx, |workspace, cx| {
17499                let pane = if split {
17500                    workspace.adjacent_pane(window, cx)
17501                } else {
17502                    workspace.active_pane().clone()
17503                };
17504
17505                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
17506                    let editor = buffer
17507                        .read(cx)
17508                        .file()
17509                        .is_none()
17510                        .then(|| {
17511                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
17512                            // so `workspace.open_project_item` will never find them, always opening a new editor.
17513                            // Instead, we try to activate the existing editor in the pane first.
17514                            let (editor, pane_item_index) =
17515                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
17516                                    let editor = item.downcast::<Editor>()?;
17517                                    let singleton_buffer =
17518                                        editor.read(cx).buffer().read(cx).as_singleton()?;
17519                                    if singleton_buffer == buffer {
17520                                        Some((editor, i))
17521                                    } else {
17522                                        None
17523                                    }
17524                                })?;
17525                            pane.update(cx, |pane, cx| {
17526                                pane.activate_item(pane_item_index, true, true, window, cx)
17527                            });
17528                            Some(editor)
17529                        })
17530                        .flatten()
17531                        .unwrap_or_else(|| {
17532                            workspace.open_project_item::<Self>(
17533                                pane.clone(),
17534                                buffer,
17535                                true,
17536                                true,
17537                                window,
17538                                cx,
17539                            )
17540                        });
17541
17542                    editor.update(cx, |editor, cx| {
17543                        let autoscroll = match scroll_offset {
17544                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
17545                            None => Autoscroll::newest(),
17546                        };
17547                        let nav_history = editor.nav_history.take();
17548                        editor.change_selections(Some(autoscroll), window, cx, |s| {
17549                            s.select_ranges(ranges);
17550                        });
17551                        editor.nav_history = nav_history;
17552                    });
17553                }
17554            })
17555        });
17556    }
17557
17558    // For now, don't allow opening excerpts in buffers that aren't backed by
17559    // regular project files.
17560    fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
17561        file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
17562    }
17563
17564    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
17565        let snapshot = self.buffer.read(cx).read(cx);
17566        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
17567        Some(
17568            ranges
17569                .iter()
17570                .map(move |range| {
17571                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
17572                })
17573                .collect(),
17574        )
17575    }
17576
17577    fn selection_replacement_ranges(
17578        &self,
17579        range: Range<OffsetUtf16>,
17580        cx: &mut App,
17581    ) -> Vec<Range<OffsetUtf16>> {
17582        let selections = self.selections.all::<OffsetUtf16>(cx);
17583        let newest_selection = selections
17584            .iter()
17585            .max_by_key(|selection| selection.id)
17586            .unwrap();
17587        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
17588        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
17589        let snapshot = self.buffer.read(cx).read(cx);
17590        selections
17591            .into_iter()
17592            .map(|mut selection| {
17593                selection.start.0 =
17594                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
17595                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
17596                snapshot.clip_offset_utf16(selection.start, Bias::Left)
17597                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
17598            })
17599            .collect()
17600    }
17601
17602    fn report_editor_event(
17603        &self,
17604        event_type: &'static str,
17605        file_extension: Option<String>,
17606        cx: &App,
17607    ) {
17608        if cfg!(any(test, feature = "test-support")) {
17609            return;
17610        }
17611
17612        let Some(project) = &self.project else { return };
17613
17614        // If None, we are in a file without an extension
17615        let file = self
17616            .buffer
17617            .read(cx)
17618            .as_singleton()
17619            .and_then(|b| b.read(cx).file());
17620        let file_extension = file_extension.or(file
17621            .as_ref()
17622            .and_then(|file| Path::new(file.file_name(cx)).extension())
17623            .and_then(|e| e.to_str())
17624            .map(|a| a.to_string()));
17625
17626        let vim_mode = cx
17627            .global::<SettingsStore>()
17628            .raw_user_settings()
17629            .get("vim_mode")
17630            == Some(&serde_json::Value::Bool(true));
17631
17632        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
17633        let copilot_enabled = edit_predictions_provider
17634            == language::language_settings::EditPredictionProvider::Copilot;
17635        let copilot_enabled_for_language = self
17636            .buffer
17637            .read(cx)
17638            .language_settings(cx)
17639            .show_edit_predictions;
17640
17641        let project = project.read(cx);
17642        telemetry::event!(
17643            event_type,
17644            file_extension,
17645            vim_mode,
17646            copilot_enabled,
17647            copilot_enabled_for_language,
17648            edit_predictions_provider,
17649            is_via_ssh = project.is_via_ssh(),
17650        );
17651    }
17652
17653    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
17654    /// with each line being an array of {text, highlight} objects.
17655    fn copy_highlight_json(
17656        &mut self,
17657        _: &CopyHighlightJson,
17658        window: &mut Window,
17659        cx: &mut Context<Self>,
17660    ) {
17661        #[derive(Serialize)]
17662        struct Chunk<'a> {
17663            text: String,
17664            highlight: Option<&'a str>,
17665        }
17666
17667        let snapshot = self.buffer.read(cx).snapshot(cx);
17668        let range = self
17669            .selected_text_range(false, window, cx)
17670            .and_then(|selection| {
17671                if selection.range.is_empty() {
17672                    None
17673                } else {
17674                    Some(selection.range)
17675                }
17676            })
17677            .unwrap_or_else(|| 0..snapshot.len());
17678
17679        let chunks = snapshot.chunks(range, true);
17680        let mut lines = Vec::new();
17681        let mut line: VecDeque<Chunk> = VecDeque::new();
17682
17683        let Some(style) = self.style.as_ref() else {
17684            return;
17685        };
17686
17687        for chunk in chunks {
17688            let highlight = chunk
17689                .syntax_highlight_id
17690                .and_then(|id| id.name(&style.syntax));
17691            let mut chunk_lines = chunk.text.split('\n').peekable();
17692            while let Some(text) = chunk_lines.next() {
17693                let mut merged_with_last_token = false;
17694                if let Some(last_token) = line.back_mut() {
17695                    if last_token.highlight == highlight {
17696                        last_token.text.push_str(text);
17697                        merged_with_last_token = true;
17698                    }
17699                }
17700
17701                if !merged_with_last_token {
17702                    line.push_back(Chunk {
17703                        text: text.into(),
17704                        highlight,
17705                    });
17706                }
17707
17708                if chunk_lines.peek().is_some() {
17709                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
17710                        line.pop_front();
17711                    }
17712                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
17713                        line.pop_back();
17714                    }
17715
17716                    lines.push(mem::take(&mut line));
17717                }
17718            }
17719        }
17720
17721        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17722            return;
17723        };
17724        cx.write_to_clipboard(ClipboardItem::new_string(lines));
17725    }
17726
17727    pub fn open_context_menu(
17728        &mut self,
17729        _: &OpenContextMenu,
17730        window: &mut Window,
17731        cx: &mut Context<Self>,
17732    ) {
17733        self.request_autoscroll(Autoscroll::newest(), cx);
17734        let position = self.selections.newest_display(cx).start;
17735        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17736    }
17737
17738    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17739        &self.inlay_hint_cache
17740    }
17741
17742    pub fn replay_insert_event(
17743        &mut self,
17744        text: &str,
17745        relative_utf16_range: Option<Range<isize>>,
17746        window: &mut Window,
17747        cx: &mut Context<Self>,
17748    ) {
17749        if !self.input_enabled {
17750            cx.emit(EditorEvent::InputIgnored { text: text.into() });
17751            return;
17752        }
17753        if let Some(relative_utf16_range) = relative_utf16_range {
17754            let selections = self.selections.all::<OffsetUtf16>(cx);
17755            self.change_selections(None, window, cx, |s| {
17756                let new_ranges = selections.into_iter().map(|range| {
17757                    let start = OffsetUtf16(
17758                        range
17759                            .head()
17760                            .0
17761                            .saturating_add_signed(relative_utf16_range.start),
17762                    );
17763                    let end = OffsetUtf16(
17764                        range
17765                            .head()
17766                            .0
17767                            .saturating_add_signed(relative_utf16_range.end),
17768                    );
17769                    start..end
17770                });
17771                s.select_ranges(new_ranges);
17772            });
17773        }
17774
17775        self.handle_input(text, window, cx);
17776    }
17777
17778    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
17779        let Some(provider) = self.semantics_provider.as_ref() else {
17780            return false;
17781        };
17782
17783        let mut supports = false;
17784        self.buffer().update(cx, |this, cx| {
17785            this.for_each_buffer(|buffer| {
17786                supports |= provider.supports_inlay_hints(buffer, cx);
17787            });
17788        });
17789
17790        supports
17791    }
17792
17793    pub fn is_focused(&self, window: &Window) -> bool {
17794        self.focus_handle.is_focused(window)
17795    }
17796
17797    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17798        cx.emit(EditorEvent::Focused);
17799
17800        if let Some(descendant) = self
17801            .last_focused_descendant
17802            .take()
17803            .and_then(|descendant| descendant.upgrade())
17804        {
17805            window.focus(&descendant);
17806        } else {
17807            if let Some(blame) = self.blame.as_ref() {
17808                blame.update(cx, GitBlame::focus)
17809            }
17810
17811            self.blink_manager.update(cx, BlinkManager::enable);
17812            self.show_cursor_names(window, cx);
17813            self.buffer.update(cx, |buffer, cx| {
17814                buffer.finalize_last_transaction(cx);
17815                if self.leader_peer_id.is_none() {
17816                    buffer.set_active_selections(
17817                        &self.selections.disjoint_anchors(),
17818                        self.selections.line_mode,
17819                        self.cursor_shape,
17820                        cx,
17821                    );
17822                }
17823            });
17824        }
17825    }
17826
17827    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17828        cx.emit(EditorEvent::FocusedIn)
17829    }
17830
17831    fn handle_focus_out(
17832        &mut self,
17833        event: FocusOutEvent,
17834        _window: &mut Window,
17835        cx: &mut Context<Self>,
17836    ) {
17837        if event.blurred != self.focus_handle {
17838            self.last_focused_descendant = Some(event.blurred);
17839        }
17840        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
17841    }
17842
17843    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17844        self.blink_manager.update(cx, BlinkManager::disable);
17845        self.buffer
17846            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
17847
17848        if let Some(blame) = self.blame.as_ref() {
17849            blame.update(cx, GitBlame::blur)
17850        }
17851        if !self.hover_state.focused(window, cx) {
17852            hide_hover(self, cx);
17853        }
17854        if !self
17855            .context_menu
17856            .borrow()
17857            .as_ref()
17858            .is_some_and(|context_menu| context_menu.focused(window, cx))
17859        {
17860            self.hide_context_menu(window, cx);
17861        }
17862        self.discard_inline_completion(false, cx);
17863        cx.emit(EditorEvent::Blurred);
17864        cx.notify();
17865    }
17866
17867    pub fn register_action<A: Action>(
17868        &mut self,
17869        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
17870    ) -> Subscription {
17871        let id = self.next_editor_action_id.post_inc();
17872        let listener = Arc::new(listener);
17873        self.editor_actions.borrow_mut().insert(
17874            id,
17875            Box::new(move |window, _| {
17876                let listener = listener.clone();
17877                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
17878                    let action = action.downcast_ref().unwrap();
17879                    if phase == DispatchPhase::Bubble {
17880                        listener(action, window, cx)
17881                    }
17882                })
17883            }),
17884        );
17885
17886        let editor_actions = self.editor_actions.clone();
17887        Subscription::new(move || {
17888            editor_actions.borrow_mut().remove(&id);
17889        })
17890    }
17891
17892    pub fn file_header_size(&self) -> u32 {
17893        FILE_HEADER_HEIGHT
17894    }
17895
17896    pub fn restore(
17897        &mut self,
17898        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
17899        window: &mut Window,
17900        cx: &mut Context<Self>,
17901    ) {
17902        let workspace = self.workspace();
17903        let project = self.project.as_ref();
17904        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
17905            let mut tasks = Vec::new();
17906            for (buffer_id, changes) in revert_changes {
17907                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
17908                    buffer.update(cx, |buffer, cx| {
17909                        buffer.edit(
17910                            changes
17911                                .into_iter()
17912                                .map(|(range, text)| (range, text.to_string())),
17913                            None,
17914                            cx,
17915                        );
17916                    });
17917
17918                    if let Some(project) =
17919                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
17920                    {
17921                        project.update(cx, |project, cx| {
17922                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
17923                        })
17924                    }
17925                }
17926            }
17927            tasks
17928        });
17929        cx.spawn_in(window, async move |_, cx| {
17930            for (buffer, task) in save_tasks {
17931                let result = task.await;
17932                if result.is_err() {
17933                    let Some(path) = buffer
17934                        .read_with(cx, |buffer, cx| buffer.project_path(cx))
17935                        .ok()
17936                    else {
17937                        continue;
17938                    };
17939                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
17940                        let Some(task) = cx
17941                            .update_window_entity(&workspace, |workspace, window, cx| {
17942                                workspace
17943                                    .open_path_preview(path, None, false, false, false, window, cx)
17944                            })
17945                            .ok()
17946                        else {
17947                            continue;
17948                        };
17949                        task.await.log_err();
17950                    }
17951                }
17952            }
17953        })
17954        .detach();
17955        self.change_selections(None, window, cx, |selections| selections.refresh());
17956    }
17957
17958    pub fn to_pixel_point(
17959        &self,
17960        source: multi_buffer::Anchor,
17961        editor_snapshot: &EditorSnapshot,
17962        window: &mut Window,
17963    ) -> Option<gpui::Point<Pixels>> {
17964        let source_point = source.to_display_point(editor_snapshot);
17965        self.display_to_pixel_point(source_point, editor_snapshot, window)
17966    }
17967
17968    pub fn display_to_pixel_point(
17969        &self,
17970        source: DisplayPoint,
17971        editor_snapshot: &EditorSnapshot,
17972        window: &mut Window,
17973    ) -> Option<gpui::Point<Pixels>> {
17974        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
17975        let text_layout_details = self.text_layout_details(window);
17976        let scroll_top = text_layout_details
17977            .scroll_anchor
17978            .scroll_position(editor_snapshot)
17979            .y;
17980
17981        if source.row().as_f32() < scroll_top.floor() {
17982            return None;
17983        }
17984        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
17985        let source_y = line_height * (source.row().as_f32() - scroll_top);
17986        Some(gpui::Point::new(source_x, source_y))
17987    }
17988
17989    pub fn has_visible_completions_menu(&self) -> bool {
17990        !self.edit_prediction_preview_is_active()
17991            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
17992                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
17993            })
17994    }
17995
17996    pub fn register_addon<T: Addon>(&mut self, instance: T) {
17997        self.addons
17998            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
17999    }
18000
18001    pub fn unregister_addon<T: Addon>(&mut self) {
18002        self.addons.remove(&std::any::TypeId::of::<T>());
18003    }
18004
18005    pub fn addon<T: Addon>(&self) -> Option<&T> {
18006        let type_id = std::any::TypeId::of::<T>();
18007        self.addons
18008            .get(&type_id)
18009            .and_then(|item| item.to_any().downcast_ref::<T>())
18010    }
18011
18012    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18013        let text_layout_details = self.text_layout_details(window);
18014        let style = &text_layout_details.editor_style;
18015        let font_id = window.text_system().resolve_font(&style.text.font());
18016        let font_size = style.text.font_size.to_pixels(window.rem_size());
18017        let line_height = style.text.line_height_in_pixels(window.rem_size());
18018        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18019
18020        gpui::Size::new(em_width, line_height)
18021    }
18022
18023    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18024        self.load_diff_task.clone()
18025    }
18026
18027    fn read_metadata_from_db(
18028        &mut self,
18029        item_id: u64,
18030        workspace_id: WorkspaceId,
18031        window: &mut Window,
18032        cx: &mut Context<Editor>,
18033    ) {
18034        if self.is_singleton(cx)
18035            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18036        {
18037            let buffer_snapshot = OnceCell::new();
18038
18039            if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18040                if !folds.is_empty() {
18041                    let snapshot =
18042                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18043                    self.fold_ranges(
18044                        folds
18045                            .into_iter()
18046                            .map(|(start, end)| {
18047                                snapshot.clip_offset(start, Bias::Left)
18048                                    ..snapshot.clip_offset(end, Bias::Right)
18049                            })
18050                            .collect(),
18051                        false,
18052                        window,
18053                        cx,
18054                    );
18055                }
18056            }
18057
18058            if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18059                if !selections.is_empty() {
18060                    let snapshot =
18061                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18062                    self.change_selections(None, window, cx, |s| {
18063                        s.select_ranges(selections.into_iter().map(|(start, end)| {
18064                            snapshot.clip_offset(start, Bias::Left)
18065                                ..snapshot.clip_offset(end, Bias::Right)
18066                        }));
18067                    });
18068                }
18069            };
18070        }
18071
18072        self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18073    }
18074}
18075
18076// Consider user intent and default settings
18077fn choose_completion_range(
18078    completion: &Completion,
18079    intent: CompletionIntent,
18080    buffer: &Entity<Buffer>,
18081    cx: &mut Context<Editor>,
18082) -> Range<usize> {
18083    fn should_replace(
18084        completion: &Completion,
18085        insert_range: &Range<text::Anchor>,
18086        intent: CompletionIntent,
18087        completion_mode_setting: LspInsertMode,
18088        buffer: &Buffer,
18089    ) -> bool {
18090        // specific actions take precedence over settings
18091        match intent {
18092            CompletionIntent::CompleteWithInsert => return false,
18093            CompletionIntent::CompleteWithReplace => return true,
18094            CompletionIntent::Complete | CompletionIntent::Compose => {}
18095        }
18096
18097        match completion_mode_setting {
18098            LspInsertMode::Insert => false,
18099            LspInsertMode::Replace => true,
18100            LspInsertMode::ReplaceSubsequence => {
18101                let mut text_to_replace = buffer.chars_for_range(
18102                    buffer.anchor_before(completion.replace_range.start)
18103                        ..buffer.anchor_after(completion.replace_range.end),
18104                );
18105                let mut completion_text = completion.new_text.chars();
18106
18107                // is `text_to_replace` a subsequence of `completion_text`
18108                text_to_replace
18109                    .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18110            }
18111            LspInsertMode::ReplaceSuffix => {
18112                let range_after_cursor = insert_range.end..completion.replace_range.end;
18113
18114                let text_after_cursor = buffer
18115                    .text_for_range(
18116                        buffer.anchor_before(range_after_cursor.start)
18117                            ..buffer.anchor_after(range_after_cursor.end),
18118                    )
18119                    .collect::<String>();
18120                completion.new_text.ends_with(&text_after_cursor)
18121            }
18122        }
18123    }
18124
18125    let buffer = buffer.read(cx);
18126
18127    if let CompletionSource::Lsp {
18128        insert_range: Some(insert_range),
18129        ..
18130    } = &completion.source
18131    {
18132        let completion_mode_setting =
18133            language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18134                .completions
18135                .lsp_insert_mode;
18136
18137        if !should_replace(
18138            completion,
18139            &insert_range,
18140            intent,
18141            completion_mode_setting,
18142            buffer,
18143        ) {
18144            return insert_range.to_offset(buffer);
18145        }
18146    }
18147
18148    completion.replace_range.to_offset(buffer)
18149}
18150
18151fn insert_extra_newline_brackets(
18152    buffer: &MultiBufferSnapshot,
18153    range: Range<usize>,
18154    language: &language::LanguageScope,
18155) -> bool {
18156    let leading_whitespace_len = buffer
18157        .reversed_chars_at(range.start)
18158        .take_while(|c| c.is_whitespace() && *c != '\n')
18159        .map(|c| c.len_utf8())
18160        .sum::<usize>();
18161    let trailing_whitespace_len = buffer
18162        .chars_at(range.end)
18163        .take_while(|c| c.is_whitespace() && *c != '\n')
18164        .map(|c| c.len_utf8())
18165        .sum::<usize>();
18166    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18167
18168    language.brackets().any(|(pair, enabled)| {
18169        let pair_start = pair.start.trim_end();
18170        let pair_end = pair.end.trim_start();
18171
18172        enabled
18173            && pair.newline
18174            && buffer.contains_str_at(range.end, pair_end)
18175            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18176    })
18177}
18178
18179fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18180    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18181        [(buffer, range, _)] => (*buffer, range.clone()),
18182        _ => return false,
18183    };
18184    let pair = {
18185        let mut result: Option<BracketMatch> = None;
18186
18187        for pair in buffer
18188            .all_bracket_ranges(range.clone())
18189            .filter(move |pair| {
18190                pair.open_range.start <= range.start && pair.close_range.end >= range.end
18191            })
18192        {
18193            let len = pair.close_range.end - pair.open_range.start;
18194
18195            if let Some(existing) = &result {
18196                let existing_len = existing.close_range.end - existing.open_range.start;
18197                if len > existing_len {
18198                    continue;
18199                }
18200            }
18201
18202            result = Some(pair);
18203        }
18204
18205        result
18206    };
18207    let Some(pair) = pair else {
18208        return false;
18209    };
18210    pair.newline_only
18211        && buffer
18212            .chars_for_range(pair.open_range.end..range.start)
18213            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18214            .all(|c| c.is_whitespace() && c != '\n')
18215}
18216
18217fn get_uncommitted_diff_for_buffer(
18218    project: &Entity<Project>,
18219    buffers: impl IntoIterator<Item = Entity<Buffer>>,
18220    buffer: Entity<MultiBuffer>,
18221    cx: &mut App,
18222) -> Task<()> {
18223    let mut tasks = Vec::new();
18224    project.update(cx, |project, cx| {
18225        for buffer in buffers {
18226            if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18227                tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18228            }
18229        }
18230    });
18231    cx.spawn(async move |cx| {
18232        let diffs = future::join_all(tasks).await;
18233        buffer
18234            .update(cx, |buffer, cx| {
18235                for diff in diffs.into_iter().flatten() {
18236                    buffer.add_diff(diff, cx);
18237                }
18238            })
18239            .ok();
18240    })
18241}
18242
18243fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18244    let tab_size = tab_size.get() as usize;
18245    let mut width = offset;
18246
18247    for ch in text.chars() {
18248        width += if ch == '\t' {
18249            tab_size - (width % tab_size)
18250        } else {
18251            1
18252        };
18253    }
18254
18255    width - offset
18256}
18257
18258#[cfg(test)]
18259mod tests {
18260    use super::*;
18261
18262    #[test]
18263    fn test_string_size_with_expanded_tabs() {
18264        let nz = |val| NonZeroU32::new(val).unwrap();
18265        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18266        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18267        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18268        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18269        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18270        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18271        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18272        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18273    }
18274}
18275
18276/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18277struct WordBreakingTokenizer<'a> {
18278    input: &'a str,
18279}
18280
18281impl<'a> WordBreakingTokenizer<'a> {
18282    fn new(input: &'a str) -> Self {
18283        Self { input }
18284    }
18285}
18286
18287fn is_char_ideographic(ch: char) -> bool {
18288    use unicode_script::Script::*;
18289    use unicode_script::UnicodeScript;
18290    matches!(ch.script(), Han | Tangut | Yi)
18291}
18292
18293fn is_grapheme_ideographic(text: &str) -> bool {
18294    text.chars().any(is_char_ideographic)
18295}
18296
18297fn is_grapheme_whitespace(text: &str) -> bool {
18298    text.chars().any(|x| x.is_whitespace())
18299}
18300
18301fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18302    text.chars().next().map_or(false, |ch| {
18303        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18304    })
18305}
18306
18307#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18308enum WordBreakToken<'a> {
18309    Word { token: &'a str, grapheme_len: usize },
18310    InlineWhitespace { token: &'a str, grapheme_len: usize },
18311    Newline,
18312}
18313
18314impl<'a> Iterator for WordBreakingTokenizer<'a> {
18315    /// Yields a span, the count of graphemes in the token, and whether it was
18316    /// whitespace. Note that it also breaks at word boundaries.
18317    type Item = WordBreakToken<'a>;
18318
18319    fn next(&mut self) -> Option<Self::Item> {
18320        use unicode_segmentation::UnicodeSegmentation;
18321        if self.input.is_empty() {
18322            return None;
18323        }
18324
18325        let mut iter = self.input.graphemes(true).peekable();
18326        let mut offset = 0;
18327        let mut grapheme_len = 0;
18328        if let Some(first_grapheme) = iter.next() {
18329            let is_newline = first_grapheme == "\n";
18330            let is_whitespace = is_grapheme_whitespace(first_grapheme);
18331            offset += first_grapheme.len();
18332            grapheme_len += 1;
18333            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
18334                if let Some(grapheme) = iter.peek().copied() {
18335                    if should_stay_with_preceding_ideograph(grapheme) {
18336                        offset += grapheme.len();
18337                        grapheme_len += 1;
18338                    }
18339                }
18340            } else {
18341                let mut words = self.input[offset..].split_word_bound_indices().peekable();
18342                let mut next_word_bound = words.peek().copied();
18343                if next_word_bound.map_or(false, |(i, _)| i == 0) {
18344                    next_word_bound = words.next();
18345                }
18346                while let Some(grapheme) = iter.peek().copied() {
18347                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
18348                        break;
18349                    };
18350                    if is_grapheme_whitespace(grapheme) != is_whitespace
18351                        || (grapheme == "\n") != is_newline
18352                    {
18353                        break;
18354                    };
18355                    offset += grapheme.len();
18356                    grapheme_len += 1;
18357                    iter.next();
18358                }
18359            }
18360            let token = &self.input[..offset];
18361            self.input = &self.input[offset..];
18362            if token == "\n" {
18363                Some(WordBreakToken::Newline)
18364            } else if is_whitespace {
18365                Some(WordBreakToken::InlineWhitespace {
18366                    token,
18367                    grapheme_len,
18368                })
18369            } else {
18370                Some(WordBreakToken::Word {
18371                    token,
18372                    grapheme_len,
18373                })
18374            }
18375        } else {
18376            None
18377        }
18378    }
18379}
18380
18381#[test]
18382fn test_word_breaking_tokenizer() {
18383    let tests: &[(&str, &[WordBreakToken<'static>])] = &[
18384        ("", &[]),
18385        ("  ", &[whitespace("  ", 2)]),
18386        ("Ʒ", &[word("Ʒ", 1)]),
18387        ("Ǽ", &[word("Ǽ", 1)]),
18388        ("", &[word("", 1)]),
18389        ("⋑⋑", &[word("⋑⋑", 2)]),
18390        (
18391            "原理,进而",
18392            &[word("", 1), word("理,", 2), word("", 1), word("", 1)],
18393        ),
18394        (
18395            "hello world",
18396            &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
18397        ),
18398        (
18399            "hello, world",
18400            &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
18401        ),
18402        (
18403            "  hello world",
18404            &[
18405                whitespace("  ", 2),
18406                word("hello", 5),
18407                whitespace(" ", 1),
18408                word("world", 5),
18409            ],
18410        ),
18411        (
18412            "这是什么 \n 钢笔",
18413            &[
18414                word("", 1),
18415                word("", 1),
18416                word("", 1),
18417                word("", 1),
18418                whitespace(" ", 1),
18419                newline(),
18420                whitespace(" ", 1),
18421                word("", 1),
18422                word("", 1),
18423            ],
18424        ),
18425        (" mutton", &[whitespace("", 1), word("mutton", 6)]),
18426    ];
18427
18428    fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18429        WordBreakToken::Word {
18430            token,
18431            grapheme_len,
18432        }
18433    }
18434
18435    fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18436        WordBreakToken::InlineWhitespace {
18437            token,
18438            grapheme_len,
18439        }
18440    }
18441
18442    fn newline() -> WordBreakToken<'static> {
18443        WordBreakToken::Newline
18444    }
18445
18446    for (input, result) in tests {
18447        assert_eq!(
18448            WordBreakingTokenizer::new(input)
18449                .collect::<Vec<_>>()
18450                .as_slice(),
18451            *result,
18452        );
18453    }
18454}
18455
18456fn wrap_with_prefix(
18457    line_prefix: String,
18458    unwrapped_text: String,
18459    wrap_column: usize,
18460    tab_size: NonZeroU32,
18461    preserve_existing_whitespace: bool,
18462) -> String {
18463    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
18464    let mut wrapped_text = String::new();
18465    let mut current_line = line_prefix.clone();
18466
18467    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
18468    let mut current_line_len = line_prefix_len;
18469    let mut in_whitespace = false;
18470    for token in tokenizer {
18471        let have_preceding_whitespace = in_whitespace;
18472        match token {
18473            WordBreakToken::Word {
18474                token,
18475                grapheme_len,
18476            } => {
18477                in_whitespace = false;
18478                if current_line_len + grapheme_len > wrap_column
18479                    && current_line_len != line_prefix_len
18480                {
18481                    wrapped_text.push_str(current_line.trim_end());
18482                    wrapped_text.push('\n');
18483                    current_line.truncate(line_prefix.len());
18484                    current_line_len = line_prefix_len;
18485                }
18486                current_line.push_str(token);
18487                current_line_len += grapheme_len;
18488            }
18489            WordBreakToken::InlineWhitespace {
18490                mut token,
18491                mut grapheme_len,
18492            } => {
18493                in_whitespace = true;
18494                if have_preceding_whitespace && !preserve_existing_whitespace {
18495                    continue;
18496                }
18497                if !preserve_existing_whitespace {
18498                    token = " ";
18499                    grapheme_len = 1;
18500                }
18501                if current_line_len + grapheme_len > wrap_column {
18502                    wrapped_text.push_str(current_line.trim_end());
18503                    wrapped_text.push('\n');
18504                    current_line.truncate(line_prefix.len());
18505                    current_line_len = line_prefix_len;
18506                } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
18507                    current_line.push_str(token);
18508                    current_line_len += grapheme_len;
18509                }
18510            }
18511            WordBreakToken::Newline => {
18512                in_whitespace = true;
18513                if preserve_existing_whitespace {
18514                    wrapped_text.push_str(current_line.trim_end());
18515                    wrapped_text.push('\n');
18516                    current_line.truncate(line_prefix.len());
18517                    current_line_len = line_prefix_len;
18518                } else if have_preceding_whitespace {
18519                    continue;
18520                } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
18521                {
18522                    wrapped_text.push_str(current_line.trim_end());
18523                    wrapped_text.push('\n');
18524                    current_line.truncate(line_prefix.len());
18525                    current_line_len = line_prefix_len;
18526                } else if current_line_len != line_prefix_len {
18527                    current_line.push(' ');
18528                    current_line_len += 1;
18529                }
18530            }
18531        }
18532    }
18533
18534    if !current_line.is_empty() {
18535        wrapped_text.push_str(&current_line);
18536    }
18537    wrapped_text
18538}
18539
18540#[test]
18541fn test_wrap_with_prefix() {
18542    assert_eq!(
18543        wrap_with_prefix(
18544            "# ".to_string(),
18545            "abcdefg".to_string(),
18546            4,
18547            NonZeroU32::new(4).unwrap(),
18548            false,
18549        ),
18550        "# abcdefg"
18551    );
18552    assert_eq!(
18553        wrap_with_prefix(
18554            "".to_string(),
18555            "\thello world".to_string(),
18556            8,
18557            NonZeroU32::new(4).unwrap(),
18558            false,
18559        ),
18560        "hello\nworld"
18561    );
18562    assert_eq!(
18563        wrap_with_prefix(
18564            "// ".to_string(),
18565            "xx \nyy zz aa bb cc".to_string(),
18566            12,
18567            NonZeroU32::new(4).unwrap(),
18568            false,
18569        ),
18570        "// xx yy zz\n// aa bb cc"
18571    );
18572    assert_eq!(
18573        wrap_with_prefix(
18574            String::new(),
18575            "这是什么 \n 钢笔".to_string(),
18576            3,
18577            NonZeroU32::new(4).unwrap(),
18578            false,
18579        ),
18580        "这是什\n么 钢\n"
18581    );
18582}
18583
18584pub trait CollaborationHub {
18585    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
18586    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
18587    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
18588}
18589
18590impl CollaborationHub for Entity<Project> {
18591    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
18592        self.read(cx).collaborators()
18593    }
18594
18595    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
18596        self.read(cx).user_store().read(cx).participant_indices()
18597    }
18598
18599    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
18600        let this = self.read(cx);
18601        let user_ids = this.collaborators().values().map(|c| c.user_id);
18602        this.user_store().read_with(cx, |user_store, cx| {
18603            user_store.participant_names(user_ids, cx)
18604        })
18605    }
18606}
18607
18608pub trait SemanticsProvider {
18609    fn hover(
18610        &self,
18611        buffer: &Entity<Buffer>,
18612        position: text::Anchor,
18613        cx: &mut App,
18614    ) -> Option<Task<Vec<project::Hover>>>;
18615
18616    fn inlay_hints(
18617        &self,
18618        buffer_handle: Entity<Buffer>,
18619        range: Range<text::Anchor>,
18620        cx: &mut App,
18621    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
18622
18623    fn resolve_inlay_hint(
18624        &self,
18625        hint: InlayHint,
18626        buffer_handle: Entity<Buffer>,
18627        server_id: LanguageServerId,
18628        cx: &mut App,
18629    ) -> Option<Task<anyhow::Result<InlayHint>>>;
18630
18631    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
18632
18633    fn document_highlights(
18634        &self,
18635        buffer: &Entity<Buffer>,
18636        position: text::Anchor,
18637        cx: &mut App,
18638    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
18639
18640    fn definitions(
18641        &self,
18642        buffer: &Entity<Buffer>,
18643        position: text::Anchor,
18644        kind: GotoDefinitionKind,
18645        cx: &mut App,
18646    ) -> Option<Task<Result<Vec<LocationLink>>>>;
18647
18648    fn range_for_rename(
18649        &self,
18650        buffer: &Entity<Buffer>,
18651        position: text::Anchor,
18652        cx: &mut App,
18653    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
18654
18655    fn perform_rename(
18656        &self,
18657        buffer: &Entity<Buffer>,
18658        position: text::Anchor,
18659        new_name: String,
18660        cx: &mut App,
18661    ) -> Option<Task<Result<ProjectTransaction>>>;
18662}
18663
18664pub trait CompletionProvider {
18665    fn completions(
18666        &self,
18667        excerpt_id: ExcerptId,
18668        buffer: &Entity<Buffer>,
18669        buffer_position: text::Anchor,
18670        trigger: CompletionContext,
18671        window: &mut Window,
18672        cx: &mut Context<Editor>,
18673    ) -> Task<Result<Option<Vec<Completion>>>>;
18674
18675    fn resolve_completions(
18676        &self,
18677        buffer: Entity<Buffer>,
18678        completion_indices: Vec<usize>,
18679        completions: Rc<RefCell<Box<[Completion]>>>,
18680        cx: &mut Context<Editor>,
18681    ) -> Task<Result<bool>>;
18682
18683    fn apply_additional_edits_for_completion(
18684        &self,
18685        _buffer: Entity<Buffer>,
18686        _completions: Rc<RefCell<Box<[Completion]>>>,
18687        _completion_index: usize,
18688        _push_to_history: bool,
18689        _cx: &mut Context<Editor>,
18690    ) -> Task<Result<Option<language::Transaction>>> {
18691        Task::ready(Ok(None))
18692    }
18693
18694    fn is_completion_trigger(
18695        &self,
18696        buffer: &Entity<Buffer>,
18697        position: language::Anchor,
18698        text: &str,
18699        trigger_in_words: bool,
18700        cx: &mut Context<Editor>,
18701    ) -> bool;
18702
18703    fn sort_completions(&self) -> bool {
18704        true
18705    }
18706
18707    fn filter_completions(&self) -> bool {
18708        true
18709    }
18710}
18711
18712pub trait CodeActionProvider {
18713    fn id(&self) -> Arc<str>;
18714
18715    fn code_actions(
18716        &self,
18717        buffer: &Entity<Buffer>,
18718        range: Range<text::Anchor>,
18719        window: &mut Window,
18720        cx: &mut App,
18721    ) -> Task<Result<Vec<CodeAction>>>;
18722
18723    fn apply_code_action(
18724        &self,
18725        buffer_handle: Entity<Buffer>,
18726        action: CodeAction,
18727        excerpt_id: ExcerptId,
18728        push_to_history: bool,
18729        window: &mut Window,
18730        cx: &mut App,
18731    ) -> Task<Result<ProjectTransaction>>;
18732}
18733
18734impl CodeActionProvider for Entity<Project> {
18735    fn id(&self) -> Arc<str> {
18736        "project".into()
18737    }
18738
18739    fn code_actions(
18740        &self,
18741        buffer: &Entity<Buffer>,
18742        range: Range<text::Anchor>,
18743        _window: &mut Window,
18744        cx: &mut App,
18745    ) -> Task<Result<Vec<CodeAction>>> {
18746        self.update(cx, |project, cx| {
18747            let code_lens = project.code_lens(buffer, range.clone(), cx);
18748            let code_actions = project.code_actions(buffer, range, None, cx);
18749            cx.background_spawn(async move {
18750                let (code_lens, code_actions) = join(code_lens, code_actions).await;
18751                Ok(code_lens
18752                    .context("code lens fetch")?
18753                    .into_iter()
18754                    .chain(code_actions.context("code action fetch")?)
18755                    .collect())
18756            })
18757        })
18758    }
18759
18760    fn apply_code_action(
18761        &self,
18762        buffer_handle: Entity<Buffer>,
18763        action: CodeAction,
18764        _excerpt_id: ExcerptId,
18765        push_to_history: bool,
18766        _window: &mut Window,
18767        cx: &mut App,
18768    ) -> Task<Result<ProjectTransaction>> {
18769        self.update(cx, |project, cx| {
18770            project.apply_code_action(buffer_handle, action, push_to_history, cx)
18771        })
18772    }
18773}
18774
18775fn snippet_completions(
18776    project: &Project,
18777    buffer: &Entity<Buffer>,
18778    buffer_position: text::Anchor,
18779    cx: &mut App,
18780) -> Task<Result<Vec<Completion>>> {
18781    let language = buffer.read(cx).language_at(buffer_position);
18782    let language_name = language.as_ref().map(|language| language.lsp_id());
18783    let snippet_store = project.snippets().read(cx);
18784    let snippets = snippet_store.snippets_for(language_name, cx);
18785
18786    if snippets.is_empty() {
18787        return Task::ready(Ok(vec![]));
18788    }
18789    let snapshot = buffer.read(cx).text_snapshot();
18790    let chars: String = snapshot
18791        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
18792        .collect();
18793
18794    let scope = language.map(|language| language.default_scope());
18795    let executor = cx.background_executor().clone();
18796
18797    cx.background_spawn(async move {
18798        let classifier = CharClassifier::new(scope).for_completion(true);
18799        let mut last_word = chars
18800            .chars()
18801            .take_while(|c| classifier.is_word(*c))
18802            .collect::<String>();
18803        last_word = last_word.chars().rev().collect();
18804
18805        if last_word.is_empty() {
18806            return Ok(vec![]);
18807        }
18808
18809        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
18810        let to_lsp = |point: &text::Anchor| {
18811            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
18812            point_to_lsp(end)
18813        };
18814        let lsp_end = to_lsp(&buffer_position);
18815
18816        let candidates = snippets
18817            .iter()
18818            .enumerate()
18819            .flat_map(|(ix, snippet)| {
18820                snippet
18821                    .prefix
18822                    .iter()
18823                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
18824            })
18825            .collect::<Vec<StringMatchCandidate>>();
18826
18827        let mut matches = fuzzy::match_strings(
18828            &candidates,
18829            &last_word,
18830            last_word.chars().any(|c| c.is_uppercase()),
18831            100,
18832            &Default::default(),
18833            executor,
18834        )
18835        .await;
18836
18837        // Remove all candidates where the query's start does not match the start of any word in the candidate
18838        if let Some(query_start) = last_word.chars().next() {
18839            matches.retain(|string_match| {
18840                split_words(&string_match.string).any(|word| {
18841                    // Check that the first codepoint of the word as lowercase matches the first
18842                    // codepoint of the query as lowercase
18843                    word.chars()
18844                        .flat_map(|codepoint| codepoint.to_lowercase())
18845                        .zip(query_start.to_lowercase())
18846                        .all(|(word_cp, query_cp)| word_cp == query_cp)
18847                })
18848            });
18849        }
18850
18851        let matched_strings = matches
18852            .into_iter()
18853            .map(|m| m.string)
18854            .collect::<HashSet<_>>();
18855
18856        let result: Vec<Completion> = snippets
18857            .into_iter()
18858            .filter_map(|snippet| {
18859                let matching_prefix = snippet
18860                    .prefix
18861                    .iter()
18862                    .find(|prefix| matched_strings.contains(*prefix))?;
18863                let start = as_offset - last_word.len();
18864                let start = snapshot.anchor_before(start);
18865                let range = start..buffer_position;
18866                let lsp_start = to_lsp(&start);
18867                let lsp_range = lsp::Range {
18868                    start: lsp_start,
18869                    end: lsp_end,
18870                };
18871                Some(Completion {
18872                    replace_range: range,
18873                    new_text: snippet.body.clone(),
18874                    source: CompletionSource::Lsp {
18875                        insert_range: None,
18876                        server_id: LanguageServerId(usize::MAX),
18877                        resolved: true,
18878                        lsp_completion: Box::new(lsp::CompletionItem {
18879                            label: snippet.prefix.first().unwrap().clone(),
18880                            kind: Some(CompletionItemKind::SNIPPET),
18881                            label_details: snippet.description.as_ref().map(|description| {
18882                                lsp::CompletionItemLabelDetails {
18883                                    detail: Some(description.clone()),
18884                                    description: None,
18885                                }
18886                            }),
18887                            insert_text_format: Some(InsertTextFormat::SNIPPET),
18888                            text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
18889                                lsp::InsertReplaceEdit {
18890                                    new_text: snippet.body.clone(),
18891                                    insert: lsp_range,
18892                                    replace: lsp_range,
18893                                },
18894                            )),
18895                            filter_text: Some(snippet.body.clone()),
18896                            sort_text: Some(char::MAX.to_string()),
18897                            ..lsp::CompletionItem::default()
18898                        }),
18899                        lsp_defaults: None,
18900                    },
18901                    label: CodeLabel {
18902                        text: matching_prefix.clone(),
18903                        runs: Vec::new(),
18904                        filter_range: 0..matching_prefix.len(),
18905                    },
18906                    icon_path: None,
18907                    documentation: snippet
18908                        .description
18909                        .clone()
18910                        .map(|description| CompletionDocumentation::SingleLine(description.into())),
18911                    insert_text_mode: None,
18912                    confirm: None,
18913                })
18914            })
18915            .collect();
18916
18917        Ok(result)
18918    })
18919}
18920
18921impl CompletionProvider for Entity<Project> {
18922    fn completions(
18923        &self,
18924        _excerpt_id: ExcerptId,
18925        buffer: &Entity<Buffer>,
18926        buffer_position: text::Anchor,
18927        options: CompletionContext,
18928        _window: &mut Window,
18929        cx: &mut Context<Editor>,
18930    ) -> Task<Result<Option<Vec<Completion>>>> {
18931        self.update(cx, |project, cx| {
18932            let snippets = snippet_completions(project, buffer, buffer_position, cx);
18933            let project_completions = project.completions(buffer, buffer_position, options, cx);
18934            cx.background_spawn(async move {
18935                let snippets_completions = snippets.await?;
18936                match project_completions.await? {
18937                    Some(mut completions) => {
18938                        completions.extend(snippets_completions);
18939                        Ok(Some(completions))
18940                    }
18941                    None => {
18942                        if snippets_completions.is_empty() {
18943                            Ok(None)
18944                        } else {
18945                            Ok(Some(snippets_completions))
18946                        }
18947                    }
18948                }
18949            })
18950        })
18951    }
18952
18953    fn resolve_completions(
18954        &self,
18955        buffer: Entity<Buffer>,
18956        completion_indices: Vec<usize>,
18957        completions: Rc<RefCell<Box<[Completion]>>>,
18958        cx: &mut Context<Editor>,
18959    ) -> Task<Result<bool>> {
18960        self.update(cx, |project, cx| {
18961            project.lsp_store().update(cx, |lsp_store, cx| {
18962                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
18963            })
18964        })
18965    }
18966
18967    fn apply_additional_edits_for_completion(
18968        &self,
18969        buffer: Entity<Buffer>,
18970        completions: Rc<RefCell<Box<[Completion]>>>,
18971        completion_index: usize,
18972        push_to_history: bool,
18973        cx: &mut Context<Editor>,
18974    ) -> Task<Result<Option<language::Transaction>>> {
18975        self.update(cx, |project, cx| {
18976            project.lsp_store().update(cx, |lsp_store, cx| {
18977                lsp_store.apply_additional_edits_for_completion(
18978                    buffer,
18979                    completions,
18980                    completion_index,
18981                    push_to_history,
18982                    cx,
18983                )
18984            })
18985        })
18986    }
18987
18988    fn is_completion_trigger(
18989        &self,
18990        buffer: &Entity<Buffer>,
18991        position: language::Anchor,
18992        text: &str,
18993        trigger_in_words: bool,
18994        cx: &mut Context<Editor>,
18995    ) -> bool {
18996        let mut chars = text.chars();
18997        let char = if let Some(char) = chars.next() {
18998            char
18999        } else {
19000            return false;
19001        };
19002        if chars.next().is_some() {
19003            return false;
19004        }
19005
19006        let buffer = buffer.read(cx);
19007        let snapshot = buffer.snapshot();
19008        if !snapshot.settings_at(position, cx).show_completions_on_input {
19009            return false;
19010        }
19011        let classifier = snapshot.char_classifier_at(position).for_completion(true);
19012        if trigger_in_words && classifier.is_word(char) {
19013            return true;
19014        }
19015
19016        buffer.completion_triggers().contains(text)
19017    }
19018}
19019
19020impl SemanticsProvider for Entity<Project> {
19021    fn hover(
19022        &self,
19023        buffer: &Entity<Buffer>,
19024        position: text::Anchor,
19025        cx: &mut App,
19026    ) -> Option<Task<Vec<project::Hover>>> {
19027        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19028    }
19029
19030    fn document_highlights(
19031        &self,
19032        buffer: &Entity<Buffer>,
19033        position: text::Anchor,
19034        cx: &mut App,
19035    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19036        Some(self.update(cx, |project, cx| {
19037            project.document_highlights(buffer, position, cx)
19038        }))
19039    }
19040
19041    fn definitions(
19042        &self,
19043        buffer: &Entity<Buffer>,
19044        position: text::Anchor,
19045        kind: GotoDefinitionKind,
19046        cx: &mut App,
19047    ) -> Option<Task<Result<Vec<LocationLink>>>> {
19048        Some(self.update(cx, |project, cx| match kind {
19049            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19050            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19051            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19052            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19053        }))
19054    }
19055
19056    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19057        // TODO: make this work for remote projects
19058        self.update(cx, |this, cx| {
19059            buffer.update(cx, |buffer, cx| {
19060                this.any_language_server_supports_inlay_hints(buffer, cx)
19061            })
19062        })
19063    }
19064
19065    fn inlay_hints(
19066        &self,
19067        buffer_handle: Entity<Buffer>,
19068        range: Range<text::Anchor>,
19069        cx: &mut App,
19070    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19071        Some(self.update(cx, |project, cx| {
19072            project.inlay_hints(buffer_handle, range, cx)
19073        }))
19074    }
19075
19076    fn resolve_inlay_hint(
19077        &self,
19078        hint: InlayHint,
19079        buffer_handle: Entity<Buffer>,
19080        server_id: LanguageServerId,
19081        cx: &mut App,
19082    ) -> Option<Task<anyhow::Result<InlayHint>>> {
19083        Some(self.update(cx, |project, cx| {
19084            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19085        }))
19086    }
19087
19088    fn range_for_rename(
19089        &self,
19090        buffer: &Entity<Buffer>,
19091        position: text::Anchor,
19092        cx: &mut App,
19093    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19094        Some(self.update(cx, |project, cx| {
19095            let buffer = buffer.clone();
19096            let task = project.prepare_rename(buffer.clone(), position, cx);
19097            cx.spawn(async move |_, cx| {
19098                Ok(match task.await? {
19099                    PrepareRenameResponse::Success(range) => Some(range),
19100                    PrepareRenameResponse::InvalidPosition => None,
19101                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19102                        // Fallback on using TreeSitter info to determine identifier range
19103                        buffer.update(cx, |buffer, _| {
19104                            let snapshot = buffer.snapshot();
19105                            let (range, kind) = snapshot.surrounding_word(position);
19106                            if kind != Some(CharKind::Word) {
19107                                return None;
19108                            }
19109                            Some(
19110                                snapshot.anchor_before(range.start)
19111                                    ..snapshot.anchor_after(range.end),
19112                            )
19113                        })?
19114                    }
19115                })
19116            })
19117        }))
19118    }
19119
19120    fn perform_rename(
19121        &self,
19122        buffer: &Entity<Buffer>,
19123        position: text::Anchor,
19124        new_name: String,
19125        cx: &mut App,
19126    ) -> Option<Task<Result<ProjectTransaction>>> {
19127        Some(self.update(cx, |project, cx| {
19128            project.perform_rename(buffer.clone(), position, new_name, cx)
19129        }))
19130    }
19131}
19132
19133fn inlay_hint_settings(
19134    location: Anchor,
19135    snapshot: &MultiBufferSnapshot,
19136    cx: &mut Context<Editor>,
19137) -> InlayHintSettings {
19138    let file = snapshot.file_at(location);
19139    let language = snapshot.language_at(location).map(|l| l.name());
19140    language_settings(language, file, cx).inlay_hints
19141}
19142
19143fn consume_contiguous_rows(
19144    contiguous_row_selections: &mut Vec<Selection<Point>>,
19145    selection: &Selection<Point>,
19146    display_map: &DisplaySnapshot,
19147    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19148) -> (MultiBufferRow, MultiBufferRow) {
19149    contiguous_row_selections.push(selection.clone());
19150    let start_row = MultiBufferRow(selection.start.row);
19151    let mut end_row = ending_row(selection, display_map);
19152
19153    while let Some(next_selection) = selections.peek() {
19154        if next_selection.start.row <= end_row.0 {
19155            end_row = ending_row(next_selection, display_map);
19156            contiguous_row_selections.push(selections.next().unwrap().clone());
19157        } else {
19158            break;
19159        }
19160    }
19161    (start_row, end_row)
19162}
19163
19164fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19165    if next_selection.end.column > 0 || next_selection.is_empty() {
19166        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19167    } else {
19168        MultiBufferRow(next_selection.end.row)
19169    }
19170}
19171
19172impl EditorSnapshot {
19173    pub fn remote_selections_in_range<'a>(
19174        &'a self,
19175        range: &'a Range<Anchor>,
19176        collaboration_hub: &dyn CollaborationHub,
19177        cx: &'a App,
19178    ) -> impl 'a + Iterator<Item = RemoteSelection> {
19179        let participant_names = collaboration_hub.user_names(cx);
19180        let participant_indices = collaboration_hub.user_participant_indices(cx);
19181        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19182        let collaborators_by_replica_id = collaborators_by_peer_id
19183            .iter()
19184            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19185            .collect::<HashMap<_, _>>();
19186        self.buffer_snapshot
19187            .selections_in_range(range, false)
19188            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19189                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19190                let participant_index = participant_indices.get(&collaborator.user_id).copied();
19191                let user_name = participant_names.get(&collaborator.user_id).cloned();
19192                Some(RemoteSelection {
19193                    replica_id,
19194                    selection,
19195                    cursor_shape,
19196                    line_mode,
19197                    participant_index,
19198                    peer_id: collaborator.peer_id,
19199                    user_name,
19200                })
19201            })
19202    }
19203
19204    pub fn hunks_for_ranges(
19205        &self,
19206        ranges: impl IntoIterator<Item = Range<Point>>,
19207    ) -> Vec<MultiBufferDiffHunk> {
19208        let mut hunks = Vec::new();
19209        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19210            HashMap::default();
19211        for query_range in ranges {
19212            let query_rows =
19213                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19214            for hunk in self.buffer_snapshot.diff_hunks_in_range(
19215                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19216            ) {
19217                // Include deleted hunks that are adjacent to the query range, because
19218                // otherwise they would be missed.
19219                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19220                if hunk.status().is_deleted() {
19221                    intersects_range |= hunk.row_range.start == query_rows.end;
19222                    intersects_range |= hunk.row_range.end == query_rows.start;
19223                }
19224                if intersects_range {
19225                    if !processed_buffer_rows
19226                        .entry(hunk.buffer_id)
19227                        .or_default()
19228                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19229                    {
19230                        continue;
19231                    }
19232                    hunks.push(hunk);
19233                }
19234            }
19235        }
19236
19237        hunks
19238    }
19239
19240    fn display_diff_hunks_for_rows<'a>(
19241        &'a self,
19242        display_rows: Range<DisplayRow>,
19243        folded_buffers: &'a HashSet<BufferId>,
19244    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19245        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19246        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19247
19248        self.buffer_snapshot
19249            .diff_hunks_in_range(buffer_start..buffer_end)
19250            .filter_map(|hunk| {
19251                if folded_buffers.contains(&hunk.buffer_id) {
19252                    return None;
19253                }
19254
19255                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
19256                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
19257
19258                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
19259                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
19260
19261                let display_hunk = if hunk_display_start.column() != 0 {
19262                    DisplayDiffHunk::Folded {
19263                        display_row: hunk_display_start.row(),
19264                    }
19265                } else {
19266                    let mut end_row = hunk_display_end.row();
19267                    if hunk_display_end.column() > 0 {
19268                        end_row.0 += 1;
19269                    }
19270                    let is_created_file = hunk.is_created_file();
19271                    DisplayDiffHunk::Unfolded {
19272                        status: hunk.status(),
19273                        diff_base_byte_range: hunk.diff_base_byte_range,
19274                        display_row_range: hunk_display_start.row()..end_row,
19275                        multi_buffer_range: Anchor::range_in_buffer(
19276                            hunk.excerpt_id,
19277                            hunk.buffer_id,
19278                            hunk.buffer_range,
19279                        ),
19280                        is_created_file,
19281                    }
19282                };
19283
19284                Some(display_hunk)
19285            })
19286    }
19287
19288    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
19289        self.display_snapshot.buffer_snapshot.language_at(position)
19290    }
19291
19292    pub fn is_focused(&self) -> bool {
19293        self.is_focused
19294    }
19295
19296    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
19297        self.placeholder_text.as_ref()
19298    }
19299
19300    pub fn scroll_position(&self) -> gpui::Point<f32> {
19301        self.scroll_anchor.scroll_position(&self.display_snapshot)
19302    }
19303
19304    fn gutter_dimensions(
19305        &self,
19306        font_id: FontId,
19307        font_size: Pixels,
19308        max_line_number_width: Pixels,
19309        cx: &App,
19310    ) -> Option<GutterDimensions> {
19311        if !self.show_gutter {
19312            return None;
19313        }
19314
19315        let descent = cx.text_system().descent(font_id, font_size);
19316        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
19317        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
19318
19319        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
19320            matches!(
19321                ProjectSettings::get_global(cx).git.git_gutter,
19322                Some(GitGutterSetting::TrackedFiles)
19323            )
19324        });
19325        let gutter_settings = EditorSettings::get_global(cx).gutter;
19326        let show_line_numbers = self
19327            .show_line_numbers
19328            .unwrap_or(gutter_settings.line_numbers);
19329        let line_gutter_width = if show_line_numbers {
19330            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
19331            let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
19332            max_line_number_width.max(min_width_for_number_on_gutter)
19333        } else {
19334            0.0.into()
19335        };
19336
19337        let show_code_actions = self
19338            .show_code_actions
19339            .unwrap_or(gutter_settings.code_actions);
19340
19341        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
19342        let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
19343
19344        let git_blame_entries_width =
19345            self.git_blame_gutter_max_author_length
19346                .map(|max_author_length| {
19347                    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
19348                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
19349
19350                    /// The number of characters to dedicate to gaps and margins.
19351                    const SPACING_WIDTH: usize = 4;
19352
19353                    let max_char_count = max_author_length.min(renderer.max_author_length())
19354                        + ::git::SHORT_SHA_LENGTH
19355                        + MAX_RELATIVE_TIMESTAMP.len()
19356                        + SPACING_WIDTH;
19357
19358                    em_advance * max_char_count
19359                });
19360
19361        let is_singleton = self.buffer_snapshot.is_singleton();
19362
19363        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
19364        left_padding += if !is_singleton {
19365            em_width * 4.0
19366        } else if show_code_actions || show_runnables || show_breakpoints {
19367            em_width * 3.0
19368        } else if show_git_gutter && show_line_numbers {
19369            em_width * 2.0
19370        } else if show_git_gutter || show_line_numbers {
19371            em_width
19372        } else {
19373            px(0.)
19374        };
19375
19376        let shows_folds = is_singleton && gutter_settings.folds;
19377
19378        let right_padding = if shows_folds && show_line_numbers {
19379            em_width * 4.0
19380        } else if shows_folds || (!is_singleton && show_line_numbers) {
19381            em_width * 3.0
19382        } else if show_line_numbers {
19383            em_width
19384        } else {
19385            px(0.)
19386        };
19387
19388        Some(GutterDimensions {
19389            left_padding,
19390            right_padding,
19391            width: line_gutter_width + left_padding + right_padding,
19392            margin: -descent,
19393            git_blame_entries_width,
19394        })
19395    }
19396
19397    pub fn render_crease_toggle(
19398        &self,
19399        buffer_row: MultiBufferRow,
19400        row_contains_cursor: bool,
19401        editor: Entity<Editor>,
19402        window: &mut Window,
19403        cx: &mut App,
19404    ) -> Option<AnyElement> {
19405        let folded = self.is_line_folded(buffer_row);
19406        let mut is_foldable = false;
19407
19408        if let Some(crease) = self
19409            .crease_snapshot
19410            .query_row(buffer_row, &self.buffer_snapshot)
19411        {
19412            is_foldable = true;
19413            match crease {
19414                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
19415                    if let Some(render_toggle) = render_toggle {
19416                        let toggle_callback =
19417                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
19418                                if folded {
19419                                    editor.update(cx, |editor, cx| {
19420                                        editor.fold_at(buffer_row, window, cx)
19421                                    });
19422                                } else {
19423                                    editor.update(cx, |editor, cx| {
19424                                        editor.unfold_at(buffer_row, window, cx)
19425                                    });
19426                                }
19427                            });
19428                        return Some((render_toggle)(
19429                            buffer_row,
19430                            folded,
19431                            toggle_callback,
19432                            window,
19433                            cx,
19434                        ));
19435                    }
19436                }
19437            }
19438        }
19439
19440        is_foldable |= self.starts_indent(buffer_row);
19441
19442        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
19443            Some(
19444                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
19445                    .toggle_state(folded)
19446                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
19447                        if folded {
19448                            this.unfold_at(buffer_row, window, cx);
19449                        } else {
19450                            this.fold_at(buffer_row, window, cx);
19451                        }
19452                    }))
19453                    .into_any_element(),
19454            )
19455        } else {
19456            None
19457        }
19458    }
19459
19460    pub fn render_crease_trailer(
19461        &self,
19462        buffer_row: MultiBufferRow,
19463        window: &mut Window,
19464        cx: &mut App,
19465    ) -> Option<AnyElement> {
19466        let folded = self.is_line_folded(buffer_row);
19467        if let Crease::Inline { render_trailer, .. } = self
19468            .crease_snapshot
19469            .query_row(buffer_row, &self.buffer_snapshot)?
19470        {
19471            let render_trailer = render_trailer.as_ref()?;
19472            Some(render_trailer(buffer_row, folded, window, cx))
19473        } else {
19474            None
19475        }
19476    }
19477}
19478
19479impl Deref for EditorSnapshot {
19480    type Target = DisplaySnapshot;
19481
19482    fn deref(&self) -> &Self::Target {
19483        &self.display_snapshot
19484    }
19485}
19486
19487#[derive(Clone, Debug, PartialEq, Eq)]
19488pub enum EditorEvent {
19489    InputIgnored {
19490        text: Arc<str>,
19491    },
19492    InputHandled {
19493        utf16_range_to_replace: Option<Range<isize>>,
19494        text: Arc<str>,
19495    },
19496    ExcerptsAdded {
19497        buffer: Entity<Buffer>,
19498        predecessor: ExcerptId,
19499        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
19500    },
19501    ExcerptsRemoved {
19502        ids: Vec<ExcerptId>,
19503    },
19504    BufferFoldToggled {
19505        ids: Vec<ExcerptId>,
19506        folded: bool,
19507    },
19508    ExcerptsEdited {
19509        ids: Vec<ExcerptId>,
19510    },
19511    ExcerptsExpanded {
19512        ids: Vec<ExcerptId>,
19513    },
19514    BufferEdited,
19515    Edited {
19516        transaction_id: clock::Lamport,
19517    },
19518    Reparsed(BufferId),
19519    Focused,
19520    FocusedIn,
19521    Blurred,
19522    DirtyChanged,
19523    Saved,
19524    TitleChanged,
19525    DiffBaseChanged,
19526    SelectionsChanged {
19527        local: bool,
19528    },
19529    ScrollPositionChanged {
19530        local: bool,
19531        autoscroll: bool,
19532    },
19533    Closed,
19534    TransactionUndone {
19535        transaction_id: clock::Lamport,
19536    },
19537    TransactionBegun {
19538        transaction_id: clock::Lamport,
19539    },
19540    Reloaded,
19541    CursorShapeChanged,
19542    PushedToNavHistory {
19543        anchor: Anchor,
19544        is_deactivate: bool,
19545    },
19546}
19547
19548impl EventEmitter<EditorEvent> for Editor {}
19549
19550impl Focusable for Editor {
19551    fn focus_handle(&self, _cx: &App) -> FocusHandle {
19552        self.focus_handle.clone()
19553    }
19554}
19555
19556impl Render for Editor {
19557    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19558        let settings = ThemeSettings::get_global(cx);
19559
19560        let mut text_style = match self.mode {
19561            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
19562                color: cx.theme().colors().editor_foreground,
19563                font_family: settings.ui_font.family.clone(),
19564                font_features: settings.ui_font.features.clone(),
19565                font_fallbacks: settings.ui_font.fallbacks.clone(),
19566                font_size: rems(0.875).into(),
19567                font_weight: settings.ui_font.weight,
19568                line_height: relative(settings.buffer_line_height.value()),
19569                ..Default::default()
19570            },
19571            EditorMode::Full { .. } => TextStyle {
19572                color: cx.theme().colors().editor_foreground,
19573                font_family: settings.buffer_font.family.clone(),
19574                font_features: settings.buffer_font.features.clone(),
19575                font_fallbacks: settings.buffer_font.fallbacks.clone(),
19576                font_size: settings.buffer_font_size(cx).into(),
19577                font_weight: settings.buffer_font.weight,
19578                line_height: relative(settings.buffer_line_height.value()),
19579                ..Default::default()
19580            },
19581        };
19582        if let Some(text_style_refinement) = &self.text_style_refinement {
19583            text_style.refine(text_style_refinement)
19584        }
19585
19586        let background = match self.mode {
19587            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
19588            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
19589            EditorMode::Full { .. } => cx.theme().colors().editor_background,
19590        };
19591
19592        EditorElement::new(
19593            &cx.entity(),
19594            EditorStyle {
19595                background,
19596                local_player: cx.theme().players().local(),
19597                text: text_style,
19598                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
19599                syntax: cx.theme().syntax().clone(),
19600                status: cx.theme().status().clone(),
19601                inlay_hints_style: make_inlay_hints_style(cx),
19602                inline_completion_styles: make_suggestion_styles(cx),
19603                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
19604            },
19605        )
19606    }
19607}
19608
19609impl EntityInputHandler for Editor {
19610    fn text_for_range(
19611        &mut self,
19612        range_utf16: Range<usize>,
19613        adjusted_range: &mut Option<Range<usize>>,
19614        _: &mut Window,
19615        cx: &mut Context<Self>,
19616    ) -> Option<String> {
19617        let snapshot = self.buffer.read(cx).read(cx);
19618        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
19619        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
19620        if (start.0..end.0) != range_utf16 {
19621            adjusted_range.replace(start.0..end.0);
19622        }
19623        Some(snapshot.text_for_range(start..end).collect())
19624    }
19625
19626    fn selected_text_range(
19627        &mut self,
19628        ignore_disabled_input: bool,
19629        _: &mut Window,
19630        cx: &mut Context<Self>,
19631    ) -> Option<UTF16Selection> {
19632        // Prevent the IME menu from appearing when holding down an alphabetic key
19633        // while input is disabled.
19634        if !ignore_disabled_input && !self.input_enabled {
19635            return None;
19636        }
19637
19638        let selection = self.selections.newest::<OffsetUtf16>(cx);
19639        let range = selection.range();
19640
19641        Some(UTF16Selection {
19642            range: range.start.0..range.end.0,
19643            reversed: selection.reversed,
19644        })
19645    }
19646
19647    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
19648        let snapshot = self.buffer.read(cx).read(cx);
19649        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
19650        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
19651    }
19652
19653    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
19654        self.clear_highlights::<InputComposition>(cx);
19655        self.ime_transaction.take();
19656    }
19657
19658    fn replace_text_in_range(
19659        &mut self,
19660        range_utf16: Option<Range<usize>>,
19661        text: &str,
19662        window: &mut Window,
19663        cx: &mut Context<Self>,
19664    ) {
19665        if !self.input_enabled {
19666            cx.emit(EditorEvent::InputIgnored { text: text.into() });
19667            return;
19668        }
19669
19670        self.transact(window, cx, |this, window, cx| {
19671            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
19672                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19673                Some(this.selection_replacement_ranges(range_utf16, cx))
19674            } else {
19675                this.marked_text_ranges(cx)
19676            };
19677
19678            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
19679                let newest_selection_id = this.selections.newest_anchor().id;
19680                this.selections
19681                    .all::<OffsetUtf16>(cx)
19682                    .iter()
19683                    .zip(ranges_to_replace.iter())
19684                    .find_map(|(selection, range)| {
19685                        if selection.id == newest_selection_id {
19686                            Some(
19687                                (range.start.0 as isize - selection.head().0 as isize)
19688                                    ..(range.end.0 as isize - selection.head().0 as isize),
19689                            )
19690                        } else {
19691                            None
19692                        }
19693                    })
19694            });
19695
19696            cx.emit(EditorEvent::InputHandled {
19697                utf16_range_to_replace: range_to_replace,
19698                text: text.into(),
19699            });
19700
19701            if let Some(new_selected_ranges) = new_selected_ranges {
19702                this.change_selections(None, window, cx, |selections| {
19703                    selections.select_ranges(new_selected_ranges)
19704                });
19705                this.backspace(&Default::default(), window, cx);
19706            }
19707
19708            this.handle_input(text, window, cx);
19709        });
19710
19711        if let Some(transaction) = self.ime_transaction {
19712            self.buffer.update(cx, |buffer, cx| {
19713                buffer.group_until_transaction(transaction, cx);
19714            });
19715        }
19716
19717        self.unmark_text(window, cx);
19718    }
19719
19720    fn replace_and_mark_text_in_range(
19721        &mut self,
19722        range_utf16: Option<Range<usize>>,
19723        text: &str,
19724        new_selected_range_utf16: Option<Range<usize>>,
19725        window: &mut Window,
19726        cx: &mut Context<Self>,
19727    ) {
19728        if !self.input_enabled {
19729            return;
19730        }
19731
19732        let transaction = self.transact(window, cx, |this, window, cx| {
19733            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
19734                let snapshot = this.buffer.read(cx).read(cx);
19735                if let Some(relative_range_utf16) = range_utf16.as_ref() {
19736                    for marked_range in &mut marked_ranges {
19737                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
19738                        marked_range.start.0 += relative_range_utf16.start;
19739                        marked_range.start =
19740                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
19741                        marked_range.end =
19742                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
19743                    }
19744                }
19745                Some(marked_ranges)
19746            } else if let Some(range_utf16) = range_utf16 {
19747                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19748                Some(this.selection_replacement_ranges(range_utf16, cx))
19749            } else {
19750                None
19751            };
19752
19753            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
19754                let newest_selection_id = this.selections.newest_anchor().id;
19755                this.selections
19756                    .all::<OffsetUtf16>(cx)
19757                    .iter()
19758                    .zip(ranges_to_replace.iter())
19759                    .find_map(|(selection, range)| {
19760                        if selection.id == newest_selection_id {
19761                            Some(
19762                                (range.start.0 as isize - selection.head().0 as isize)
19763                                    ..(range.end.0 as isize - selection.head().0 as isize),
19764                            )
19765                        } else {
19766                            None
19767                        }
19768                    })
19769            });
19770
19771            cx.emit(EditorEvent::InputHandled {
19772                utf16_range_to_replace: range_to_replace,
19773                text: text.into(),
19774            });
19775
19776            if let Some(ranges) = ranges_to_replace {
19777                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
19778            }
19779
19780            let marked_ranges = {
19781                let snapshot = this.buffer.read(cx).read(cx);
19782                this.selections
19783                    .disjoint_anchors()
19784                    .iter()
19785                    .map(|selection| {
19786                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
19787                    })
19788                    .collect::<Vec<_>>()
19789            };
19790
19791            if text.is_empty() {
19792                this.unmark_text(window, cx);
19793            } else {
19794                this.highlight_text::<InputComposition>(
19795                    marked_ranges.clone(),
19796                    HighlightStyle {
19797                        underline: Some(UnderlineStyle {
19798                            thickness: px(1.),
19799                            color: None,
19800                            wavy: false,
19801                        }),
19802                        ..Default::default()
19803                    },
19804                    cx,
19805                );
19806            }
19807
19808            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
19809            let use_autoclose = this.use_autoclose;
19810            let use_auto_surround = this.use_auto_surround;
19811            this.set_use_autoclose(false);
19812            this.set_use_auto_surround(false);
19813            this.handle_input(text, window, cx);
19814            this.set_use_autoclose(use_autoclose);
19815            this.set_use_auto_surround(use_auto_surround);
19816
19817            if let Some(new_selected_range) = new_selected_range_utf16 {
19818                let snapshot = this.buffer.read(cx).read(cx);
19819                let new_selected_ranges = marked_ranges
19820                    .into_iter()
19821                    .map(|marked_range| {
19822                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
19823                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
19824                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
19825                        snapshot.clip_offset_utf16(new_start, Bias::Left)
19826                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
19827                    })
19828                    .collect::<Vec<_>>();
19829
19830                drop(snapshot);
19831                this.change_selections(None, window, cx, |selections| {
19832                    selections.select_ranges(new_selected_ranges)
19833                });
19834            }
19835        });
19836
19837        self.ime_transaction = self.ime_transaction.or(transaction);
19838        if let Some(transaction) = self.ime_transaction {
19839            self.buffer.update(cx, |buffer, cx| {
19840                buffer.group_until_transaction(transaction, cx);
19841            });
19842        }
19843
19844        if self.text_highlights::<InputComposition>(cx).is_none() {
19845            self.ime_transaction.take();
19846        }
19847    }
19848
19849    fn bounds_for_range(
19850        &mut self,
19851        range_utf16: Range<usize>,
19852        element_bounds: gpui::Bounds<Pixels>,
19853        window: &mut Window,
19854        cx: &mut Context<Self>,
19855    ) -> Option<gpui::Bounds<Pixels>> {
19856        let text_layout_details = self.text_layout_details(window);
19857        let gpui::Size {
19858            width: em_width,
19859            height: line_height,
19860        } = self.character_size(window);
19861
19862        let snapshot = self.snapshot(window, cx);
19863        let scroll_position = snapshot.scroll_position();
19864        let scroll_left = scroll_position.x * em_width;
19865
19866        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
19867        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
19868            + self.gutter_dimensions.width
19869            + self.gutter_dimensions.margin;
19870        let y = line_height * (start.row().as_f32() - scroll_position.y);
19871
19872        Some(Bounds {
19873            origin: element_bounds.origin + point(x, y),
19874            size: size(em_width, line_height),
19875        })
19876    }
19877
19878    fn character_index_for_point(
19879        &mut self,
19880        point: gpui::Point<Pixels>,
19881        _window: &mut Window,
19882        _cx: &mut Context<Self>,
19883    ) -> Option<usize> {
19884        let position_map = self.last_position_map.as_ref()?;
19885        if !position_map.text_hitbox.contains(&point) {
19886            return None;
19887        }
19888        let display_point = position_map.point_for_position(point).previous_valid;
19889        let anchor = position_map
19890            .snapshot
19891            .display_point_to_anchor(display_point, Bias::Left);
19892        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
19893        Some(utf16_offset.0)
19894    }
19895}
19896
19897trait SelectionExt {
19898    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
19899    fn spanned_rows(
19900        &self,
19901        include_end_if_at_line_start: bool,
19902        map: &DisplaySnapshot,
19903    ) -> Range<MultiBufferRow>;
19904}
19905
19906impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
19907    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
19908        let start = self
19909            .start
19910            .to_point(&map.buffer_snapshot)
19911            .to_display_point(map);
19912        let end = self
19913            .end
19914            .to_point(&map.buffer_snapshot)
19915            .to_display_point(map);
19916        if self.reversed {
19917            end..start
19918        } else {
19919            start..end
19920        }
19921    }
19922
19923    fn spanned_rows(
19924        &self,
19925        include_end_if_at_line_start: bool,
19926        map: &DisplaySnapshot,
19927    ) -> Range<MultiBufferRow> {
19928        let start = self.start.to_point(&map.buffer_snapshot);
19929        let mut end = self.end.to_point(&map.buffer_snapshot);
19930        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
19931            end.row -= 1;
19932        }
19933
19934        let buffer_start = map.prev_line_boundary(start).0;
19935        let buffer_end = map.next_line_boundary(end).0;
19936        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
19937    }
19938}
19939
19940impl<T: InvalidationRegion> InvalidationStack<T> {
19941    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
19942    where
19943        S: Clone + ToOffset,
19944    {
19945        while let Some(region) = self.last() {
19946            let all_selections_inside_invalidation_ranges =
19947                if selections.len() == region.ranges().len() {
19948                    selections
19949                        .iter()
19950                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
19951                        .all(|(selection, invalidation_range)| {
19952                            let head = selection.head().to_offset(buffer);
19953                            invalidation_range.start <= head && invalidation_range.end >= head
19954                        })
19955                } else {
19956                    false
19957                };
19958
19959            if all_selections_inside_invalidation_ranges {
19960                break;
19961            } else {
19962                self.pop();
19963            }
19964        }
19965    }
19966}
19967
19968impl<T> Default for InvalidationStack<T> {
19969    fn default() -> Self {
19970        Self(Default::default())
19971    }
19972}
19973
19974impl<T> Deref for InvalidationStack<T> {
19975    type Target = Vec<T>;
19976
19977    fn deref(&self) -> &Self::Target {
19978        &self.0
19979    }
19980}
19981
19982impl<T> DerefMut for InvalidationStack<T> {
19983    fn deref_mut(&mut self) -> &mut Self::Target {
19984        &mut self.0
19985    }
19986}
19987
19988impl InvalidationRegion for SnippetState {
19989    fn ranges(&self) -> &[Range<Anchor>] {
19990        &self.ranges[self.active_index]
19991    }
19992}
19993
19994pub fn diagnostic_block_renderer(
19995    diagnostic: Diagnostic,
19996    max_message_rows: Option<u8>,
19997    allow_closing: bool,
19998) -> RenderBlock {
19999    let (text_without_backticks, code_ranges) =
20000        highlight_diagnostic_message(&diagnostic, max_message_rows);
20001
20002    Arc::new(move |cx: &mut BlockContext| {
20003        let group_id: SharedString = cx.block_id.to_string().into();
20004
20005        let mut text_style = cx.window.text_style().clone();
20006        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
20007        let theme_settings = ThemeSettings::get_global(cx);
20008        text_style.font_family = theme_settings.buffer_font.family.clone();
20009        text_style.font_style = theme_settings.buffer_font.style;
20010        text_style.font_features = theme_settings.buffer_font.features.clone();
20011        text_style.font_weight = theme_settings.buffer_font.weight;
20012
20013        let multi_line_diagnostic = diagnostic.message.contains('\n');
20014
20015        let buttons = |diagnostic: &Diagnostic| {
20016            if multi_line_diagnostic {
20017                v_flex()
20018            } else {
20019                h_flex()
20020            }
20021            .when(allow_closing, |div| {
20022                div.children(diagnostic.is_primary.then(|| {
20023                    IconButton::new("close-block", IconName::XCircle)
20024                        .icon_color(Color::Muted)
20025                        .size(ButtonSize::Compact)
20026                        .style(ButtonStyle::Transparent)
20027                        .visible_on_hover(group_id.clone())
20028                        .on_click(move |_click, window, cx| {
20029                            window.dispatch_action(Box::new(Cancel), cx)
20030                        })
20031                        .tooltip(|window, cx| {
20032                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
20033                        })
20034                }))
20035            })
20036            .child(
20037                IconButton::new("copy-block", IconName::Copy)
20038                    .icon_color(Color::Muted)
20039                    .size(ButtonSize::Compact)
20040                    .style(ButtonStyle::Transparent)
20041                    .visible_on_hover(group_id.clone())
20042                    .on_click({
20043                        let message = diagnostic.message.clone();
20044                        move |_click, _, cx| {
20045                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
20046                        }
20047                    })
20048                    .tooltip(Tooltip::text("Copy diagnostic message")),
20049            )
20050        };
20051
20052        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
20053            AvailableSpace::min_size(),
20054            cx.window,
20055            cx.app,
20056        );
20057
20058        h_flex()
20059            .id(cx.block_id)
20060            .group(group_id.clone())
20061            .relative()
20062            .size_full()
20063            .block_mouse_down()
20064            .pl(cx.gutter_dimensions.width)
20065            .w(cx.max_width - cx.gutter_dimensions.full_width())
20066            .child(
20067                div()
20068                    .flex()
20069                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
20070                    .flex_shrink(),
20071            )
20072            .child(buttons(&diagnostic))
20073            .child(div().flex().flex_shrink_0().child(
20074                StyledText::new(text_without_backticks.clone()).with_default_highlights(
20075                    &text_style,
20076                    code_ranges.iter().map(|range| {
20077                        (
20078                            range.clone(),
20079                            HighlightStyle {
20080                                font_weight: Some(FontWeight::BOLD),
20081                                ..Default::default()
20082                            },
20083                        )
20084                    }),
20085                ),
20086            ))
20087            .into_any_element()
20088    })
20089}
20090
20091fn inline_completion_edit_text(
20092    current_snapshot: &BufferSnapshot,
20093    edits: &[(Range<Anchor>, String)],
20094    edit_preview: &EditPreview,
20095    include_deletions: bool,
20096    cx: &App,
20097) -> HighlightedText {
20098    let edits = edits
20099        .iter()
20100        .map(|(anchor, text)| {
20101            (
20102                anchor.start.text_anchor..anchor.end.text_anchor,
20103                text.clone(),
20104            )
20105        })
20106        .collect::<Vec<_>>();
20107
20108    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20109}
20110
20111pub fn highlight_diagnostic_message(
20112    diagnostic: &Diagnostic,
20113    mut max_message_rows: Option<u8>,
20114) -> (SharedString, Vec<Range<usize>>) {
20115    let mut text_without_backticks = String::new();
20116    let mut code_ranges = Vec::new();
20117
20118    if let Some(source) = &diagnostic.source {
20119        text_without_backticks.push_str(source);
20120        code_ranges.push(0..source.len());
20121        text_without_backticks.push_str(": ");
20122    }
20123
20124    let mut prev_offset = 0;
20125    let mut in_code_block = false;
20126    let has_row_limit = max_message_rows.is_some();
20127    let mut newline_indices = diagnostic
20128        .message
20129        .match_indices('\n')
20130        .filter(|_| has_row_limit)
20131        .map(|(ix, _)| ix)
20132        .fuse()
20133        .peekable();
20134
20135    for (quote_ix, _) in diagnostic
20136        .message
20137        .match_indices('`')
20138        .chain([(diagnostic.message.len(), "")])
20139    {
20140        let mut first_newline_ix = None;
20141        let mut last_newline_ix = None;
20142        while let Some(newline_ix) = newline_indices.peek() {
20143            if *newline_ix < quote_ix {
20144                if first_newline_ix.is_none() {
20145                    first_newline_ix = Some(*newline_ix);
20146                }
20147                last_newline_ix = Some(*newline_ix);
20148
20149                if let Some(rows_left) = &mut max_message_rows {
20150                    if *rows_left == 0 {
20151                        break;
20152                    } else {
20153                        *rows_left -= 1;
20154                    }
20155                }
20156                let _ = newline_indices.next();
20157            } else {
20158                break;
20159            }
20160        }
20161        let prev_len = text_without_backticks.len();
20162        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
20163        text_without_backticks.push_str(new_text);
20164        if in_code_block {
20165            code_ranges.push(prev_len..text_without_backticks.len());
20166        }
20167        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
20168        in_code_block = !in_code_block;
20169        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
20170            text_without_backticks.push_str("...");
20171            break;
20172        }
20173    }
20174
20175    (text_without_backticks.into(), code_ranges)
20176}
20177
20178fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20179    match severity {
20180        DiagnosticSeverity::ERROR => colors.error,
20181        DiagnosticSeverity::WARNING => colors.warning,
20182        DiagnosticSeverity::INFORMATION => colors.info,
20183        DiagnosticSeverity::HINT => colors.info,
20184        _ => colors.ignored,
20185    }
20186}
20187
20188pub fn styled_runs_for_code_label<'a>(
20189    label: &'a CodeLabel,
20190    syntax_theme: &'a theme::SyntaxTheme,
20191) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20192    let fade_out = HighlightStyle {
20193        fade_out: Some(0.35),
20194        ..Default::default()
20195    };
20196
20197    let mut prev_end = label.filter_range.end;
20198    label
20199        .runs
20200        .iter()
20201        .enumerate()
20202        .flat_map(move |(ix, (range, highlight_id))| {
20203            let style = if let Some(style) = highlight_id.style(syntax_theme) {
20204                style
20205            } else {
20206                return Default::default();
20207            };
20208            let mut muted_style = style;
20209            muted_style.highlight(fade_out);
20210
20211            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20212            if range.start >= label.filter_range.end {
20213                if range.start > prev_end {
20214                    runs.push((prev_end..range.start, fade_out));
20215                }
20216                runs.push((range.clone(), muted_style));
20217            } else if range.end <= label.filter_range.end {
20218                runs.push((range.clone(), style));
20219            } else {
20220                runs.push((range.start..label.filter_range.end, style));
20221                runs.push((label.filter_range.end..range.end, muted_style));
20222            }
20223            prev_end = cmp::max(prev_end, range.end);
20224
20225            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20226                runs.push((prev_end..label.text.len(), fade_out));
20227            }
20228
20229            runs
20230        })
20231}
20232
20233pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20234    let mut prev_index = 0;
20235    let mut prev_codepoint: Option<char> = None;
20236    text.char_indices()
20237        .chain([(text.len(), '\0')])
20238        .filter_map(move |(index, codepoint)| {
20239            let prev_codepoint = prev_codepoint.replace(codepoint)?;
20240            let is_boundary = index == text.len()
20241                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20242                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20243            if is_boundary {
20244                let chunk = &text[prev_index..index];
20245                prev_index = index;
20246                Some(chunk)
20247            } else {
20248                None
20249            }
20250        })
20251}
20252
20253pub trait RangeToAnchorExt: Sized {
20254    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20255
20256    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20257        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20258        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20259    }
20260}
20261
20262impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20263    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20264        let start_offset = self.start.to_offset(snapshot);
20265        let end_offset = self.end.to_offset(snapshot);
20266        if start_offset == end_offset {
20267            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20268        } else {
20269            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20270        }
20271    }
20272}
20273
20274pub trait RowExt {
20275    fn as_f32(&self) -> f32;
20276
20277    fn next_row(&self) -> Self;
20278
20279    fn previous_row(&self) -> Self;
20280
20281    fn minus(&self, other: Self) -> u32;
20282}
20283
20284impl RowExt for DisplayRow {
20285    fn as_f32(&self) -> f32 {
20286        self.0 as f32
20287    }
20288
20289    fn next_row(&self) -> Self {
20290        Self(self.0 + 1)
20291    }
20292
20293    fn previous_row(&self) -> Self {
20294        Self(self.0.saturating_sub(1))
20295    }
20296
20297    fn minus(&self, other: Self) -> u32 {
20298        self.0 - other.0
20299    }
20300}
20301
20302impl RowExt for MultiBufferRow {
20303    fn as_f32(&self) -> f32 {
20304        self.0 as f32
20305    }
20306
20307    fn next_row(&self) -> Self {
20308        Self(self.0 + 1)
20309    }
20310
20311    fn previous_row(&self) -> Self {
20312        Self(self.0.saturating_sub(1))
20313    }
20314
20315    fn minus(&self, other: Self) -> u32 {
20316        self.0 - other.0
20317    }
20318}
20319
20320trait RowRangeExt {
20321    type Row;
20322
20323    fn len(&self) -> usize;
20324
20325    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20326}
20327
20328impl RowRangeExt for Range<MultiBufferRow> {
20329    type Row = MultiBufferRow;
20330
20331    fn len(&self) -> usize {
20332        (self.end.0 - self.start.0) as usize
20333    }
20334
20335    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20336        (self.start.0..self.end.0).map(MultiBufferRow)
20337    }
20338}
20339
20340impl RowRangeExt for Range<DisplayRow> {
20341    type Row = DisplayRow;
20342
20343    fn len(&self) -> usize {
20344        (self.end.0 - self.start.0) as usize
20345    }
20346
20347    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20348        (self.start.0..self.end.0).map(DisplayRow)
20349    }
20350}
20351
20352/// If select range has more than one line, we
20353/// just point the cursor to range.start.
20354fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20355    if range.start.row == range.end.row {
20356        range
20357    } else {
20358        range.start..range.start
20359    }
20360}
20361pub struct KillRing(ClipboardItem);
20362impl Global for KillRing {}
20363
20364const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20365
20366enum BreakpointPromptEditAction {
20367    Log,
20368    Condition,
20369    HitCondition,
20370}
20371
20372struct BreakpointPromptEditor {
20373    pub(crate) prompt: Entity<Editor>,
20374    editor: WeakEntity<Editor>,
20375    breakpoint_anchor: Anchor,
20376    breakpoint: Breakpoint,
20377    edit_action: BreakpointPromptEditAction,
20378    block_ids: HashSet<CustomBlockId>,
20379    gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20380    _subscriptions: Vec<Subscription>,
20381}
20382
20383impl BreakpointPromptEditor {
20384    const MAX_LINES: u8 = 4;
20385
20386    fn new(
20387        editor: WeakEntity<Editor>,
20388        breakpoint_anchor: Anchor,
20389        breakpoint: Breakpoint,
20390        edit_action: BreakpointPromptEditAction,
20391        window: &mut Window,
20392        cx: &mut Context<Self>,
20393    ) -> Self {
20394        let base_text = match edit_action {
20395            BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20396            BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20397            BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20398        }
20399        .map(|msg| msg.to_string())
20400        .unwrap_or_default();
20401
20402        let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20403        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20404
20405        let prompt = cx.new(|cx| {
20406            let mut prompt = Editor::new(
20407                EditorMode::AutoHeight {
20408                    max_lines: Self::MAX_LINES as usize,
20409                },
20410                buffer,
20411                None,
20412                window,
20413                cx,
20414            );
20415            prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20416            prompt.set_show_cursor_when_unfocused(false, cx);
20417            prompt.set_placeholder_text(
20418                match edit_action {
20419                    BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20420                    BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20421                    BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20422                },
20423                cx,
20424            );
20425
20426            prompt
20427        });
20428
20429        Self {
20430            prompt,
20431            editor,
20432            breakpoint_anchor,
20433            breakpoint,
20434            edit_action,
20435            gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20436            block_ids: Default::default(),
20437            _subscriptions: vec![],
20438        }
20439    }
20440
20441    pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20442        self.block_ids.extend(block_ids)
20443    }
20444
20445    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20446        if let Some(editor) = self.editor.upgrade() {
20447            let message = self
20448                .prompt
20449                .read(cx)
20450                .buffer
20451                .read(cx)
20452                .as_singleton()
20453                .expect("A multi buffer in breakpoint prompt isn't possible")
20454                .read(cx)
20455                .as_rope()
20456                .to_string();
20457
20458            editor.update(cx, |editor, cx| {
20459                editor.edit_breakpoint_at_anchor(
20460                    self.breakpoint_anchor,
20461                    self.breakpoint.clone(),
20462                    match self.edit_action {
20463                        BreakpointPromptEditAction::Log => {
20464                            BreakpointEditAction::EditLogMessage(message.into())
20465                        }
20466                        BreakpointPromptEditAction::Condition => {
20467                            BreakpointEditAction::EditCondition(message.into())
20468                        }
20469                        BreakpointPromptEditAction::HitCondition => {
20470                            BreakpointEditAction::EditHitCondition(message.into())
20471                        }
20472                    },
20473                    cx,
20474                );
20475
20476                editor.remove_blocks(self.block_ids.clone(), None, cx);
20477                cx.focus_self(window);
20478            });
20479        }
20480    }
20481
20482    fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
20483        self.editor
20484            .update(cx, |editor, cx| {
20485                editor.remove_blocks(self.block_ids.clone(), None, cx);
20486                window.focus(&editor.focus_handle);
20487            })
20488            .log_err();
20489    }
20490
20491    fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
20492        let settings = ThemeSettings::get_global(cx);
20493        let text_style = TextStyle {
20494            color: if self.prompt.read(cx).read_only(cx) {
20495                cx.theme().colors().text_disabled
20496            } else {
20497                cx.theme().colors().text
20498            },
20499            font_family: settings.buffer_font.family.clone(),
20500            font_fallbacks: settings.buffer_font.fallbacks.clone(),
20501            font_size: settings.buffer_font_size(cx).into(),
20502            font_weight: settings.buffer_font.weight,
20503            line_height: relative(settings.buffer_line_height.value()),
20504            ..Default::default()
20505        };
20506        EditorElement::new(
20507            &self.prompt,
20508            EditorStyle {
20509                background: cx.theme().colors().editor_background,
20510                local_player: cx.theme().players().local(),
20511                text: text_style,
20512                ..Default::default()
20513            },
20514        )
20515    }
20516}
20517
20518impl Render for BreakpointPromptEditor {
20519    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20520        let gutter_dimensions = *self.gutter_dimensions.lock();
20521        h_flex()
20522            .key_context("Editor")
20523            .bg(cx.theme().colors().editor_background)
20524            .border_y_1()
20525            .border_color(cx.theme().status().info_border)
20526            .size_full()
20527            .py(window.line_height() / 2.5)
20528            .on_action(cx.listener(Self::confirm))
20529            .on_action(cx.listener(Self::cancel))
20530            .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
20531            .child(div().flex_1().child(self.render_prompt_editor(cx)))
20532    }
20533}
20534
20535impl Focusable for BreakpointPromptEditor {
20536    fn focus_handle(&self, cx: &App) -> FocusHandle {
20537        self.prompt.focus_handle(cx)
20538    }
20539}
20540
20541fn all_edits_insertions_or_deletions(
20542    edits: &Vec<(Range<Anchor>, String)>,
20543    snapshot: &MultiBufferSnapshot,
20544) -> bool {
20545    let mut all_insertions = true;
20546    let mut all_deletions = true;
20547
20548    for (range, new_text) in edits.iter() {
20549        let range_is_empty = range.to_offset(&snapshot).is_empty();
20550        let text_is_empty = new_text.is_empty();
20551
20552        if range_is_empty != text_is_empty {
20553            if range_is_empty {
20554                all_deletions = false;
20555            } else {
20556                all_insertions = false;
20557            }
20558        } else {
20559            return false;
20560        }
20561
20562        if !all_insertions && !all_deletions {
20563            return false;
20564        }
20565    }
20566    all_insertions || all_deletions
20567}
20568
20569struct MissingEditPredictionKeybindingTooltip;
20570
20571impl Render for MissingEditPredictionKeybindingTooltip {
20572    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20573        ui::tooltip_container(window, cx, |container, _, cx| {
20574            container
20575                .flex_shrink_0()
20576                .max_w_80()
20577                .min_h(rems_from_px(124.))
20578                .justify_between()
20579                .child(
20580                    v_flex()
20581                        .flex_1()
20582                        .text_ui_sm(cx)
20583                        .child(Label::new("Conflict with Accept Keybinding"))
20584                        .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
20585                )
20586                .child(
20587                    h_flex()
20588                        .pb_1()
20589                        .gap_1()
20590                        .items_end()
20591                        .w_full()
20592                        .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
20593                            window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
20594                        }))
20595                        .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
20596                            cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
20597                        })),
20598                )
20599        })
20600    }
20601}
20602
20603#[derive(Debug, Clone, Copy, PartialEq)]
20604pub struct LineHighlight {
20605    pub background: Background,
20606    pub border: Option<gpui::Hsla>,
20607}
20608
20609impl From<Hsla> for LineHighlight {
20610    fn from(hsla: Hsla) -> Self {
20611        Self {
20612            background: hsla.into(),
20613            border: None,
20614        }
20615    }
20616}
20617
20618impl From<Background> for LineHighlight {
20619    fn from(background: Background) -> Self {
20620        Self {
20621            background,
20622            border: None,
20623        }
20624    }
20625}
20626
20627fn render_diff_hunk_controls(
20628    row: u32,
20629    status: &DiffHunkStatus,
20630    hunk_range: Range<Anchor>,
20631    is_created_file: bool,
20632    line_height: Pixels,
20633    editor: &Entity<Editor>,
20634    _window: &mut Window,
20635    cx: &mut App,
20636) -> AnyElement {
20637    h_flex()
20638        .h(line_height)
20639        .mr_1()
20640        .gap_1()
20641        .px_0p5()
20642        .pb_1()
20643        .border_x_1()
20644        .border_b_1()
20645        .border_color(cx.theme().colors().border_variant)
20646        .rounded_b_lg()
20647        .bg(cx.theme().colors().editor_background)
20648        .gap_1()
20649        .occlude()
20650        .shadow_md()
20651        .child(if status.has_secondary_hunk() {
20652            Button::new(("stage", row as u64), "Stage")
20653                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20654                .tooltip({
20655                    let focus_handle = editor.focus_handle(cx);
20656                    move |window, cx| {
20657                        Tooltip::for_action_in(
20658                            "Stage Hunk",
20659                            &::git::ToggleStaged,
20660                            &focus_handle,
20661                            window,
20662                            cx,
20663                        )
20664                    }
20665                })
20666                .on_click({
20667                    let editor = editor.clone();
20668                    move |_event, _window, cx| {
20669                        editor.update(cx, |editor, cx| {
20670                            editor.stage_or_unstage_diff_hunks(
20671                                true,
20672                                vec![hunk_range.start..hunk_range.start],
20673                                cx,
20674                            );
20675                        });
20676                    }
20677                })
20678        } else {
20679            Button::new(("unstage", row as u64), "Unstage")
20680                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20681                .tooltip({
20682                    let focus_handle = editor.focus_handle(cx);
20683                    move |window, cx| {
20684                        Tooltip::for_action_in(
20685                            "Unstage Hunk",
20686                            &::git::ToggleStaged,
20687                            &focus_handle,
20688                            window,
20689                            cx,
20690                        )
20691                    }
20692                })
20693                .on_click({
20694                    let editor = editor.clone();
20695                    move |_event, _window, cx| {
20696                        editor.update(cx, |editor, cx| {
20697                            editor.stage_or_unstage_diff_hunks(
20698                                false,
20699                                vec![hunk_range.start..hunk_range.start],
20700                                cx,
20701                            );
20702                        });
20703                    }
20704                })
20705        })
20706        .child(
20707            Button::new(("restore", row as u64), "Restore")
20708                .tooltip({
20709                    let focus_handle = editor.focus_handle(cx);
20710                    move |window, cx| {
20711                        Tooltip::for_action_in(
20712                            "Restore Hunk",
20713                            &::git::Restore,
20714                            &focus_handle,
20715                            window,
20716                            cx,
20717                        )
20718                    }
20719                })
20720                .on_click({
20721                    let editor = editor.clone();
20722                    move |_event, window, cx| {
20723                        editor.update(cx, |editor, cx| {
20724                            let snapshot = editor.snapshot(window, cx);
20725                            let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
20726                            editor.restore_hunks_in_ranges(vec![point..point], window, cx);
20727                        });
20728                    }
20729                })
20730                .disabled(is_created_file),
20731        )
20732        .when(
20733            !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
20734            |el| {
20735                el.child(
20736                    IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
20737                        .shape(IconButtonShape::Square)
20738                        .icon_size(IconSize::Small)
20739                        // .disabled(!has_multiple_hunks)
20740                        .tooltip({
20741                            let focus_handle = editor.focus_handle(cx);
20742                            move |window, cx| {
20743                                Tooltip::for_action_in(
20744                                    "Next Hunk",
20745                                    &GoToHunk,
20746                                    &focus_handle,
20747                                    window,
20748                                    cx,
20749                                )
20750                            }
20751                        })
20752                        .on_click({
20753                            let editor = editor.clone();
20754                            move |_event, window, cx| {
20755                                editor.update(cx, |editor, cx| {
20756                                    let snapshot = editor.snapshot(window, cx);
20757                                    let position =
20758                                        hunk_range.end.to_point(&snapshot.buffer_snapshot);
20759                                    editor.go_to_hunk_before_or_after_position(
20760                                        &snapshot,
20761                                        position,
20762                                        Direction::Next,
20763                                        window,
20764                                        cx,
20765                                    );
20766                                    editor.expand_selected_diff_hunks(cx);
20767                                });
20768                            }
20769                        }),
20770                )
20771                .child(
20772                    IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
20773                        .shape(IconButtonShape::Square)
20774                        .icon_size(IconSize::Small)
20775                        // .disabled(!has_multiple_hunks)
20776                        .tooltip({
20777                            let focus_handle = editor.focus_handle(cx);
20778                            move |window, cx| {
20779                                Tooltip::for_action_in(
20780                                    "Previous Hunk",
20781                                    &GoToPreviousHunk,
20782                                    &focus_handle,
20783                                    window,
20784                                    cx,
20785                                )
20786                            }
20787                        })
20788                        .on_click({
20789                            let editor = editor.clone();
20790                            move |_event, window, cx| {
20791                                editor.update(cx, |editor, cx| {
20792                                    let snapshot = editor.snapshot(window, cx);
20793                                    let point =
20794                                        hunk_range.start.to_point(&snapshot.buffer_snapshot);
20795                                    editor.go_to_hunk_before_or_after_position(
20796                                        &snapshot,
20797                                        point,
20798                                        Direction::Prev,
20799                                        window,
20800                                        cx,
20801                                    );
20802                                    editor.expand_selected_diff_hunks(cx);
20803                                });
20804                            }
20805                        }),
20806                )
20807            },
20808        )
20809        .into_any_element()
20810}