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
 3160        for (selection, autoclose_region) in
 3161            self.selections_with_autoclose_regions(selections, &snapshot)
 3162        {
 3163            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3164                // Determine if the inserted text matches the opening or closing
 3165                // bracket of any of this language's bracket pairs.
 3166                let mut bracket_pair = None;
 3167                let mut is_bracket_pair_start = false;
 3168                let mut is_bracket_pair_end = false;
 3169                if !text.is_empty() {
 3170                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3171                    //  and they are removing the character that triggered IME popup.
 3172                    for (pair, enabled) in scope.brackets() {
 3173                        if !pair.close && !pair.surround {
 3174                            continue;
 3175                        }
 3176
 3177                        if enabled && pair.start.ends_with(text.as_ref()) {
 3178                            let prefix_len = pair.start.len() - text.len();
 3179                            let preceding_text_matches_prefix = prefix_len == 0
 3180                                || (selection.start.column >= (prefix_len as u32)
 3181                                    && snapshot.contains_str_at(
 3182                                        Point::new(
 3183                                            selection.start.row,
 3184                                            selection.start.column - (prefix_len as u32),
 3185                                        ),
 3186                                        &pair.start[..prefix_len],
 3187                                    ));
 3188                            if preceding_text_matches_prefix {
 3189                                bracket_pair = Some(pair.clone());
 3190                                is_bracket_pair_start = true;
 3191                                break;
 3192                            }
 3193                        }
 3194                        if pair.end.as_str() == text.as_ref() {
 3195                            bracket_pair = Some(pair.clone());
 3196                            is_bracket_pair_end = true;
 3197                            break;
 3198                        }
 3199                    }
 3200                }
 3201
 3202                if let Some(bracket_pair) = bracket_pair {
 3203                    let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
 3204                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3205                    let auto_surround =
 3206                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3207                    if selection.is_empty() {
 3208                        if is_bracket_pair_start {
 3209                            // If the inserted text is a suffix of an opening bracket and the
 3210                            // selection is preceded by the rest of the opening bracket, then
 3211                            // insert the closing bracket.
 3212                            let following_text_allows_autoclose = snapshot
 3213                                .chars_at(selection.start)
 3214                                .next()
 3215                                .map_or(true, |c| scope.should_autoclose_before(c));
 3216
 3217                            let preceding_text_allows_autoclose = selection.start.column == 0
 3218                                || snapshot.reversed_chars_at(selection.start).next().map_or(
 3219                                    true,
 3220                                    |c| {
 3221                                        bracket_pair.start != bracket_pair.end
 3222                                            || !snapshot
 3223                                                .char_classifier_at(selection.start)
 3224                                                .is_word(c)
 3225                                    },
 3226                                );
 3227
 3228                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3229                                && bracket_pair.start.len() == 1
 3230                            {
 3231                                let target = bracket_pair.start.chars().next().unwrap();
 3232                                let current_line_count = snapshot
 3233                                    .reversed_chars_at(selection.start)
 3234                                    .take_while(|&c| c != '\n')
 3235                                    .filter(|&c| c == target)
 3236                                    .count();
 3237                                current_line_count % 2 == 1
 3238                            } else {
 3239                                false
 3240                            };
 3241
 3242                            if autoclose
 3243                                && bracket_pair.close
 3244                                && following_text_allows_autoclose
 3245                                && preceding_text_allows_autoclose
 3246                                && !is_closing_quote
 3247                            {
 3248                                let anchor = snapshot.anchor_before(selection.end);
 3249                                new_selections.push((selection.map(|_| anchor), text.len()));
 3250                                new_autoclose_regions.push((
 3251                                    anchor,
 3252                                    text.len(),
 3253                                    selection.id,
 3254                                    bracket_pair.clone(),
 3255                                ));
 3256                                edits.push((
 3257                                    selection.range(),
 3258                                    format!("{}{}", text, bracket_pair.end).into(),
 3259                                ));
 3260                                bracket_inserted = true;
 3261                                continue;
 3262                            }
 3263                        }
 3264
 3265                        if let Some(region) = autoclose_region {
 3266                            // If the selection is followed by an auto-inserted closing bracket,
 3267                            // then don't insert that closing bracket again; just move the selection
 3268                            // past the closing bracket.
 3269                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3270                                && text.as_ref() == region.pair.end.as_str();
 3271                            if should_skip {
 3272                                let anchor = snapshot.anchor_after(selection.end);
 3273                                new_selections
 3274                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3275                                continue;
 3276                            }
 3277                        }
 3278
 3279                        let always_treat_brackets_as_autoclosed = snapshot
 3280                            .language_settings_at(selection.start, cx)
 3281                            .always_treat_brackets_as_autoclosed;
 3282                        if always_treat_brackets_as_autoclosed
 3283                            && is_bracket_pair_end
 3284                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3285                        {
 3286                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3287                            // and the inserted text is a closing bracket and the selection is followed
 3288                            // by the closing bracket then move the selection past the closing bracket.
 3289                            let anchor = snapshot.anchor_after(selection.end);
 3290                            new_selections.push((selection.map(|_| anchor), text.len()));
 3291                            continue;
 3292                        }
 3293                    }
 3294                    // If an opening bracket is 1 character long and is typed while
 3295                    // text is selected, then surround that text with the bracket pair.
 3296                    else if auto_surround
 3297                        && bracket_pair.surround
 3298                        && is_bracket_pair_start
 3299                        && bracket_pair.start.chars().count() == 1
 3300                    {
 3301                        edits.push((selection.start..selection.start, text.clone()));
 3302                        edits.push((
 3303                            selection.end..selection.end,
 3304                            bracket_pair.end.as_str().into(),
 3305                        ));
 3306                        bracket_inserted = true;
 3307                        new_selections.push((
 3308                            Selection {
 3309                                id: selection.id,
 3310                                start: snapshot.anchor_after(selection.start),
 3311                                end: snapshot.anchor_before(selection.end),
 3312                                reversed: selection.reversed,
 3313                                goal: selection.goal,
 3314                            },
 3315                            0,
 3316                        ));
 3317                        continue;
 3318                    }
 3319                }
 3320            }
 3321
 3322            if self.auto_replace_emoji_shortcode
 3323                && selection.is_empty()
 3324                && text.as_ref().ends_with(':')
 3325            {
 3326                if let Some(possible_emoji_short_code) =
 3327                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3328                {
 3329                    if !possible_emoji_short_code.is_empty() {
 3330                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3331                            let emoji_shortcode_start = Point::new(
 3332                                selection.start.row,
 3333                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3334                            );
 3335
 3336                            // Remove shortcode from buffer
 3337                            edits.push((
 3338                                emoji_shortcode_start..selection.start,
 3339                                "".to_string().into(),
 3340                            ));
 3341                            new_selections.push((
 3342                                Selection {
 3343                                    id: selection.id,
 3344                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3345                                    end: snapshot.anchor_before(selection.start),
 3346                                    reversed: selection.reversed,
 3347                                    goal: selection.goal,
 3348                                },
 3349                                0,
 3350                            ));
 3351
 3352                            // Insert emoji
 3353                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3354                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3355                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3356
 3357                            continue;
 3358                        }
 3359                    }
 3360                }
 3361            }
 3362
 3363            // If not handling any auto-close operation, then just replace the selected
 3364            // text with the given input and move the selection to the end of the
 3365            // newly inserted text.
 3366            let anchor = snapshot.anchor_after(selection.end);
 3367            if !self.linked_edit_ranges.is_empty() {
 3368                let start_anchor = snapshot.anchor_before(selection.start);
 3369
 3370                let is_word_char = text.chars().next().map_or(true, |char| {
 3371                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3372                    classifier.is_word(char)
 3373                });
 3374
 3375                if is_word_char {
 3376                    if let Some(ranges) = self
 3377                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3378                    {
 3379                        for (buffer, edits) in ranges {
 3380                            linked_edits
 3381                                .entry(buffer.clone())
 3382                                .or_default()
 3383                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3384                        }
 3385                    }
 3386                }
 3387            }
 3388
 3389            new_selections.push((selection.map(|_| anchor), 0));
 3390            edits.push((selection.start..selection.end, text.clone()));
 3391        }
 3392
 3393        drop(snapshot);
 3394
 3395        self.transact(window, cx, |this, window, cx| {
 3396            let initial_buffer_versions =
 3397                jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
 3398
 3399            this.buffer.update(cx, |buffer, cx| {
 3400                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3401            });
 3402            for (buffer, edits) in linked_edits {
 3403                buffer.update(cx, |buffer, cx| {
 3404                    let snapshot = buffer.snapshot();
 3405                    let edits = edits
 3406                        .into_iter()
 3407                        .map(|(range, text)| {
 3408                            use text::ToPoint as TP;
 3409                            let end_point = TP::to_point(&range.end, &snapshot);
 3410                            let start_point = TP::to_point(&range.start, &snapshot);
 3411                            (start_point..end_point, text)
 3412                        })
 3413                        .sorted_by_key(|(range, _)| range.start);
 3414                    buffer.edit(edits, None, cx);
 3415                })
 3416            }
 3417            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3418            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3419            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3420            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3421                .zip(new_selection_deltas)
 3422                .map(|(selection, delta)| Selection {
 3423                    id: selection.id,
 3424                    start: selection.start + delta,
 3425                    end: selection.end + delta,
 3426                    reversed: selection.reversed,
 3427                    goal: SelectionGoal::None,
 3428                })
 3429                .collect::<Vec<_>>();
 3430
 3431            let mut i = 0;
 3432            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3433                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3434                let start = map.buffer_snapshot.anchor_before(position);
 3435                let end = map.buffer_snapshot.anchor_after(position);
 3436                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3437                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3438                        Ordering::Less => i += 1,
 3439                        Ordering::Greater => break,
 3440                        Ordering::Equal => {
 3441                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3442                                Ordering::Less => i += 1,
 3443                                Ordering::Equal => break,
 3444                                Ordering::Greater => break,
 3445                            }
 3446                        }
 3447                    }
 3448                }
 3449                this.autoclose_regions.insert(
 3450                    i,
 3451                    AutocloseRegion {
 3452                        selection_id,
 3453                        range: start..end,
 3454                        pair,
 3455                    },
 3456                );
 3457            }
 3458
 3459            let had_active_inline_completion = this.has_active_inline_completion();
 3460            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3461                s.select(new_selections)
 3462            });
 3463
 3464            if !bracket_inserted {
 3465                if let Some(on_type_format_task) =
 3466                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3467                {
 3468                    on_type_format_task.detach_and_log_err(cx);
 3469                }
 3470            }
 3471
 3472            let editor_settings = EditorSettings::get_global(cx);
 3473            if bracket_inserted
 3474                && (editor_settings.auto_signature_help
 3475                    || editor_settings.show_signature_help_after_edits)
 3476            {
 3477                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3478            }
 3479
 3480            let trigger_in_words =
 3481                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3482            if this.hard_wrap.is_some() {
 3483                let latest: Range<Point> = this.selections.newest(cx).range();
 3484                if latest.is_empty()
 3485                    && this
 3486                        .buffer()
 3487                        .read(cx)
 3488                        .snapshot(cx)
 3489                        .line_len(MultiBufferRow(latest.start.row))
 3490                        == latest.start.column
 3491                {
 3492                    this.rewrap_impl(
 3493                        RewrapOptions {
 3494                            override_language_settings: true,
 3495                            preserve_existing_whitespace: true,
 3496                        },
 3497                        cx,
 3498                    )
 3499                }
 3500            }
 3501            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3502            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3503            this.refresh_inline_completion(true, false, window, cx);
 3504            jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
 3505        });
 3506    }
 3507
 3508    fn find_possible_emoji_shortcode_at_position(
 3509        snapshot: &MultiBufferSnapshot,
 3510        position: Point,
 3511    ) -> Option<String> {
 3512        let mut chars = Vec::new();
 3513        let mut found_colon = false;
 3514        for char in snapshot.reversed_chars_at(position).take(100) {
 3515            // Found a possible emoji shortcode in the middle of the buffer
 3516            if found_colon {
 3517                if char.is_whitespace() {
 3518                    chars.reverse();
 3519                    return Some(chars.iter().collect());
 3520                }
 3521                // If the previous character is not a whitespace, we are in the middle of a word
 3522                // and we only want to complete the shortcode if the word is made up of other emojis
 3523                let mut containing_word = String::new();
 3524                for ch in snapshot
 3525                    .reversed_chars_at(position)
 3526                    .skip(chars.len() + 1)
 3527                    .take(100)
 3528                {
 3529                    if ch.is_whitespace() {
 3530                        break;
 3531                    }
 3532                    containing_word.push(ch);
 3533                }
 3534                let containing_word = containing_word.chars().rev().collect::<String>();
 3535                if util::word_consists_of_emojis(containing_word.as_str()) {
 3536                    chars.reverse();
 3537                    return Some(chars.iter().collect());
 3538                }
 3539            }
 3540
 3541            if char.is_whitespace() || !char.is_ascii() {
 3542                return None;
 3543            }
 3544            if char == ':' {
 3545                found_colon = true;
 3546            } else {
 3547                chars.push(char);
 3548            }
 3549        }
 3550        // Found a possible emoji shortcode at the beginning of the buffer
 3551        chars.reverse();
 3552        Some(chars.iter().collect())
 3553    }
 3554
 3555    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3556        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3557        self.transact(window, cx, |this, window, cx| {
 3558            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3559                let selections = this.selections.all::<usize>(cx);
 3560                let multi_buffer = this.buffer.read(cx);
 3561                let buffer = multi_buffer.snapshot(cx);
 3562                selections
 3563                    .iter()
 3564                    .map(|selection| {
 3565                        let start_point = selection.start.to_point(&buffer);
 3566                        let mut indent =
 3567                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3568                        indent.len = cmp::min(indent.len, start_point.column);
 3569                        let start = selection.start;
 3570                        let end = selection.end;
 3571                        let selection_is_empty = start == end;
 3572                        let language_scope = buffer.language_scope_at(start);
 3573                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3574                            &language_scope
 3575                        {
 3576                            let insert_extra_newline =
 3577                                insert_extra_newline_brackets(&buffer, start..end, language)
 3578                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3579
 3580                            // Comment extension on newline is allowed only for cursor selections
 3581                            let comment_delimiter = maybe!({
 3582                                if !selection_is_empty {
 3583                                    return None;
 3584                                }
 3585
 3586                                if !multi_buffer.language_settings(cx).extend_comment_on_newline {
 3587                                    return None;
 3588                                }
 3589
 3590                                let delimiters = language.line_comment_prefixes();
 3591                                let max_len_of_delimiter =
 3592                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3593                                let (snapshot, range) =
 3594                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3595
 3596                                let mut index_of_first_non_whitespace = 0;
 3597                                let comment_candidate = snapshot
 3598                                    .chars_for_range(range)
 3599                                    .skip_while(|c| {
 3600                                        let should_skip = c.is_whitespace();
 3601                                        if should_skip {
 3602                                            index_of_first_non_whitespace += 1;
 3603                                        }
 3604                                        should_skip
 3605                                    })
 3606                                    .take(max_len_of_delimiter)
 3607                                    .collect::<String>();
 3608                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3609                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3610                                })?;
 3611                                let cursor_is_placed_after_comment_marker =
 3612                                    index_of_first_non_whitespace + comment_prefix.len()
 3613                                        <= start_point.column as usize;
 3614                                if cursor_is_placed_after_comment_marker {
 3615                                    Some(comment_prefix.clone())
 3616                                } else {
 3617                                    None
 3618                                }
 3619                            });
 3620                            (comment_delimiter, insert_extra_newline)
 3621                        } else {
 3622                            (None, false)
 3623                        };
 3624
 3625                        let capacity_for_delimiter = comment_delimiter
 3626                            .as_deref()
 3627                            .map(str::len)
 3628                            .unwrap_or_default();
 3629                        let mut new_text =
 3630                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3631                        new_text.push('\n');
 3632                        new_text.extend(indent.chars());
 3633                        if let Some(delimiter) = &comment_delimiter {
 3634                            new_text.push_str(delimiter);
 3635                        }
 3636                        if insert_extra_newline {
 3637                            new_text = new_text.repeat(2);
 3638                        }
 3639
 3640                        let anchor = buffer.anchor_after(end);
 3641                        let new_selection = selection.map(|_| anchor);
 3642                        (
 3643                            (start..end, new_text),
 3644                            (insert_extra_newline, new_selection),
 3645                        )
 3646                    })
 3647                    .unzip()
 3648            };
 3649
 3650            this.edit_with_autoindent(edits, cx);
 3651            let buffer = this.buffer.read(cx).snapshot(cx);
 3652            let new_selections = selection_fixup_info
 3653                .into_iter()
 3654                .map(|(extra_newline_inserted, new_selection)| {
 3655                    let mut cursor = new_selection.end.to_point(&buffer);
 3656                    if extra_newline_inserted {
 3657                        cursor.row -= 1;
 3658                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3659                    }
 3660                    new_selection.map(|_| cursor)
 3661                })
 3662                .collect();
 3663
 3664            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3665                s.select(new_selections)
 3666            });
 3667            this.refresh_inline_completion(true, false, window, cx);
 3668        });
 3669    }
 3670
 3671    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3672        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3673
 3674        let buffer = self.buffer.read(cx);
 3675        let snapshot = buffer.snapshot(cx);
 3676
 3677        let mut edits = Vec::new();
 3678        let mut rows = Vec::new();
 3679
 3680        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3681            let cursor = selection.head();
 3682            let row = cursor.row;
 3683
 3684            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3685
 3686            let newline = "\n".to_string();
 3687            edits.push((start_of_line..start_of_line, newline));
 3688
 3689            rows.push(row + rows_inserted as u32);
 3690        }
 3691
 3692        self.transact(window, cx, |editor, window, cx| {
 3693            editor.edit(edits, cx);
 3694
 3695            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3696                let mut index = 0;
 3697                s.move_cursors_with(|map, _, _| {
 3698                    let row = rows[index];
 3699                    index += 1;
 3700
 3701                    let point = Point::new(row, 0);
 3702                    let boundary = map.next_line_boundary(point).1;
 3703                    let clipped = map.clip_point(boundary, Bias::Left);
 3704
 3705                    (clipped, SelectionGoal::None)
 3706                });
 3707            });
 3708
 3709            let mut indent_edits = Vec::new();
 3710            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3711            for row in rows {
 3712                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3713                for (row, indent) in indents {
 3714                    if indent.len == 0 {
 3715                        continue;
 3716                    }
 3717
 3718                    let text = match indent.kind {
 3719                        IndentKind::Space => " ".repeat(indent.len as usize),
 3720                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3721                    };
 3722                    let point = Point::new(row.0, 0);
 3723                    indent_edits.push((point..point, text));
 3724                }
 3725            }
 3726            editor.edit(indent_edits, cx);
 3727        });
 3728    }
 3729
 3730    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3731        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3732
 3733        let buffer = self.buffer.read(cx);
 3734        let snapshot = buffer.snapshot(cx);
 3735
 3736        let mut edits = Vec::new();
 3737        let mut rows = Vec::new();
 3738        let mut rows_inserted = 0;
 3739
 3740        for selection in self.selections.all_adjusted(cx) {
 3741            let cursor = selection.head();
 3742            let row = cursor.row;
 3743
 3744            let point = Point::new(row + 1, 0);
 3745            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3746
 3747            let newline = "\n".to_string();
 3748            edits.push((start_of_line..start_of_line, newline));
 3749
 3750            rows_inserted += 1;
 3751            rows.push(row + rows_inserted);
 3752        }
 3753
 3754        self.transact(window, cx, |editor, window, cx| {
 3755            editor.edit(edits, cx);
 3756
 3757            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3758                let mut index = 0;
 3759                s.move_cursors_with(|map, _, _| {
 3760                    let row = rows[index];
 3761                    index += 1;
 3762
 3763                    let point = Point::new(row, 0);
 3764                    let boundary = map.next_line_boundary(point).1;
 3765                    let clipped = map.clip_point(boundary, Bias::Left);
 3766
 3767                    (clipped, SelectionGoal::None)
 3768                });
 3769            });
 3770
 3771            let mut indent_edits = Vec::new();
 3772            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3773            for row in rows {
 3774                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3775                for (row, indent) in indents {
 3776                    if indent.len == 0 {
 3777                        continue;
 3778                    }
 3779
 3780                    let text = match indent.kind {
 3781                        IndentKind::Space => " ".repeat(indent.len as usize),
 3782                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3783                    };
 3784                    let point = Point::new(row.0, 0);
 3785                    indent_edits.push((point..point, text));
 3786                }
 3787            }
 3788            editor.edit(indent_edits, cx);
 3789        });
 3790    }
 3791
 3792    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3793        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3794            original_indent_columns: Vec::new(),
 3795        });
 3796        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3797    }
 3798
 3799    fn insert_with_autoindent_mode(
 3800        &mut self,
 3801        text: &str,
 3802        autoindent_mode: Option<AutoindentMode>,
 3803        window: &mut Window,
 3804        cx: &mut Context<Self>,
 3805    ) {
 3806        if self.read_only(cx) {
 3807            return;
 3808        }
 3809
 3810        let text: Arc<str> = text.into();
 3811        self.transact(window, cx, |this, window, cx| {
 3812            let old_selections = this.selections.all_adjusted(cx);
 3813            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3814                let anchors = {
 3815                    let snapshot = buffer.read(cx);
 3816                    old_selections
 3817                        .iter()
 3818                        .map(|s| {
 3819                            let anchor = snapshot.anchor_after(s.head());
 3820                            s.map(|_| anchor)
 3821                        })
 3822                        .collect::<Vec<_>>()
 3823                };
 3824                buffer.edit(
 3825                    old_selections
 3826                        .iter()
 3827                        .map(|s| (s.start..s.end, text.clone())),
 3828                    autoindent_mode,
 3829                    cx,
 3830                );
 3831                anchors
 3832            });
 3833
 3834            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3835                s.select_anchors(selection_anchors);
 3836            });
 3837
 3838            cx.notify();
 3839        });
 3840    }
 3841
 3842    fn trigger_completion_on_input(
 3843        &mut self,
 3844        text: &str,
 3845        trigger_in_words: bool,
 3846        window: &mut Window,
 3847        cx: &mut Context<Self>,
 3848    ) {
 3849        let ignore_completion_provider = self
 3850            .context_menu
 3851            .borrow()
 3852            .as_ref()
 3853            .map(|menu| match menu {
 3854                CodeContextMenu::Completions(completions_menu) => {
 3855                    completions_menu.ignore_completion_provider
 3856                }
 3857                CodeContextMenu::CodeActions(_) => false,
 3858            })
 3859            .unwrap_or(false);
 3860
 3861        if ignore_completion_provider {
 3862            self.show_word_completions(&ShowWordCompletions, window, cx);
 3863        } else if self.is_completion_trigger(text, trigger_in_words, cx) {
 3864            self.show_completions(
 3865                &ShowCompletions {
 3866                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3867                },
 3868                window,
 3869                cx,
 3870            );
 3871        } else {
 3872            self.hide_context_menu(window, cx);
 3873        }
 3874    }
 3875
 3876    fn is_completion_trigger(
 3877        &self,
 3878        text: &str,
 3879        trigger_in_words: bool,
 3880        cx: &mut Context<Self>,
 3881    ) -> bool {
 3882        let position = self.selections.newest_anchor().head();
 3883        let multibuffer = self.buffer.read(cx);
 3884        let Some(buffer) = position
 3885            .buffer_id
 3886            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3887        else {
 3888            return false;
 3889        };
 3890
 3891        if let Some(completion_provider) = &self.completion_provider {
 3892            completion_provider.is_completion_trigger(
 3893                &buffer,
 3894                position.text_anchor,
 3895                text,
 3896                trigger_in_words,
 3897                cx,
 3898            )
 3899        } else {
 3900            false
 3901        }
 3902    }
 3903
 3904    /// If any empty selections is touching the start of its innermost containing autoclose
 3905    /// region, expand it to select the brackets.
 3906    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3907        let selections = self.selections.all::<usize>(cx);
 3908        let buffer = self.buffer.read(cx).read(cx);
 3909        let new_selections = self
 3910            .selections_with_autoclose_regions(selections, &buffer)
 3911            .map(|(mut selection, region)| {
 3912                if !selection.is_empty() {
 3913                    return selection;
 3914                }
 3915
 3916                if let Some(region) = region {
 3917                    let mut range = region.range.to_offset(&buffer);
 3918                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3919                        range.start -= region.pair.start.len();
 3920                        if buffer.contains_str_at(range.start, &region.pair.start)
 3921                            && buffer.contains_str_at(range.end, &region.pair.end)
 3922                        {
 3923                            range.end += region.pair.end.len();
 3924                            selection.start = range.start;
 3925                            selection.end = range.end;
 3926
 3927                            return selection;
 3928                        }
 3929                    }
 3930                }
 3931
 3932                let always_treat_brackets_as_autoclosed = buffer
 3933                    .language_settings_at(selection.start, cx)
 3934                    .always_treat_brackets_as_autoclosed;
 3935
 3936                if !always_treat_brackets_as_autoclosed {
 3937                    return selection;
 3938                }
 3939
 3940                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3941                    for (pair, enabled) in scope.brackets() {
 3942                        if !enabled || !pair.close {
 3943                            continue;
 3944                        }
 3945
 3946                        if buffer.contains_str_at(selection.start, &pair.end) {
 3947                            let pair_start_len = pair.start.len();
 3948                            if buffer.contains_str_at(
 3949                                selection.start.saturating_sub(pair_start_len),
 3950                                &pair.start,
 3951                            ) {
 3952                                selection.start -= pair_start_len;
 3953                                selection.end += pair.end.len();
 3954
 3955                                return selection;
 3956                            }
 3957                        }
 3958                    }
 3959                }
 3960
 3961                selection
 3962            })
 3963            .collect();
 3964
 3965        drop(buffer);
 3966        self.change_selections(None, window, cx, |selections| {
 3967            selections.select(new_selections)
 3968        });
 3969    }
 3970
 3971    /// Iterate the given selections, and for each one, find the smallest surrounding
 3972    /// autoclose region. This uses the ordering of the selections and the autoclose
 3973    /// regions to avoid repeated comparisons.
 3974    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3975        &'a self,
 3976        selections: impl IntoIterator<Item = Selection<D>>,
 3977        buffer: &'a MultiBufferSnapshot,
 3978    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3979        let mut i = 0;
 3980        let mut regions = self.autoclose_regions.as_slice();
 3981        selections.into_iter().map(move |selection| {
 3982            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3983
 3984            let mut enclosing = None;
 3985            while let Some(pair_state) = regions.get(i) {
 3986                if pair_state.range.end.to_offset(buffer) < range.start {
 3987                    regions = &regions[i + 1..];
 3988                    i = 0;
 3989                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3990                    break;
 3991                } else {
 3992                    if pair_state.selection_id == selection.id {
 3993                        enclosing = Some(pair_state);
 3994                    }
 3995                    i += 1;
 3996                }
 3997            }
 3998
 3999            (selection, enclosing)
 4000        })
 4001    }
 4002
 4003    /// Remove any autoclose regions that no longer contain their selection.
 4004    fn invalidate_autoclose_regions(
 4005        &mut self,
 4006        mut selections: &[Selection<Anchor>],
 4007        buffer: &MultiBufferSnapshot,
 4008    ) {
 4009        self.autoclose_regions.retain(|state| {
 4010            let mut i = 0;
 4011            while let Some(selection) = selections.get(i) {
 4012                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4013                    selections = &selections[1..];
 4014                    continue;
 4015                }
 4016                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4017                    break;
 4018                }
 4019                if selection.id == state.selection_id {
 4020                    return true;
 4021                } else {
 4022                    i += 1;
 4023                }
 4024            }
 4025            false
 4026        });
 4027    }
 4028
 4029    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4030        let offset = position.to_offset(buffer);
 4031        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4032        if offset > word_range.start && kind == Some(CharKind::Word) {
 4033            Some(
 4034                buffer
 4035                    .text_for_range(word_range.start..offset)
 4036                    .collect::<String>(),
 4037            )
 4038        } else {
 4039            None
 4040        }
 4041    }
 4042
 4043    pub fn toggle_inlay_hints(
 4044        &mut self,
 4045        _: &ToggleInlayHints,
 4046        _: &mut Window,
 4047        cx: &mut Context<Self>,
 4048    ) {
 4049        self.refresh_inlay_hints(
 4050            InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
 4051            cx,
 4052        );
 4053    }
 4054
 4055    pub fn inlay_hints_enabled(&self) -> bool {
 4056        self.inlay_hint_cache.enabled
 4057    }
 4058
 4059    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 4060        if self.semantics_provider.is_none() || !self.mode.is_full() {
 4061            return;
 4062        }
 4063
 4064        let reason_description = reason.description();
 4065        let ignore_debounce = matches!(
 4066            reason,
 4067            InlayHintRefreshReason::SettingsChange(_)
 4068                | InlayHintRefreshReason::Toggle(_)
 4069                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4070                | InlayHintRefreshReason::ModifiersChanged(_)
 4071        );
 4072        let (invalidate_cache, required_languages) = match reason {
 4073            InlayHintRefreshReason::ModifiersChanged(enabled) => {
 4074                match self.inlay_hint_cache.modifiers_override(enabled) {
 4075                    Some(enabled) => {
 4076                        if enabled {
 4077                            (InvalidationStrategy::RefreshRequested, None)
 4078                        } else {
 4079                            self.splice_inlays(
 4080                                &self
 4081                                    .visible_inlay_hints(cx)
 4082                                    .iter()
 4083                                    .map(|inlay| inlay.id)
 4084                                    .collect::<Vec<InlayId>>(),
 4085                                Vec::new(),
 4086                                cx,
 4087                            );
 4088                            return;
 4089                        }
 4090                    }
 4091                    None => return,
 4092                }
 4093            }
 4094            InlayHintRefreshReason::Toggle(enabled) => {
 4095                if self.inlay_hint_cache.toggle(enabled) {
 4096                    if enabled {
 4097                        (InvalidationStrategy::RefreshRequested, None)
 4098                    } else {
 4099                        self.splice_inlays(
 4100                            &self
 4101                                .visible_inlay_hints(cx)
 4102                                .iter()
 4103                                .map(|inlay| inlay.id)
 4104                                .collect::<Vec<InlayId>>(),
 4105                            Vec::new(),
 4106                            cx,
 4107                        );
 4108                        return;
 4109                    }
 4110                } else {
 4111                    return;
 4112                }
 4113            }
 4114            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4115                match self.inlay_hint_cache.update_settings(
 4116                    &self.buffer,
 4117                    new_settings,
 4118                    self.visible_inlay_hints(cx),
 4119                    cx,
 4120                ) {
 4121                    ControlFlow::Break(Some(InlaySplice {
 4122                        to_remove,
 4123                        to_insert,
 4124                    })) => {
 4125                        self.splice_inlays(&to_remove, to_insert, cx);
 4126                        return;
 4127                    }
 4128                    ControlFlow::Break(None) => return,
 4129                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4130                }
 4131            }
 4132            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4133                if let Some(InlaySplice {
 4134                    to_remove,
 4135                    to_insert,
 4136                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 4137                {
 4138                    self.splice_inlays(&to_remove, to_insert, cx);
 4139                }
 4140                return;
 4141            }
 4142            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4143            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4144                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4145            }
 4146            InlayHintRefreshReason::RefreshRequested => {
 4147                (InvalidationStrategy::RefreshRequested, None)
 4148            }
 4149        };
 4150
 4151        if let Some(InlaySplice {
 4152            to_remove,
 4153            to_insert,
 4154        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4155            reason_description,
 4156            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4157            invalidate_cache,
 4158            ignore_debounce,
 4159            cx,
 4160        ) {
 4161            self.splice_inlays(&to_remove, to_insert, cx);
 4162        }
 4163    }
 4164
 4165    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 4166        self.display_map
 4167            .read(cx)
 4168            .current_inlays()
 4169            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4170            .cloned()
 4171            .collect()
 4172    }
 4173
 4174    pub fn excerpts_for_inlay_hints_query(
 4175        &self,
 4176        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4177        cx: &mut Context<Editor>,
 4178    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 4179        let Some(project) = self.project.as_ref() else {
 4180            return HashMap::default();
 4181        };
 4182        let project = project.read(cx);
 4183        let multi_buffer = self.buffer().read(cx);
 4184        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4185        let multi_buffer_visible_start = self
 4186            .scroll_manager
 4187            .anchor()
 4188            .anchor
 4189            .to_point(&multi_buffer_snapshot);
 4190        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4191            multi_buffer_visible_start
 4192                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4193            Bias::Left,
 4194        );
 4195        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4196        multi_buffer_snapshot
 4197            .range_to_buffer_ranges(multi_buffer_visible_range)
 4198            .into_iter()
 4199            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4200            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 4201                let buffer_file = project::File::from_dyn(buffer.file())?;
 4202                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4203                let worktree_entry = buffer_worktree
 4204                    .read(cx)
 4205                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4206                if worktree_entry.is_ignored {
 4207                    return None;
 4208                }
 4209
 4210                let language = buffer.language()?;
 4211                if let Some(restrict_to_languages) = restrict_to_languages {
 4212                    if !restrict_to_languages.contains(language) {
 4213                        return None;
 4214                    }
 4215                }
 4216                Some((
 4217                    excerpt_id,
 4218                    (
 4219                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 4220                        buffer.version().clone(),
 4221                        excerpt_visible_range,
 4222                    ),
 4223                ))
 4224            })
 4225            .collect()
 4226    }
 4227
 4228    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 4229        TextLayoutDetails {
 4230            text_system: window.text_system().clone(),
 4231            editor_style: self.style.clone().unwrap(),
 4232            rem_size: window.rem_size(),
 4233            scroll_anchor: self.scroll_manager.anchor(),
 4234            visible_rows: self.visible_line_count(),
 4235            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4236        }
 4237    }
 4238
 4239    pub fn splice_inlays(
 4240        &self,
 4241        to_remove: &[InlayId],
 4242        to_insert: Vec<Inlay>,
 4243        cx: &mut Context<Self>,
 4244    ) {
 4245        self.display_map.update(cx, |display_map, cx| {
 4246            display_map.splice_inlays(to_remove, to_insert, cx)
 4247        });
 4248        cx.notify();
 4249    }
 4250
 4251    fn trigger_on_type_formatting(
 4252        &self,
 4253        input: String,
 4254        window: &mut Window,
 4255        cx: &mut Context<Self>,
 4256    ) -> Option<Task<Result<()>>> {
 4257        if input.len() != 1 {
 4258            return None;
 4259        }
 4260
 4261        let project = self.project.as_ref()?;
 4262        let position = self.selections.newest_anchor().head();
 4263        let (buffer, buffer_position) = self
 4264            .buffer
 4265            .read(cx)
 4266            .text_anchor_for_position(position, cx)?;
 4267
 4268        let settings = language_settings::language_settings(
 4269            buffer
 4270                .read(cx)
 4271                .language_at(buffer_position)
 4272                .map(|l| l.name()),
 4273            buffer.read(cx).file(),
 4274            cx,
 4275        );
 4276        if !settings.use_on_type_format {
 4277            return None;
 4278        }
 4279
 4280        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4281        // hence we do LSP request & edit on host side only — add formats to host's history.
 4282        let push_to_lsp_host_history = true;
 4283        // If this is not the host, append its history with new edits.
 4284        let push_to_client_history = project.read(cx).is_via_collab();
 4285
 4286        let on_type_formatting = project.update(cx, |project, cx| {
 4287            project.on_type_format(
 4288                buffer.clone(),
 4289                buffer_position,
 4290                input,
 4291                push_to_lsp_host_history,
 4292                cx,
 4293            )
 4294        });
 4295        Some(cx.spawn_in(window, async move |editor, cx| {
 4296            if let Some(transaction) = on_type_formatting.await? {
 4297                if push_to_client_history {
 4298                    buffer
 4299                        .update(cx, |buffer, _| {
 4300                            buffer.push_transaction(transaction, Instant::now());
 4301                            buffer.finalize_last_transaction();
 4302                        })
 4303                        .ok();
 4304                }
 4305                editor.update(cx, |editor, cx| {
 4306                    editor.refresh_document_highlights(cx);
 4307                })?;
 4308            }
 4309            Ok(())
 4310        }))
 4311    }
 4312
 4313    pub fn show_word_completions(
 4314        &mut self,
 4315        _: &ShowWordCompletions,
 4316        window: &mut Window,
 4317        cx: &mut Context<Self>,
 4318    ) {
 4319        self.open_completions_menu(true, None, window, cx);
 4320    }
 4321
 4322    pub fn show_completions(
 4323        &mut self,
 4324        options: &ShowCompletions,
 4325        window: &mut Window,
 4326        cx: &mut Context<Self>,
 4327    ) {
 4328        self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
 4329    }
 4330
 4331    fn open_completions_menu(
 4332        &mut self,
 4333        ignore_completion_provider: bool,
 4334        trigger: Option<&str>,
 4335        window: &mut Window,
 4336        cx: &mut Context<Self>,
 4337    ) {
 4338        if self.pending_rename.is_some() {
 4339            return;
 4340        }
 4341        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 4342            return;
 4343        }
 4344
 4345        let position = self.selections.newest_anchor().head();
 4346        if position.diff_base_anchor.is_some() {
 4347            return;
 4348        }
 4349        let (buffer, buffer_position) =
 4350            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4351                output
 4352            } else {
 4353                return;
 4354            };
 4355        let buffer_snapshot = buffer.read(cx).snapshot();
 4356        let show_completion_documentation = buffer_snapshot
 4357            .settings_at(buffer_position, cx)
 4358            .show_completion_documentation;
 4359
 4360        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4361
 4362        let trigger_kind = match trigger {
 4363            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4364                CompletionTriggerKind::TRIGGER_CHARACTER
 4365            }
 4366            _ => CompletionTriggerKind::INVOKED,
 4367        };
 4368        let completion_context = CompletionContext {
 4369            trigger_character: trigger.and_then(|trigger| {
 4370                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4371                    Some(String::from(trigger))
 4372                } else {
 4373                    None
 4374                }
 4375            }),
 4376            trigger_kind,
 4377        };
 4378
 4379        let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
 4380        let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
 4381            let word_to_exclude = buffer_snapshot
 4382                .text_for_range(old_range.clone())
 4383                .collect::<String>();
 4384            (
 4385                buffer_snapshot.anchor_before(old_range.start)
 4386                    ..buffer_snapshot.anchor_after(old_range.end),
 4387                Some(word_to_exclude),
 4388            )
 4389        } else {
 4390            (buffer_position..buffer_position, None)
 4391        };
 4392
 4393        let completion_settings = language_settings(
 4394            buffer_snapshot
 4395                .language_at(buffer_position)
 4396                .map(|language| language.name()),
 4397            buffer_snapshot.file(),
 4398            cx,
 4399        )
 4400        .completions;
 4401
 4402        // The document can be large, so stay in reasonable bounds when searching for words,
 4403        // otherwise completion pop-up might be slow to appear.
 4404        const WORD_LOOKUP_ROWS: u32 = 5_000;
 4405        let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
 4406        let min_word_search = buffer_snapshot.clip_point(
 4407            Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
 4408            Bias::Left,
 4409        );
 4410        let max_word_search = buffer_snapshot.clip_point(
 4411            Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
 4412            Bias::Right,
 4413        );
 4414        let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
 4415            ..buffer_snapshot.point_to_offset(max_word_search);
 4416
 4417        let provider = self
 4418            .completion_provider
 4419            .as_ref()
 4420            .filter(|_| !ignore_completion_provider);
 4421        let skip_digits = query
 4422            .as_ref()
 4423            .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
 4424
 4425        let (mut words, provided_completions) = match provider {
 4426            Some(provider) => {
 4427                let completions = provider.completions(
 4428                    position.excerpt_id,
 4429                    &buffer,
 4430                    buffer_position,
 4431                    completion_context,
 4432                    window,
 4433                    cx,
 4434                );
 4435
 4436                let words = match completion_settings.words {
 4437                    WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
 4438                    WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
 4439                        .background_spawn(async move {
 4440                            buffer_snapshot.words_in_range(WordsQuery {
 4441                                fuzzy_contents: None,
 4442                                range: word_search_range,
 4443                                skip_digits,
 4444                            })
 4445                        }),
 4446                };
 4447
 4448                (words, completions)
 4449            }
 4450            None => (
 4451                cx.background_spawn(async move {
 4452                    buffer_snapshot.words_in_range(WordsQuery {
 4453                        fuzzy_contents: None,
 4454                        range: word_search_range,
 4455                        skip_digits,
 4456                    })
 4457                }),
 4458                Task::ready(Ok(None)),
 4459            ),
 4460        };
 4461
 4462        let sort_completions = provider
 4463            .as_ref()
 4464            .map_or(false, |provider| provider.sort_completions());
 4465
 4466        let filter_completions = provider
 4467            .as_ref()
 4468            .map_or(true, |provider| provider.filter_completions());
 4469
 4470        let id = post_inc(&mut self.next_completion_id);
 4471        let task = cx.spawn_in(window, async move |editor, cx| {
 4472            async move {
 4473                editor.update(cx, |this, _| {
 4474                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4475                })?;
 4476
 4477                let mut completions = Vec::new();
 4478                if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
 4479                    completions.extend(provided_completions);
 4480                    if completion_settings.words == WordsCompletionMode::Fallback {
 4481                        words = Task::ready(BTreeMap::default());
 4482                    }
 4483                }
 4484
 4485                let mut words = words.await;
 4486                if let Some(word_to_exclude) = &word_to_exclude {
 4487                    words.remove(word_to_exclude);
 4488                }
 4489                for lsp_completion in &completions {
 4490                    words.remove(&lsp_completion.new_text);
 4491                }
 4492                completions.extend(words.into_iter().map(|(word, word_range)| Completion {
 4493                    replace_range: old_range.clone(),
 4494                    new_text: word.clone(),
 4495                    label: CodeLabel::plain(word, None),
 4496                    icon_path: None,
 4497                    documentation: None,
 4498                    source: CompletionSource::BufferWord {
 4499                        word_range,
 4500                        resolved: false,
 4501                    },
 4502                    insert_text_mode: Some(InsertTextMode::AS_IS),
 4503                    confirm: None,
 4504                }));
 4505
 4506                let menu = if completions.is_empty() {
 4507                    None
 4508                } else {
 4509                    let mut menu = CompletionsMenu::new(
 4510                        id,
 4511                        sort_completions,
 4512                        show_completion_documentation,
 4513                        ignore_completion_provider,
 4514                        position,
 4515                        buffer.clone(),
 4516                        completions.into(),
 4517                    );
 4518
 4519                    menu.filter(
 4520                        if filter_completions {
 4521                            query.as_deref()
 4522                        } else {
 4523                            None
 4524                        },
 4525                        cx.background_executor().clone(),
 4526                    )
 4527                    .await;
 4528
 4529                    menu.visible().then_some(menu)
 4530                };
 4531
 4532                editor.update_in(cx, |editor, window, cx| {
 4533                    match editor.context_menu.borrow().as_ref() {
 4534                        None => {}
 4535                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4536                            if prev_menu.id > id {
 4537                                return;
 4538                            }
 4539                        }
 4540                        _ => return,
 4541                    }
 4542
 4543                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4544                        let mut menu = menu.unwrap();
 4545                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4546
 4547                        *editor.context_menu.borrow_mut() =
 4548                            Some(CodeContextMenu::Completions(menu));
 4549
 4550                        if editor.show_edit_predictions_in_menu() {
 4551                            editor.update_visible_inline_completion(window, cx);
 4552                        } else {
 4553                            editor.discard_inline_completion(false, cx);
 4554                        }
 4555
 4556                        cx.notify();
 4557                    } else if editor.completion_tasks.len() <= 1 {
 4558                        // If there are no more completion tasks and the last menu was
 4559                        // empty, we should hide it.
 4560                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4561                        // If it was already hidden and we don't show inline
 4562                        // completions in the menu, we should also show the
 4563                        // inline-completion when available.
 4564                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4565                            editor.update_visible_inline_completion(window, cx);
 4566                        }
 4567                    }
 4568                })?;
 4569
 4570                anyhow::Ok(())
 4571            }
 4572            .log_err()
 4573            .await
 4574        });
 4575
 4576        self.completion_tasks.push((id, task));
 4577    }
 4578
 4579    #[cfg(feature = "test-support")]
 4580    pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
 4581        let menu = self.context_menu.borrow();
 4582        if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
 4583            let completions = menu.completions.borrow();
 4584            Some(completions.to_vec())
 4585        } else {
 4586            None
 4587        }
 4588    }
 4589
 4590    pub fn confirm_completion(
 4591        &mut self,
 4592        action: &ConfirmCompletion,
 4593        window: &mut Window,
 4594        cx: &mut Context<Self>,
 4595    ) -> Option<Task<Result<()>>> {
 4596        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4597        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4598    }
 4599
 4600    pub fn confirm_completion_insert(
 4601        &mut self,
 4602        _: &ConfirmCompletionInsert,
 4603        window: &mut Window,
 4604        cx: &mut Context<Self>,
 4605    ) -> Option<Task<Result<()>>> {
 4606        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4607        self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
 4608    }
 4609
 4610    pub fn confirm_completion_replace(
 4611        &mut self,
 4612        _: &ConfirmCompletionReplace,
 4613        window: &mut Window,
 4614        cx: &mut Context<Self>,
 4615    ) -> Option<Task<Result<()>>> {
 4616        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4617        self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
 4618    }
 4619
 4620    pub fn compose_completion(
 4621        &mut self,
 4622        action: &ComposeCompletion,
 4623        window: &mut Window,
 4624        cx: &mut Context<Self>,
 4625    ) -> Option<Task<Result<()>>> {
 4626        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4627        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4628    }
 4629
 4630    fn do_completion(
 4631        &mut self,
 4632        item_ix: Option<usize>,
 4633        intent: CompletionIntent,
 4634        window: &mut Window,
 4635        cx: &mut Context<Editor>,
 4636    ) -> Option<Task<Result<()>>> {
 4637        use language::ToOffset as _;
 4638
 4639        let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
 4640        else {
 4641            return None;
 4642        };
 4643
 4644        let candidate_id = {
 4645            let entries = completions_menu.entries.borrow();
 4646            let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4647            if self.show_edit_predictions_in_menu() {
 4648                self.discard_inline_completion(true, cx);
 4649            }
 4650            mat.candidate_id
 4651        };
 4652
 4653        let buffer_handle = completions_menu.buffer;
 4654        let completion = completions_menu
 4655            .completions
 4656            .borrow()
 4657            .get(candidate_id)?
 4658            .clone();
 4659        cx.stop_propagation();
 4660
 4661        let snippet;
 4662        let new_text;
 4663        if completion.is_snippet() {
 4664            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4665            new_text = snippet.as_ref().unwrap().text.clone();
 4666        } else {
 4667            snippet = None;
 4668            new_text = completion.new_text.clone();
 4669        };
 4670        let selections = self.selections.all::<usize>(cx);
 4671
 4672        let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
 4673        let buffer = buffer_handle.read(cx);
 4674        let old_text = buffer
 4675            .text_for_range(replace_range.clone())
 4676            .collect::<String>();
 4677
 4678        let newest_selection = self.selections.newest_anchor();
 4679        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4680            return None;
 4681        }
 4682
 4683        let lookbehind = newest_selection
 4684            .start
 4685            .text_anchor
 4686            .to_offset(buffer)
 4687            .saturating_sub(replace_range.start);
 4688        let lookahead = replace_range
 4689            .end
 4690            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4691        let mut common_prefix_len = 0;
 4692        for (a, b) in old_text.chars().zip(new_text.chars()) {
 4693            if a == b {
 4694                common_prefix_len += a.len_utf8();
 4695            } else {
 4696                break;
 4697            }
 4698        }
 4699
 4700        let snapshot = self.buffer.read(cx).snapshot(cx);
 4701        let mut range_to_replace: Option<Range<usize>> = None;
 4702        let mut ranges = Vec::new();
 4703        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4704        for selection in &selections {
 4705            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4706                let start = selection.start.saturating_sub(lookbehind);
 4707                let end = selection.end + lookahead;
 4708                if selection.id == newest_selection.id {
 4709                    range_to_replace = Some(start + common_prefix_len..end);
 4710                }
 4711                ranges.push(start + common_prefix_len..end);
 4712            } else {
 4713                common_prefix_len = 0;
 4714                ranges.clear();
 4715                ranges.extend(selections.iter().map(|s| {
 4716                    if s.id == newest_selection.id {
 4717                        range_to_replace = Some(replace_range.clone());
 4718                        replace_range.clone()
 4719                    } else {
 4720                        s.start..s.end
 4721                    }
 4722                }));
 4723                break;
 4724            }
 4725            if !self.linked_edit_ranges.is_empty() {
 4726                let start_anchor = snapshot.anchor_before(selection.head());
 4727                let end_anchor = snapshot.anchor_after(selection.tail());
 4728                if let Some(ranges) = self
 4729                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4730                {
 4731                    for (buffer, edits) in ranges {
 4732                        linked_edits.entry(buffer.clone()).or_default().extend(
 4733                            edits
 4734                                .into_iter()
 4735                                .map(|range| (range, new_text[common_prefix_len..].to_owned())),
 4736                        );
 4737                    }
 4738                }
 4739            }
 4740        }
 4741        let text = &new_text[common_prefix_len..];
 4742
 4743        let utf16_range_to_replace = range_to_replace.map(|range| {
 4744            let newest_selection = self.selections.newest::<OffsetUtf16>(cx).range();
 4745            let selection_start_utf16 = newest_selection.start.0 as isize;
 4746
 4747            range.start.to_offset_utf16(&snapshot).0 as isize - selection_start_utf16
 4748                ..range.end.to_offset_utf16(&snapshot).0 as isize - selection_start_utf16
 4749        });
 4750        cx.emit(EditorEvent::InputHandled {
 4751            utf16_range_to_replace,
 4752            text: text.into(),
 4753        });
 4754
 4755        self.transact(window, cx, |this, window, cx| {
 4756            if let Some(mut snippet) = snippet {
 4757                snippet.text = text.to_string();
 4758                for tabstop in snippet
 4759                    .tabstops
 4760                    .iter_mut()
 4761                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4762                {
 4763                    tabstop.start -= common_prefix_len as isize;
 4764                    tabstop.end -= common_prefix_len as isize;
 4765                }
 4766
 4767                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4768            } else {
 4769                this.buffer.update(cx, |buffer, cx| {
 4770                    let edits = ranges.iter().map(|range| (range.clone(), text));
 4771                    let auto_indent = if completion.insert_text_mode == Some(InsertTextMode::AS_IS)
 4772                    {
 4773                        None
 4774                    } else {
 4775                        this.autoindent_mode.clone()
 4776                    };
 4777                    buffer.edit(edits, auto_indent, cx);
 4778                });
 4779            }
 4780            for (buffer, edits) in linked_edits {
 4781                buffer.update(cx, |buffer, cx| {
 4782                    let snapshot = buffer.snapshot();
 4783                    let edits = edits
 4784                        .into_iter()
 4785                        .map(|(range, text)| {
 4786                            use text::ToPoint as TP;
 4787                            let end_point = TP::to_point(&range.end, &snapshot);
 4788                            let start_point = TP::to_point(&range.start, &snapshot);
 4789                            (start_point..end_point, text)
 4790                        })
 4791                        .sorted_by_key(|(range, _)| range.start);
 4792                    buffer.edit(edits, None, cx);
 4793                })
 4794            }
 4795
 4796            this.refresh_inline_completion(true, false, window, cx);
 4797        });
 4798
 4799        let show_new_completions_on_confirm = completion
 4800            .confirm
 4801            .as_ref()
 4802            .map_or(false, |confirm| confirm(intent, window, cx));
 4803        if show_new_completions_on_confirm {
 4804            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4805        }
 4806
 4807        let provider = self.completion_provider.as_ref()?;
 4808        drop(completion);
 4809        let apply_edits = provider.apply_additional_edits_for_completion(
 4810            buffer_handle,
 4811            completions_menu.completions.clone(),
 4812            candidate_id,
 4813            true,
 4814            cx,
 4815        );
 4816
 4817        let editor_settings = EditorSettings::get_global(cx);
 4818        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4819            // After the code completion is finished, users often want to know what signatures are needed.
 4820            // so we should automatically call signature_help
 4821            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4822        }
 4823
 4824        Some(cx.foreground_executor().spawn(async move {
 4825            apply_edits.await?;
 4826            Ok(())
 4827        }))
 4828    }
 4829
 4830    pub fn toggle_code_actions(
 4831        &mut self,
 4832        action: &ToggleCodeActions,
 4833        window: &mut Window,
 4834        cx: &mut Context<Self>,
 4835    ) {
 4836        let mut context_menu = self.context_menu.borrow_mut();
 4837        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4838            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4839                // Toggle if we're selecting the same one
 4840                *context_menu = None;
 4841                cx.notify();
 4842                return;
 4843            } else {
 4844                // Otherwise, clear it and start a new one
 4845                *context_menu = None;
 4846                cx.notify();
 4847            }
 4848        }
 4849        drop(context_menu);
 4850        let snapshot = self.snapshot(window, cx);
 4851        let deployed_from_indicator = action.deployed_from_indicator;
 4852        let mut task = self.code_actions_task.take();
 4853        let action = action.clone();
 4854        cx.spawn_in(window, async move |editor, cx| {
 4855            while let Some(prev_task) = task {
 4856                prev_task.await.log_err();
 4857                task = editor.update(cx, |this, _| this.code_actions_task.take())?;
 4858            }
 4859
 4860            let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
 4861                if editor.focus_handle.is_focused(window) {
 4862                    let multibuffer_point = action
 4863                        .deployed_from_indicator
 4864                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4865                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4866                    let (buffer, buffer_row) = snapshot
 4867                        .buffer_snapshot
 4868                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4869                        .and_then(|(buffer_snapshot, range)| {
 4870                            editor
 4871                                .buffer
 4872                                .read(cx)
 4873                                .buffer(buffer_snapshot.remote_id())
 4874                                .map(|buffer| (buffer, range.start.row))
 4875                        })?;
 4876                    let (_, code_actions) = editor
 4877                        .available_code_actions
 4878                        .clone()
 4879                        .and_then(|(location, code_actions)| {
 4880                            let snapshot = location.buffer.read(cx).snapshot();
 4881                            let point_range = location.range.to_point(&snapshot);
 4882                            let point_range = point_range.start.row..=point_range.end.row;
 4883                            if point_range.contains(&buffer_row) {
 4884                                Some((location, code_actions))
 4885                            } else {
 4886                                None
 4887                            }
 4888                        })
 4889                        .unzip();
 4890                    let buffer_id = buffer.read(cx).remote_id();
 4891                    let tasks = editor
 4892                        .tasks
 4893                        .get(&(buffer_id, buffer_row))
 4894                        .map(|t| Arc::new(t.to_owned()));
 4895                    if tasks.is_none() && code_actions.is_none() {
 4896                        return None;
 4897                    }
 4898
 4899                    editor.completion_tasks.clear();
 4900                    editor.discard_inline_completion(false, cx);
 4901                    let task_context =
 4902                        tasks
 4903                            .as_ref()
 4904                            .zip(editor.project.clone())
 4905                            .map(|(tasks, project)| {
 4906                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4907                            });
 4908
 4909                    let debugger_flag = cx.has_flag::<Debugger>();
 4910
 4911                    Some(cx.spawn_in(window, async move |editor, cx| {
 4912                        let task_context = match task_context {
 4913                            Some(task_context) => task_context.await,
 4914                            None => None,
 4915                        };
 4916                        let resolved_tasks =
 4917                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4918                                Rc::new(ResolvedTasks {
 4919                                    templates: tasks.resolve(&task_context).collect(),
 4920                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4921                                        multibuffer_point.row,
 4922                                        tasks.column,
 4923                                    )),
 4924                                })
 4925                            });
 4926                        let spawn_straight_away = resolved_tasks.as_ref().map_or(false, |tasks| {
 4927                            tasks
 4928                                .templates
 4929                                .iter()
 4930                                .filter(|task| {
 4931                                    if matches!(task.1.task_type(), task::TaskType::Debug(_)) {
 4932                                        debugger_flag
 4933                                    } else {
 4934                                        true
 4935                                    }
 4936                                })
 4937                                .count()
 4938                                == 1
 4939                        }) && code_actions
 4940                            .as_ref()
 4941                            .map_or(true, |actions| actions.is_empty());
 4942                        if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
 4943                            *editor.context_menu.borrow_mut() =
 4944                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4945                                    buffer,
 4946                                    actions: CodeActionContents {
 4947                                        tasks: resolved_tasks,
 4948                                        actions: code_actions,
 4949                                    },
 4950                                    selected_item: Default::default(),
 4951                                    scroll_handle: UniformListScrollHandle::default(),
 4952                                    deployed_from_indicator,
 4953                                }));
 4954                            if spawn_straight_away {
 4955                                if let Some(task) = editor.confirm_code_action(
 4956                                    &ConfirmCodeAction { item_ix: Some(0) },
 4957                                    window,
 4958                                    cx,
 4959                                ) {
 4960                                    cx.notify();
 4961                                    return task;
 4962                                }
 4963                            }
 4964                            cx.notify();
 4965                            Task::ready(Ok(()))
 4966                        }) {
 4967                            task.await
 4968                        } else {
 4969                            Ok(())
 4970                        }
 4971                    }))
 4972                } else {
 4973                    Some(Task::ready(Ok(())))
 4974                }
 4975            })?;
 4976            if let Some(task) = spawned_test_task {
 4977                task.await?;
 4978            }
 4979
 4980            Ok::<_, anyhow::Error>(())
 4981        })
 4982        .detach_and_log_err(cx);
 4983    }
 4984
 4985    pub fn confirm_code_action(
 4986        &mut self,
 4987        action: &ConfirmCodeAction,
 4988        window: &mut Window,
 4989        cx: &mut Context<Self>,
 4990    ) -> Option<Task<Result<()>>> {
 4991        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4992
 4993        let actions_menu =
 4994            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4995                menu
 4996            } else {
 4997                return None;
 4998            };
 4999
 5000        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 5001        let action = actions_menu.actions.get(action_ix)?;
 5002        let title = action.label();
 5003        let buffer = actions_menu.buffer;
 5004        let workspace = self.workspace()?;
 5005
 5006        match action {
 5007            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 5008                match resolved_task.task_type() {
 5009                    task::TaskType::Script => workspace.update(cx, |workspace, cx| {
 5010                        workspace::tasks::schedule_resolved_task(
 5011                            workspace,
 5012                            task_source_kind,
 5013                            resolved_task,
 5014                            false,
 5015                            cx,
 5016                        );
 5017
 5018                        Some(Task::ready(Ok(())))
 5019                    }),
 5020                    task::TaskType::Debug(debug_args) => {
 5021                        if debug_args.locator.is_some() {
 5022                            workspace.update(cx, |workspace, cx| {
 5023                                workspace::tasks::schedule_resolved_task(
 5024                                    workspace,
 5025                                    task_source_kind,
 5026                                    resolved_task,
 5027                                    false,
 5028                                    cx,
 5029                                );
 5030                            });
 5031
 5032                            return Some(Task::ready(Ok(())));
 5033                        }
 5034
 5035                        if let Some(project) = self.project.as_ref() {
 5036                            project
 5037                                .update(cx, |project, cx| {
 5038                                    project.start_debug_session(
 5039                                        resolved_task.resolved_debug_adapter_config().unwrap(),
 5040                                        cx,
 5041                                    )
 5042                                })
 5043                                .detach_and_log_err(cx);
 5044                            Some(Task::ready(Ok(())))
 5045                        } else {
 5046                            Some(Task::ready(Ok(())))
 5047                        }
 5048                    }
 5049                }
 5050            }
 5051            CodeActionsItem::CodeAction {
 5052                excerpt_id,
 5053                action,
 5054                provider,
 5055            } => {
 5056                let apply_code_action =
 5057                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 5058                let workspace = workspace.downgrade();
 5059                Some(cx.spawn_in(window, async move |editor, cx| {
 5060                    let project_transaction = apply_code_action.await?;
 5061                    Self::open_project_transaction(
 5062                        &editor,
 5063                        workspace,
 5064                        project_transaction,
 5065                        title,
 5066                        cx,
 5067                    )
 5068                    .await
 5069                }))
 5070            }
 5071        }
 5072    }
 5073
 5074    pub async fn open_project_transaction(
 5075        this: &WeakEntity<Editor>,
 5076        workspace: WeakEntity<Workspace>,
 5077        transaction: ProjectTransaction,
 5078        title: String,
 5079        cx: &mut AsyncWindowContext,
 5080    ) -> Result<()> {
 5081        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 5082        cx.update(|_, cx| {
 5083            entries.sort_unstable_by_key(|(buffer, _)| {
 5084                buffer.read(cx).file().map(|f| f.path().clone())
 5085            });
 5086        })?;
 5087
 5088        // If the project transaction's edits are all contained within this editor, then
 5089        // avoid opening a new editor to display them.
 5090
 5091        if let Some((buffer, transaction)) = entries.first() {
 5092            if entries.len() == 1 {
 5093                let excerpt = this.update(cx, |editor, cx| {
 5094                    editor
 5095                        .buffer()
 5096                        .read(cx)
 5097                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 5098                })?;
 5099                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 5100                    if excerpted_buffer == *buffer {
 5101                        let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
 5102                            let excerpt_range = excerpt_range.to_offset(buffer);
 5103                            buffer
 5104                                .edited_ranges_for_transaction::<usize>(transaction)
 5105                                .all(|range| {
 5106                                    excerpt_range.start <= range.start
 5107                                        && excerpt_range.end >= range.end
 5108                                })
 5109                        })?;
 5110
 5111                        if all_edits_within_excerpt {
 5112                            return Ok(());
 5113                        }
 5114                    }
 5115                }
 5116            }
 5117        } else {
 5118            return Ok(());
 5119        }
 5120
 5121        let mut ranges_to_highlight = Vec::new();
 5122        let excerpt_buffer = cx.new(|cx| {
 5123            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 5124            for (buffer_handle, transaction) in &entries {
 5125                let edited_ranges = buffer_handle
 5126                    .read(cx)
 5127                    .edited_ranges_for_transaction::<Point>(transaction)
 5128                    .collect::<Vec<_>>();
 5129                let (ranges, _) = multibuffer.set_excerpts_for_path(
 5130                    PathKey::for_buffer(buffer_handle, cx),
 5131                    buffer_handle.clone(),
 5132                    edited_ranges,
 5133                    DEFAULT_MULTIBUFFER_CONTEXT,
 5134                    cx,
 5135                );
 5136
 5137                ranges_to_highlight.extend(ranges);
 5138            }
 5139            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5140            multibuffer
 5141        })?;
 5142
 5143        workspace.update_in(cx, |workspace, window, cx| {
 5144            let project = workspace.project().clone();
 5145            let editor =
 5146                cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
 5147            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 5148            editor.update(cx, |editor, cx| {
 5149                editor.highlight_background::<Self>(
 5150                    &ranges_to_highlight,
 5151                    |theme| theme.editor_highlighted_line_background,
 5152                    cx,
 5153                );
 5154            });
 5155        })?;
 5156
 5157        Ok(())
 5158    }
 5159
 5160    pub fn clear_code_action_providers(&mut self) {
 5161        self.code_action_providers.clear();
 5162        self.available_code_actions.take();
 5163    }
 5164
 5165    pub fn add_code_action_provider(
 5166        &mut self,
 5167        provider: Rc<dyn CodeActionProvider>,
 5168        window: &mut Window,
 5169        cx: &mut Context<Self>,
 5170    ) {
 5171        if self
 5172            .code_action_providers
 5173            .iter()
 5174            .any(|existing_provider| existing_provider.id() == provider.id())
 5175        {
 5176            return;
 5177        }
 5178
 5179        self.code_action_providers.push(provider);
 5180        self.refresh_code_actions(window, cx);
 5181    }
 5182
 5183    pub fn remove_code_action_provider(
 5184        &mut self,
 5185        id: Arc<str>,
 5186        window: &mut Window,
 5187        cx: &mut Context<Self>,
 5188    ) {
 5189        self.code_action_providers
 5190            .retain(|provider| provider.id() != id);
 5191        self.refresh_code_actions(window, cx);
 5192    }
 5193
 5194    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 5195        let buffer = self.buffer.read(cx);
 5196        let newest_selection = self.selections.newest_anchor().clone();
 5197        if newest_selection.head().diff_base_anchor.is_some() {
 5198            return None;
 5199        }
 5200        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 5201        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 5202        if start_buffer != end_buffer {
 5203            return None;
 5204        }
 5205
 5206        self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
 5207            cx.background_executor()
 5208                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5209                .await;
 5210
 5211            let (providers, tasks) = this.update_in(cx, |this, window, cx| {
 5212                let providers = this.code_action_providers.clone();
 5213                let tasks = this
 5214                    .code_action_providers
 5215                    .iter()
 5216                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 5217                    .collect::<Vec<_>>();
 5218                (providers, tasks)
 5219            })?;
 5220
 5221            let mut actions = Vec::new();
 5222            for (provider, provider_actions) in
 5223                providers.into_iter().zip(future::join_all(tasks).await)
 5224            {
 5225                if let Some(provider_actions) = provider_actions.log_err() {
 5226                    actions.extend(provider_actions.into_iter().map(|action| {
 5227                        AvailableCodeAction {
 5228                            excerpt_id: newest_selection.start.excerpt_id,
 5229                            action,
 5230                            provider: provider.clone(),
 5231                        }
 5232                    }));
 5233                }
 5234            }
 5235
 5236            this.update(cx, |this, cx| {
 5237                this.available_code_actions = if actions.is_empty() {
 5238                    None
 5239                } else {
 5240                    Some((
 5241                        Location {
 5242                            buffer: start_buffer,
 5243                            range: start..end,
 5244                        },
 5245                        actions.into(),
 5246                    ))
 5247                };
 5248                cx.notify();
 5249            })
 5250        }));
 5251        None
 5252    }
 5253
 5254    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5255        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5256            self.show_git_blame_inline = false;
 5257
 5258            self.show_git_blame_inline_delay_task =
 5259                Some(cx.spawn_in(window, async move |this, cx| {
 5260                    cx.background_executor().timer(delay).await;
 5261
 5262                    this.update(cx, |this, cx| {
 5263                        this.show_git_blame_inline = true;
 5264                        cx.notify();
 5265                    })
 5266                    .log_err();
 5267                }));
 5268        }
 5269    }
 5270
 5271    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 5272        if self.pending_rename.is_some() {
 5273            return None;
 5274        }
 5275
 5276        let provider = self.semantics_provider.clone()?;
 5277        let buffer = self.buffer.read(cx);
 5278        let newest_selection = self.selections.newest_anchor().clone();
 5279        let cursor_position = newest_selection.head();
 5280        let (cursor_buffer, cursor_buffer_position) =
 5281            buffer.text_anchor_for_position(cursor_position, cx)?;
 5282        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5283        if cursor_buffer != tail_buffer {
 5284            return None;
 5285        }
 5286        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 5287        self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
 5288            cx.background_executor()
 5289                .timer(Duration::from_millis(debounce))
 5290                .await;
 5291
 5292            let highlights = if let Some(highlights) = cx
 5293                .update(|cx| {
 5294                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5295                })
 5296                .ok()
 5297                .flatten()
 5298            {
 5299                highlights.await.log_err()
 5300            } else {
 5301                None
 5302            };
 5303
 5304            if let Some(highlights) = highlights {
 5305                this.update(cx, |this, cx| {
 5306                    if this.pending_rename.is_some() {
 5307                        return;
 5308                    }
 5309
 5310                    let buffer_id = cursor_position.buffer_id;
 5311                    let buffer = this.buffer.read(cx);
 5312                    if !buffer
 5313                        .text_anchor_for_position(cursor_position, cx)
 5314                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5315                    {
 5316                        return;
 5317                    }
 5318
 5319                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5320                    let mut write_ranges = Vec::new();
 5321                    let mut read_ranges = Vec::new();
 5322                    for highlight in highlights {
 5323                        for (excerpt_id, excerpt_range) in
 5324                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 5325                        {
 5326                            let start = highlight
 5327                                .range
 5328                                .start
 5329                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5330                            let end = highlight
 5331                                .range
 5332                                .end
 5333                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5334                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5335                                continue;
 5336                            }
 5337
 5338                            let range = Anchor {
 5339                                buffer_id,
 5340                                excerpt_id,
 5341                                text_anchor: start,
 5342                                diff_base_anchor: None,
 5343                            }..Anchor {
 5344                                buffer_id,
 5345                                excerpt_id,
 5346                                text_anchor: end,
 5347                                diff_base_anchor: None,
 5348                            };
 5349                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5350                                write_ranges.push(range);
 5351                            } else {
 5352                                read_ranges.push(range);
 5353                            }
 5354                        }
 5355                    }
 5356
 5357                    this.highlight_background::<DocumentHighlightRead>(
 5358                        &read_ranges,
 5359                        |theme| theme.editor_document_highlight_read_background,
 5360                        cx,
 5361                    );
 5362                    this.highlight_background::<DocumentHighlightWrite>(
 5363                        &write_ranges,
 5364                        |theme| theme.editor_document_highlight_write_background,
 5365                        cx,
 5366                    );
 5367                    cx.notify();
 5368                })
 5369                .log_err();
 5370            }
 5371        }));
 5372        None
 5373    }
 5374
 5375    pub fn refresh_selected_text_highlights(
 5376        &mut self,
 5377        window: &mut Window,
 5378        cx: &mut Context<Editor>,
 5379    ) {
 5380        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 5381            return;
 5382        }
 5383        self.selection_highlight_task.take();
 5384        if !EditorSettings::get_global(cx).selection_highlight {
 5385            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5386            return;
 5387        }
 5388        if self.selections.count() != 1 || self.selections.line_mode {
 5389            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5390            return;
 5391        }
 5392        let selection = self.selections.newest::<Point>(cx);
 5393        if selection.is_empty() || selection.start.row != selection.end.row {
 5394            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5395            return;
 5396        }
 5397        let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
 5398        self.selection_highlight_task = Some(cx.spawn_in(window, async move |editor, cx| {
 5399            cx.background_executor()
 5400                .timer(Duration::from_millis(debounce))
 5401                .await;
 5402            let Some(Some(matches_task)) = editor
 5403                .update_in(cx, |editor, _, cx| {
 5404                    if editor.selections.count() != 1 || editor.selections.line_mode {
 5405                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5406                        return None;
 5407                    }
 5408                    let selection = editor.selections.newest::<Point>(cx);
 5409                    if selection.is_empty() || selection.start.row != selection.end.row {
 5410                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5411                        return None;
 5412                    }
 5413                    let buffer = editor.buffer().read(cx).snapshot(cx);
 5414                    let query = buffer.text_for_range(selection.range()).collect::<String>();
 5415                    if query.trim().is_empty() {
 5416                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5417                        return None;
 5418                    }
 5419                    Some(cx.background_spawn(async move {
 5420                        let mut ranges = Vec::new();
 5421                        let selection_anchors = selection.range().to_anchors(&buffer);
 5422                        for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
 5423                            for (search_buffer, search_range, excerpt_id) in
 5424                                buffer.range_to_buffer_ranges(range)
 5425                            {
 5426                                ranges.extend(
 5427                                    project::search::SearchQuery::text(
 5428                                        query.clone(),
 5429                                        false,
 5430                                        false,
 5431                                        false,
 5432                                        Default::default(),
 5433                                        Default::default(),
 5434                                        None,
 5435                                    )
 5436                                    .unwrap()
 5437                                    .search(search_buffer, Some(search_range.clone()))
 5438                                    .await
 5439                                    .into_iter()
 5440                                    .filter_map(
 5441                                        |match_range| {
 5442                                            let start = search_buffer.anchor_after(
 5443                                                search_range.start + match_range.start,
 5444                                            );
 5445                                            let end = search_buffer.anchor_before(
 5446                                                search_range.start + match_range.end,
 5447                                            );
 5448                                            let range = Anchor::range_in_buffer(
 5449                                                excerpt_id,
 5450                                                search_buffer.remote_id(),
 5451                                                start..end,
 5452                                            );
 5453                                            (range != selection_anchors).then_some(range)
 5454                                        },
 5455                                    ),
 5456                                );
 5457                            }
 5458                        }
 5459                        ranges
 5460                    }))
 5461                })
 5462                .log_err()
 5463            else {
 5464                return;
 5465            };
 5466            let matches = matches_task.await;
 5467            editor
 5468                .update_in(cx, |editor, _, cx| {
 5469                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5470                    if !matches.is_empty() {
 5471                        editor.highlight_background::<SelectedTextHighlight>(
 5472                            &matches,
 5473                            |theme| theme.editor_document_highlight_bracket_background,
 5474                            cx,
 5475                        )
 5476                    }
 5477                })
 5478                .log_err();
 5479        }));
 5480    }
 5481
 5482    pub fn refresh_inline_completion(
 5483        &mut self,
 5484        debounce: bool,
 5485        user_requested: bool,
 5486        window: &mut Window,
 5487        cx: &mut Context<Self>,
 5488    ) -> Option<()> {
 5489        let provider = self.edit_prediction_provider()?;
 5490        let cursor = self.selections.newest_anchor().head();
 5491        let (buffer, cursor_buffer_position) =
 5492            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5493
 5494        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 5495            self.discard_inline_completion(false, cx);
 5496            return None;
 5497        }
 5498
 5499        if !user_requested
 5500            && (!self.should_show_edit_predictions()
 5501                || !self.is_focused(window)
 5502                || buffer.read(cx).is_empty())
 5503        {
 5504            self.discard_inline_completion(false, cx);
 5505            return None;
 5506        }
 5507
 5508        self.update_visible_inline_completion(window, cx);
 5509        provider.refresh(
 5510            self.project.clone(),
 5511            buffer,
 5512            cursor_buffer_position,
 5513            debounce,
 5514            cx,
 5515        );
 5516        Some(())
 5517    }
 5518
 5519    fn show_edit_predictions_in_menu(&self) -> bool {
 5520        match self.edit_prediction_settings {
 5521            EditPredictionSettings::Disabled => false,
 5522            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 5523        }
 5524    }
 5525
 5526    pub fn edit_predictions_enabled(&self) -> bool {
 5527        match self.edit_prediction_settings {
 5528            EditPredictionSettings::Disabled => false,
 5529            EditPredictionSettings::Enabled { .. } => true,
 5530        }
 5531    }
 5532
 5533    fn edit_prediction_requires_modifier(&self) -> bool {
 5534        match self.edit_prediction_settings {
 5535            EditPredictionSettings::Disabled => false,
 5536            EditPredictionSettings::Enabled {
 5537                preview_requires_modifier,
 5538                ..
 5539            } => preview_requires_modifier,
 5540        }
 5541    }
 5542
 5543    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 5544        if self.edit_prediction_provider.is_none() {
 5545            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5546        } else {
 5547            let selection = self.selections.newest_anchor();
 5548            let cursor = selection.head();
 5549
 5550            if let Some((buffer, cursor_buffer_position)) =
 5551                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5552            {
 5553                self.edit_prediction_settings =
 5554                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5555            }
 5556        }
 5557    }
 5558
 5559    fn edit_prediction_settings_at_position(
 5560        &self,
 5561        buffer: &Entity<Buffer>,
 5562        buffer_position: language::Anchor,
 5563        cx: &App,
 5564    ) -> EditPredictionSettings {
 5565        if !self.mode.is_full()
 5566            || !self.show_inline_completions_override.unwrap_or(true)
 5567            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 5568        {
 5569            return EditPredictionSettings::Disabled;
 5570        }
 5571
 5572        let buffer = buffer.read(cx);
 5573
 5574        let file = buffer.file();
 5575
 5576        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 5577            return EditPredictionSettings::Disabled;
 5578        };
 5579
 5580        let by_provider = matches!(
 5581            self.menu_inline_completions_policy,
 5582            MenuInlineCompletionsPolicy::ByProvider
 5583        );
 5584
 5585        let show_in_menu = by_provider
 5586            && self
 5587                .edit_prediction_provider
 5588                .as_ref()
 5589                .map_or(false, |provider| {
 5590                    provider.provider.show_completions_in_menu()
 5591                });
 5592
 5593        let preview_requires_modifier =
 5594            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 5595
 5596        EditPredictionSettings::Enabled {
 5597            show_in_menu,
 5598            preview_requires_modifier,
 5599        }
 5600    }
 5601
 5602    fn should_show_edit_predictions(&self) -> bool {
 5603        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 5604    }
 5605
 5606    pub fn edit_prediction_preview_is_active(&self) -> bool {
 5607        matches!(
 5608            self.edit_prediction_preview,
 5609            EditPredictionPreview::Active { .. }
 5610        )
 5611    }
 5612
 5613    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 5614        let cursor = self.selections.newest_anchor().head();
 5615        if let Some((buffer, cursor_position)) =
 5616            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5617        {
 5618            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 5619        } else {
 5620            false
 5621        }
 5622    }
 5623
 5624    fn edit_predictions_enabled_in_buffer(
 5625        &self,
 5626        buffer: &Entity<Buffer>,
 5627        buffer_position: language::Anchor,
 5628        cx: &App,
 5629    ) -> bool {
 5630        maybe!({
 5631            if self.read_only(cx) {
 5632                return Some(false);
 5633            }
 5634            let provider = self.edit_prediction_provider()?;
 5635            if !provider.is_enabled(&buffer, buffer_position, cx) {
 5636                return Some(false);
 5637            }
 5638            let buffer = buffer.read(cx);
 5639            let Some(file) = buffer.file() else {
 5640                return Some(true);
 5641            };
 5642            let settings = all_language_settings(Some(file), cx);
 5643            Some(settings.edit_predictions_enabled_for_file(file, cx))
 5644        })
 5645        .unwrap_or(false)
 5646    }
 5647
 5648    fn cycle_inline_completion(
 5649        &mut self,
 5650        direction: Direction,
 5651        window: &mut Window,
 5652        cx: &mut Context<Self>,
 5653    ) -> Option<()> {
 5654        let provider = self.edit_prediction_provider()?;
 5655        let cursor = self.selections.newest_anchor().head();
 5656        let (buffer, cursor_buffer_position) =
 5657            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5658        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 5659            return None;
 5660        }
 5661
 5662        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5663        self.update_visible_inline_completion(window, cx);
 5664
 5665        Some(())
 5666    }
 5667
 5668    pub fn show_inline_completion(
 5669        &mut self,
 5670        _: &ShowEditPrediction,
 5671        window: &mut Window,
 5672        cx: &mut Context<Self>,
 5673    ) {
 5674        if !self.has_active_inline_completion() {
 5675            self.refresh_inline_completion(false, true, window, cx);
 5676            return;
 5677        }
 5678
 5679        self.update_visible_inline_completion(window, cx);
 5680    }
 5681
 5682    pub fn display_cursor_names(
 5683        &mut self,
 5684        _: &DisplayCursorNames,
 5685        window: &mut Window,
 5686        cx: &mut Context<Self>,
 5687    ) {
 5688        self.show_cursor_names(window, cx);
 5689    }
 5690
 5691    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5692        self.show_cursor_names = true;
 5693        cx.notify();
 5694        cx.spawn_in(window, async move |this, cx| {
 5695            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5696            this.update(cx, |this, cx| {
 5697                this.show_cursor_names = false;
 5698                cx.notify()
 5699            })
 5700            .ok()
 5701        })
 5702        .detach();
 5703    }
 5704
 5705    pub fn next_edit_prediction(
 5706        &mut self,
 5707        _: &NextEditPrediction,
 5708        window: &mut Window,
 5709        cx: &mut Context<Self>,
 5710    ) {
 5711        if self.has_active_inline_completion() {
 5712            self.cycle_inline_completion(Direction::Next, window, cx);
 5713        } else {
 5714            let is_copilot_disabled = self
 5715                .refresh_inline_completion(false, true, window, cx)
 5716                .is_none();
 5717            if is_copilot_disabled {
 5718                cx.propagate();
 5719            }
 5720        }
 5721    }
 5722
 5723    pub fn previous_edit_prediction(
 5724        &mut self,
 5725        _: &PreviousEditPrediction,
 5726        window: &mut Window,
 5727        cx: &mut Context<Self>,
 5728    ) {
 5729        if self.has_active_inline_completion() {
 5730            self.cycle_inline_completion(Direction::Prev, window, cx);
 5731        } else {
 5732            let is_copilot_disabled = self
 5733                .refresh_inline_completion(false, true, window, cx)
 5734                .is_none();
 5735            if is_copilot_disabled {
 5736                cx.propagate();
 5737            }
 5738        }
 5739    }
 5740
 5741    pub fn accept_edit_prediction(
 5742        &mut self,
 5743        _: &AcceptEditPrediction,
 5744        window: &mut Window,
 5745        cx: &mut Context<Self>,
 5746    ) {
 5747        if self.show_edit_predictions_in_menu() {
 5748            self.hide_context_menu(window, cx);
 5749        }
 5750
 5751        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5752            return;
 5753        };
 5754
 5755        self.report_inline_completion_event(
 5756            active_inline_completion.completion_id.clone(),
 5757            true,
 5758            cx,
 5759        );
 5760
 5761        match &active_inline_completion.completion {
 5762            InlineCompletion::Move { target, .. } => {
 5763                let target = *target;
 5764
 5765                if let Some(position_map) = &self.last_position_map {
 5766                    if position_map
 5767                        .visible_row_range
 5768                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5769                        || !self.edit_prediction_requires_modifier()
 5770                    {
 5771                        self.unfold_ranges(&[target..target], true, false, cx);
 5772                        // Note that this is also done in vim's handler of the Tab action.
 5773                        self.change_selections(
 5774                            Some(Autoscroll::newest()),
 5775                            window,
 5776                            cx,
 5777                            |selections| {
 5778                                selections.select_anchor_ranges([target..target]);
 5779                            },
 5780                        );
 5781                        self.clear_row_highlights::<EditPredictionPreview>();
 5782
 5783                        self.edit_prediction_preview
 5784                            .set_previous_scroll_position(None);
 5785                    } else {
 5786                        self.edit_prediction_preview
 5787                            .set_previous_scroll_position(Some(
 5788                                position_map.snapshot.scroll_anchor,
 5789                            ));
 5790
 5791                        self.highlight_rows::<EditPredictionPreview>(
 5792                            target..target,
 5793                            cx.theme().colors().editor_highlighted_line_background,
 5794                            true,
 5795                            cx,
 5796                        );
 5797                        self.request_autoscroll(Autoscroll::fit(), cx);
 5798                    }
 5799                }
 5800            }
 5801            InlineCompletion::Edit { edits, .. } => {
 5802                if let Some(provider) = self.edit_prediction_provider() {
 5803                    provider.accept(cx);
 5804                }
 5805
 5806                let snapshot = self.buffer.read(cx).snapshot(cx);
 5807                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5808
 5809                self.buffer.update(cx, |buffer, cx| {
 5810                    buffer.edit(edits.iter().cloned(), None, cx)
 5811                });
 5812
 5813                self.change_selections(None, window, cx, |s| {
 5814                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5815                });
 5816
 5817                self.update_visible_inline_completion(window, cx);
 5818                if self.active_inline_completion.is_none() {
 5819                    self.refresh_inline_completion(true, true, window, cx);
 5820                }
 5821
 5822                cx.notify();
 5823            }
 5824        }
 5825
 5826        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 5827    }
 5828
 5829    pub fn accept_partial_inline_completion(
 5830        &mut self,
 5831        _: &AcceptPartialEditPrediction,
 5832        window: &mut Window,
 5833        cx: &mut Context<Self>,
 5834    ) {
 5835        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5836            return;
 5837        };
 5838        if self.selections.count() != 1 {
 5839            return;
 5840        }
 5841
 5842        self.report_inline_completion_event(
 5843            active_inline_completion.completion_id.clone(),
 5844            true,
 5845            cx,
 5846        );
 5847
 5848        match &active_inline_completion.completion {
 5849            InlineCompletion::Move { target, .. } => {
 5850                let target = *target;
 5851                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5852                    selections.select_anchor_ranges([target..target]);
 5853                });
 5854            }
 5855            InlineCompletion::Edit { edits, .. } => {
 5856                // Find an insertion that starts at the cursor position.
 5857                let snapshot = self.buffer.read(cx).snapshot(cx);
 5858                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5859                let insertion = edits.iter().find_map(|(range, text)| {
 5860                    let range = range.to_offset(&snapshot);
 5861                    if range.is_empty() && range.start == cursor_offset {
 5862                        Some(text)
 5863                    } else {
 5864                        None
 5865                    }
 5866                });
 5867
 5868                if let Some(text) = insertion {
 5869                    let mut partial_completion = text
 5870                        .chars()
 5871                        .by_ref()
 5872                        .take_while(|c| c.is_alphabetic())
 5873                        .collect::<String>();
 5874                    if partial_completion.is_empty() {
 5875                        partial_completion = text
 5876                            .chars()
 5877                            .by_ref()
 5878                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5879                            .collect::<String>();
 5880                    }
 5881
 5882                    cx.emit(EditorEvent::InputHandled {
 5883                        utf16_range_to_replace: None,
 5884                        text: partial_completion.clone().into(),
 5885                    });
 5886
 5887                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5888
 5889                    self.refresh_inline_completion(true, true, window, cx);
 5890                    cx.notify();
 5891                } else {
 5892                    self.accept_edit_prediction(&Default::default(), window, cx);
 5893                }
 5894            }
 5895        }
 5896    }
 5897
 5898    fn discard_inline_completion(
 5899        &mut self,
 5900        should_report_inline_completion_event: bool,
 5901        cx: &mut Context<Self>,
 5902    ) -> bool {
 5903        if should_report_inline_completion_event {
 5904            let completion_id = self
 5905                .active_inline_completion
 5906                .as_ref()
 5907                .and_then(|active_completion| active_completion.completion_id.clone());
 5908
 5909            self.report_inline_completion_event(completion_id, false, cx);
 5910        }
 5911
 5912        if let Some(provider) = self.edit_prediction_provider() {
 5913            provider.discard(cx);
 5914        }
 5915
 5916        self.take_active_inline_completion(cx)
 5917    }
 5918
 5919    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5920        let Some(provider) = self.edit_prediction_provider() else {
 5921            return;
 5922        };
 5923
 5924        let Some((_, buffer, _)) = self
 5925            .buffer
 5926            .read(cx)
 5927            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5928        else {
 5929            return;
 5930        };
 5931
 5932        let extension = buffer
 5933            .read(cx)
 5934            .file()
 5935            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5936
 5937        let event_type = match accepted {
 5938            true => "Edit Prediction Accepted",
 5939            false => "Edit Prediction Discarded",
 5940        };
 5941        telemetry::event!(
 5942            event_type,
 5943            provider = provider.name(),
 5944            prediction_id = id,
 5945            suggestion_accepted = accepted,
 5946            file_extension = extension,
 5947        );
 5948    }
 5949
 5950    pub fn has_active_inline_completion(&self) -> bool {
 5951        self.active_inline_completion.is_some()
 5952    }
 5953
 5954    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5955        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5956            return false;
 5957        };
 5958
 5959        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5960        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5961        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5962        true
 5963    }
 5964
 5965    /// Returns true when we're displaying the edit prediction popover below the cursor
 5966    /// like we are not previewing and the LSP autocomplete menu is visible
 5967    /// or we are in `when_holding_modifier` mode.
 5968    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5969        if self.edit_prediction_preview_is_active()
 5970            || !self.show_edit_predictions_in_menu()
 5971            || !self.edit_predictions_enabled()
 5972        {
 5973            return false;
 5974        }
 5975
 5976        if self.has_visible_completions_menu() {
 5977            return true;
 5978        }
 5979
 5980        has_completion && self.edit_prediction_requires_modifier()
 5981    }
 5982
 5983    fn handle_modifiers_changed(
 5984        &mut self,
 5985        modifiers: Modifiers,
 5986        position_map: &PositionMap,
 5987        window: &mut Window,
 5988        cx: &mut Context<Self>,
 5989    ) {
 5990        if self.show_edit_predictions_in_menu() {
 5991            self.update_edit_prediction_preview(&modifiers, window, cx);
 5992        }
 5993
 5994        self.update_selection_mode(&modifiers, position_map, window, cx);
 5995
 5996        let mouse_position = window.mouse_position();
 5997        if !position_map.text_hitbox.is_hovered(window) {
 5998            return;
 5999        }
 6000
 6001        self.update_hovered_link(
 6002            position_map.point_for_position(mouse_position),
 6003            &position_map.snapshot,
 6004            modifiers,
 6005            window,
 6006            cx,
 6007        )
 6008    }
 6009
 6010    fn update_selection_mode(
 6011        &mut self,
 6012        modifiers: &Modifiers,
 6013        position_map: &PositionMap,
 6014        window: &mut Window,
 6015        cx: &mut Context<Self>,
 6016    ) {
 6017        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 6018            return;
 6019        }
 6020
 6021        let mouse_position = window.mouse_position();
 6022        let point_for_position = position_map.point_for_position(mouse_position);
 6023        let position = point_for_position.previous_valid;
 6024
 6025        self.select(
 6026            SelectPhase::BeginColumnar {
 6027                position,
 6028                reset: false,
 6029                goal_column: point_for_position.exact_unclipped.column(),
 6030            },
 6031            window,
 6032            cx,
 6033        );
 6034    }
 6035
 6036    fn update_edit_prediction_preview(
 6037        &mut self,
 6038        modifiers: &Modifiers,
 6039        window: &mut Window,
 6040        cx: &mut Context<Self>,
 6041    ) {
 6042        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 6043        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 6044            return;
 6045        };
 6046
 6047        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 6048            if matches!(
 6049                self.edit_prediction_preview,
 6050                EditPredictionPreview::Inactive { .. }
 6051            ) {
 6052                self.edit_prediction_preview = EditPredictionPreview::Active {
 6053                    previous_scroll_position: None,
 6054                    since: Instant::now(),
 6055                };
 6056
 6057                self.update_visible_inline_completion(window, cx);
 6058                cx.notify();
 6059            }
 6060        } else if let EditPredictionPreview::Active {
 6061            previous_scroll_position,
 6062            since,
 6063        } = self.edit_prediction_preview
 6064        {
 6065            if let (Some(previous_scroll_position), Some(position_map)) =
 6066                (previous_scroll_position, self.last_position_map.as_ref())
 6067            {
 6068                self.set_scroll_position(
 6069                    previous_scroll_position
 6070                        .scroll_position(&position_map.snapshot.display_snapshot),
 6071                    window,
 6072                    cx,
 6073                );
 6074            }
 6075
 6076            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 6077                released_too_fast: since.elapsed() < Duration::from_millis(200),
 6078            };
 6079            self.clear_row_highlights::<EditPredictionPreview>();
 6080            self.update_visible_inline_completion(window, cx);
 6081            cx.notify();
 6082        }
 6083    }
 6084
 6085    fn update_visible_inline_completion(
 6086        &mut self,
 6087        _window: &mut Window,
 6088        cx: &mut Context<Self>,
 6089    ) -> Option<()> {
 6090        let selection = self.selections.newest_anchor();
 6091        let cursor = selection.head();
 6092        let multibuffer = self.buffer.read(cx).snapshot(cx);
 6093        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 6094        let excerpt_id = cursor.excerpt_id;
 6095
 6096        let show_in_menu = self.show_edit_predictions_in_menu();
 6097        let completions_menu_has_precedence = !show_in_menu
 6098            && (self.context_menu.borrow().is_some()
 6099                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 6100
 6101        if completions_menu_has_precedence
 6102            || !offset_selection.is_empty()
 6103            || self
 6104                .active_inline_completion
 6105                .as_ref()
 6106                .map_or(false, |completion| {
 6107                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 6108                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 6109                    !invalidation_range.contains(&offset_selection.head())
 6110                })
 6111        {
 6112            self.discard_inline_completion(false, cx);
 6113            return None;
 6114        }
 6115
 6116        self.take_active_inline_completion(cx);
 6117        let Some(provider) = self.edit_prediction_provider() else {
 6118            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 6119            return None;
 6120        };
 6121
 6122        let (buffer, cursor_buffer_position) =
 6123            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 6124
 6125        self.edit_prediction_settings =
 6126            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 6127
 6128        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 6129
 6130        if self.edit_prediction_indent_conflict {
 6131            let cursor_point = cursor.to_point(&multibuffer);
 6132
 6133            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 6134
 6135            if let Some((_, indent)) = indents.iter().next() {
 6136                if indent.len == cursor_point.column {
 6137                    self.edit_prediction_indent_conflict = false;
 6138                }
 6139            }
 6140        }
 6141
 6142        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 6143        let edits = inline_completion
 6144            .edits
 6145            .into_iter()
 6146            .flat_map(|(range, new_text)| {
 6147                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 6148                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 6149                Some((start..end, new_text))
 6150            })
 6151            .collect::<Vec<_>>();
 6152        if edits.is_empty() {
 6153            return None;
 6154        }
 6155
 6156        let first_edit_start = edits.first().unwrap().0.start;
 6157        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 6158        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 6159
 6160        let last_edit_end = edits.last().unwrap().0.end;
 6161        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 6162        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 6163
 6164        let cursor_row = cursor.to_point(&multibuffer).row;
 6165
 6166        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 6167
 6168        let mut inlay_ids = Vec::new();
 6169        let invalidation_row_range;
 6170        let move_invalidation_row_range = if cursor_row < edit_start_row {
 6171            Some(cursor_row..edit_end_row)
 6172        } else if cursor_row > edit_end_row {
 6173            Some(edit_start_row..cursor_row)
 6174        } else {
 6175            None
 6176        };
 6177        let is_move =
 6178            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 6179        let completion = if is_move {
 6180            invalidation_row_range =
 6181                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 6182            let target = first_edit_start;
 6183            InlineCompletion::Move { target, snapshot }
 6184        } else {
 6185            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 6186                && !self.inline_completions_hidden_for_vim_mode;
 6187
 6188            if show_completions_in_buffer {
 6189                if edits
 6190                    .iter()
 6191                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 6192                {
 6193                    let mut inlays = Vec::new();
 6194                    for (range, new_text) in &edits {
 6195                        let inlay = Inlay::inline_completion(
 6196                            post_inc(&mut self.next_inlay_id),
 6197                            range.start,
 6198                            new_text.as_str(),
 6199                        );
 6200                        inlay_ids.push(inlay.id);
 6201                        inlays.push(inlay);
 6202                    }
 6203
 6204                    self.splice_inlays(&[], inlays, cx);
 6205                } else {
 6206                    let background_color = cx.theme().status().deleted_background;
 6207                    self.highlight_text::<InlineCompletionHighlight>(
 6208                        edits.iter().map(|(range, _)| range.clone()).collect(),
 6209                        HighlightStyle {
 6210                            background_color: Some(background_color),
 6211                            ..Default::default()
 6212                        },
 6213                        cx,
 6214                    );
 6215                }
 6216            }
 6217
 6218            invalidation_row_range = edit_start_row..edit_end_row;
 6219
 6220            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 6221                if provider.show_tab_accept_marker() {
 6222                    EditDisplayMode::TabAccept
 6223                } else {
 6224                    EditDisplayMode::Inline
 6225                }
 6226            } else {
 6227                EditDisplayMode::DiffPopover
 6228            };
 6229
 6230            InlineCompletion::Edit {
 6231                edits,
 6232                edit_preview: inline_completion.edit_preview,
 6233                display_mode,
 6234                snapshot,
 6235            }
 6236        };
 6237
 6238        let invalidation_range = multibuffer
 6239            .anchor_before(Point::new(invalidation_row_range.start, 0))
 6240            ..multibuffer.anchor_after(Point::new(
 6241                invalidation_row_range.end,
 6242                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 6243            ));
 6244
 6245        self.stale_inline_completion_in_menu = None;
 6246        self.active_inline_completion = Some(InlineCompletionState {
 6247            inlay_ids,
 6248            completion,
 6249            completion_id: inline_completion.id,
 6250            invalidation_range,
 6251        });
 6252
 6253        cx.notify();
 6254
 6255        Some(())
 6256    }
 6257
 6258    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 6259        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 6260    }
 6261
 6262    fn render_code_actions_indicator(
 6263        &self,
 6264        _style: &EditorStyle,
 6265        row: DisplayRow,
 6266        is_active: bool,
 6267        breakpoint: Option<&(Anchor, Breakpoint)>,
 6268        cx: &mut Context<Self>,
 6269    ) -> Option<IconButton> {
 6270        let color = Color::Muted;
 6271        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6272        let show_tooltip = !self.context_menu_visible();
 6273
 6274        if self.available_code_actions.is_some() {
 6275            Some(
 6276                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 6277                    .shape(ui::IconButtonShape::Square)
 6278                    .icon_size(IconSize::XSmall)
 6279                    .icon_color(color)
 6280                    .toggle_state(is_active)
 6281                    .when(show_tooltip, |this| {
 6282                        this.tooltip({
 6283                            let focus_handle = self.focus_handle.clone();
 6284                            move |window, cx| {
 6285                                Tooltip::for_action_in(
 6286                                    "Toggle Code Actions",
 6287                                    &ToggleCodeActions {
 6288                                        deployed_from_indicator: None,
 6289                                    },
 6290                                    &focus_handle,
 6291                                    window,
 6292                                    cx,
 6293                                )
 6294                            }
 6295                        })
 6296                    })
 6297                    .on_click(cx.listener(move |editor, _e, window, cx| {
 6298                        window.focus(&editor.focus_handle(cx));
 6299                        editor.toggle_code_actions(
 6300                            &ToggleCodeActions {
 6301                                deployed_from_indicator: Some(row),
 6302                            },
 6303                            window,
 6304                            cx,
 6305                        );
 6306                    }))
 6307                    .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6308                        editor.set_breakpoint_context_menu(
 6309                            row,
 6310                            position,
 6311                            event.down.position,
 6312                            window,
 6313                            cx,
 6314                        );
 6315                    })),
 6316            )
 6317        } else {
 6318            None
 6319        }
 6320    }
 6321
 6322    fn clear_tasks(&mut self) {
 6323        self.tasks.clear()
 6324    }
 6325
 6326    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 6327        if self.tasks.insert(key, value).is_some() {
 6328            // This case should hopefully be rare, but just in case...
 6329            log::error!(
 6330                "multiple different run targets found on a single line, only the last target will be rendered"
 6331            )
 6332        }
 6333    }
 6334
 6335    /// Get all display points of breakpoints that will be rendered within editor
 6336    ///
 6337    /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
 6338    /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
 6339    /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
 6340    fn active_breakpoints(
 6341        &self,
 6342        range: Range<DisplayRow>,
 6343        window: &mut Window,
 6344        cx: &mut Context<Self>,
 6345    ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
 6346        let mut breakpoint_display_points = HashMap::default();
 6347
 6348        let Some(breakpoint_store) = self.breakpoint_store.clone() else {
 6349            return breakpoint_display_points;
 6350        };
 6351
 6352        let snapshot = self.snapshot(window, cx);
 6353
 6354        let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
 6355        let Some(project) = self.project.as_ref() else {
 6356            return breakpoint_display_points;
 6357        };
 6358
 6359        let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
 6360            ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
 6361
 6362        for (buffer_snapshot, range, excerpt_id) in
 6363            multi_buffer_snapshot.range_to_buffer_ranges(range)
 6364        {
 6365            let Some(buffer) = project.read_with(cx, |this, cx| {
 6366                this.buffer_for_id(buffer_snapshot.remote_id(), cx)
 6367            }) else {
 6368                continue;
 6369            };
 6370            let breakpoints = breakpoint_store.read(cx).breakpoints(
 6371                &buffer,
 6372                Some(
 6373                    buffer_snapshot.anchor_before(range.start)
 6374                        ..buffer_snapshot.anchor_after(range.end),
 6375                ),
 6376                buffer_snapshot,
 6377                cx,
 6378            );
 6379            for (anchor, breakpoint) in breakpoints {
 6380                let multi_buffer_anchor =
 6381                    Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
 6382                let position = multi_buffer_anchor
 6383                    .to_point(&multi_buffer_snapshot)
 6384                    .to_display_point(&snapshot);
 6385
 6386                breakpoint_display_points
 6387                    .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
 6388            }
 6389        }
 6390
 6391        breakpoint_display_points
 6392    }
 6393
 6394    fn breakpoint_context_menu(
 6395        &self,
 6396        anchor: Anchor,
 6397        window: &mut Window,
 6398        cx: &mut Context<Self>,
 6399    ) -> Entity<ui::ContextMenu> {
 6400        let weak_editor = cx.weak_entity();
 6401        let focus_handle = self.focus_handle(cx);
 6402
 6403        let row = self
 6404            .buffer
 6405            .read(cx)
 6406            .snapshot(cx)
 6407            .summary_for_anchor::<Point>(&anchor)
 6408            .row;
 6409
 6410        let breakpoint = self
 6411            .breakpoint_at_row(row, window, cx)
 6412            .map(|(anchor, bp)| (anchor, Arc::from(bp)));
 6413
 6414        let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
 6415            "Edit Log Breakpoint"
 6416        } else {
 6417            "Set Log Breakpoint"
 6418        };
 6419
 6420        let condition_breakpoint_msg = if breakpoint
 6421            .as_ref()
 6422            .is_some_and(|bp| bp.1.condition.is_some())
 6423        {
 6424            "Edit Condition Breakpoint"
 6425        } else {
 6426            "Set Condition Breakpoint"
 6427        };
 6428
 6429        let hit_condition_breakpoint_msg = if breakpoint
 6430            .as_ref()
 6431            .is_some_and(|bp| bp.1.hit_condition.is_some())
 6432        {
 6433            "Edit Hit Condition Breakpoint"
 6434        } else {
 6435            "Set Hit Condition Breakpoint"
 6436        };
 6437
 6438        let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
 6439            "Unset Breakpoint"
 6440        } else {
 6441            "Set Breakpoint"
 6442        };
 6443
 6444        let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
 6445            BreakpointState::Enabled => Some("Disable"),
 6446            BreakpointState::Disabled => Some("Enable"),
 6447        });
 6448
 6449        let (anchor, breakpoint) =
 6450            breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
 6451
 6452        ui::ContextMenu::build(window, cx, |menu, _, _cx| {
 6453            menu.on_blur_subscription(Subscription::new(|| {}))
 6454                .context(focus_handle)
 6455                .when_some(toggle_state_msg, |this, msg| {
 6456                    this.entry(msg, None, {
 6457                        let weak_editor = weak_editor.clone();
 6458                        let breakpoint = breakpoint.clone();
 6459                        move |_window, cx| {
 6460                            weak_editor
 6461                                .update(cx, |this, cx| {
 6462                                    this.edit_breakpoint_at_anchor(
 6463                                        anchor,
 6464                                        breakpoint.as_ref().clone(),
 6465                                        BreakpointEditAction::InvertState,
 6466                                        cx,
 6467                                    );
 6468                                })
 6469                                .log_err();
 6470                        }
 6471                    })
 6472                })
 6473                .entry(set_breakpoint_msg, None, {
 6474                    let weak_editor = weak_editor.clone();
 6475                    let breakpoint = breakpoint.clone();
 6476                    move |_window, cx| {
 6477                        weak_editor
 6478                            .update(cx, |this, cx| {
 6479                                this.edit_breakpoint_at_anchor(
 6480                                    anchor,
 6481                                    breakpoint.as_ref().clone(),
 6482                                    BreakpointEditAction::Toggle,
 6483                                    cx,
 6484                                );
 6485                            })
 6486                            .log_err();
 6487                    }
 6488                })
 6489                .entry(log_breakpoint_msg, None, {
 6490                    let breakpoint = breakpoint.clone();
 6491                    let weak_editor = weak_editor.clone();
 6492                    move |window, cx| {
 6493                        weak_editor
 6494                            .update(cx, |this, cx| {
 6495                                this.add_edit_breakpoint_block(
 6496                                    anchor,
 6497                                    breakpoint.as_ref(),
 6498                                    BreakpointPromptEditAction::Log,
 6499                                    window,
 6500                                    cx,
 6501                                );
 6502                            })
 6503                            .log_err();
 6504                    }
 6505                })
 6506                .entry(condition_breakpoint_msg, None, {
 6507                    let breakpoint = breakpoint.clone();
 6508                    let weak_editor = weak_editor.clone();
 6509                    move |window, cx| {
 6510                        weak_editor
 6511                            .update(cx, |this, cx| {
 6512                                this.add_edit_breakpoint_block(
 6513                                    anchor,
 6514                                    breakpoint.as_ref(),
 6515                                    BreakpointPromptEditAction::Condition,
 6516                                    window,
 6517                                    cx,
 6518                                );
 6519                            })
 6520                            .log_err();
 6521                    }
 6522                })
 6523                .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
 6524                    weak_editor
 6525                        .update(cx, |this, cx| {
 6526                            this.add_edit_breakpoint_block(
 6527                                anchor,
 6528                                breakpoint.as_ref(),
 6529                                BreakpointPromptEditAction::HitCondition,
 6530                                window,
 6531                                cx,
 6532                            );
 6533                        })
 6534                        .log_err();
 6535                })
 6536        })
 6537    }
 6538
 6539    fn render_breakpoint(
 6540        &self,
 6541        position: Anchor,
 6542        row: DisplayRow,
 6543        breakpoint: &Breakpoint,
 6544        cx: &mut Context<Self>,
 6545    ) -> IconButton {
 6546        let (color, icon) = {
 6547            let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
 6548                (false, false) => ui::IconName::DebugBreakpoint,
 6549                (true, false) => ui::IconName::DebugLogBreakpoint,
 6550                (false, true) => ui::IconName::DebugDisabledBreakpoint,
 6551                (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
 6552            };
 6553
 6554            let color = if self
 6555                .gutter_breakpoint_indicator
 6556                .0
 6557                .is_some_and(|(point, is_visible)| is_visible && point.row() == row)
 6558            {
 6559                Color::Hint
 6560            } else {
 6561                Color::Debugger
 6562            };
 6563
 6564            (color, icon)
 6565        };
 6566
 6567        let breakpoint = Arc::from(breakpoint.clone());
 6568
 6569        IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
 6570            .icon_size(IconSize::XSmall)
 6571            .size(ui::ButtonSize::None)
 6572            .icon_color(color)
 6573            .style(ButtonStyle::Transparent)
 6574            .on_click(cx.listener({
 6575                let breakpoint = breakpoint.clone();
 6576
 6577                move |editor, event: &ClickEvent, window, cx| {
 6578                    let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
 6579                        BreakpointEditAction::InvertState
 6580                    } else {
 6581                        BreakpointEditAction::Toggle
 6582                    };
 6583
 6584                    window.focus(&editor.focus_handle(cx));
 6585                    editor.edit_breakpoint_at_anchor(
 6586                        position,
 6587                        breakpoint.as_ref().clone(),
 6588                        edit_action,
 6589                        cx,
 6590                    );
 6591                }
 6592            }))
 6593            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6594                editor.set_breakpoint_context_menu(
 6595                    row,
 6596                    Some(position),
 6597                    event.down.position,
 6598                    window,
 6599                    cx,
 6600                );
 6601            }))
 6602    }
 6603
 6604    fn build_tasks_context(
 6605        project: &Entity<Project>,
 6606        buffer: &Entity<Buffer>,
 6607        buffer_row: u32,
 6608        tasks: &Arc<RunnableTasks>,
 6609        cx: &mut Context<Self>,
 6610    ) -> Task<Option<task::TaskContext>> {
 6611        let position = Point::new(buffer_row, tasks.column);
 6612        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 6613        let location = Location {
 6614            buffer: buffer.clone(),
 6615            range: range_start..range_start,
 6616        };
 6617        // Fill in the environmental variables from the tree-sitter captures
 6618        let mut captured_task_variables = TaskVariables::default();
 6619        for (capture_name, value) in tasks.extra_variables.clone() {
 6620            captured_task_variables.insert(
 6621                task::VariableName::Custom(capture_name.into()),
 6622                value.clone(),
 6623            );
 6624        }
 6625        project.update(cx, |project, cx| {
 6626            project.task_store().update(cx, |task_store, cx| {
 6627                task_store.task_context_for_location(captured_task_variables, location, cx)
 6628            })
 6629        })
 6630    }
 6631
 6632    pub fn spawn_nearest_task(
 6633        &mut self,
 6634        action: &SpawnNearestTask,
 6635        window: &mut Window,
 6636        cx: &mut Context<Self>,
 6637    ) {
 6638        let Some((workspace, _)) = self.workspace.clone() else {
 6639            return;
 6640        };
 6641        let Some(project) = self.project.clone() else {
 6642            return;
 6643        };
 6644
 6645        // Try to find a closest, enclosing node using tree-sitter that has a
 6646        // task
 6647        let Some((buffer, buffer_row, tasks)) = self
 6648            .find_enclosing_node_task(cx)
 6649            // Or find the task that's closest in row-distance.
 6650            .or_else(|| self.find_closest_task(cx))
 6651        else {
 6652            return;
 6653        };
 6654
 6655        let reveal_strategy = action.reveal;
 6656        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 6657        cx.spawn_in(window, async move |_, cx| {
 6658            let context = task_context.await?;
 6659            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 6660
 6661            let resolved = resolved_task.resolved.as_mut()?;
 6662            resolved.reveal = reveal_strategy;
 6663
 6664            workspace
 6665                .update(cx, |workspace, cx| {
 6666                    workspace::tasks::schedule_resolved_task(
 6667                        workspace,
 6668                        task_source_kind,
 6669                        resolved_task,
 6670                        false,
 6671                        cx,
 6672                    );
 6673                })
 6674                .ok()
 6675        })
 6676        .detach();
 6677    }
 6678
 6679    fn find_closest_task(
 6680        &mut self,
 6681        cx: &mut Context<Self>,
 6682    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6683        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 6684
 6685        let ((buffer_id, row), tasks) = self
 6686            .tasks
 6687            .iter()
 6688            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 6689
 6690        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 6691        let tasks = Arc::new(tasks.to_owned());
 6692        Some((buffer, *row, tasks))
 6693    }
 6694
 6695    fn find_enclosing_node_task(
 6696        &mut self,
 6697        cx: &mut Context<Self>,
 6698    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6699        let snapshot = self.buffer.read(cx).snapshot(cx);
 6700        let offset = self.selections.newest::<usize>(cx).head();
 6701        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 6702        let buffer_id = excerpt.buffer().remote_id();
 6703
 6704        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 6705        let mut cursor = layer.node().walk();
 6706
 6707        while cursor.goto_first_child_for_byte(offset).is_some() {
 6708            if cursor.node().end_byte() == offset {
 6709                cursor.goto_next_sibling();
 6710            }
 6711        }
 6712
 6713        // Ascend to the smallest ancestor that contains the range and has a task.
 6714        loop {
 6715            let node = cursor.node();
 6716            let node_range = node.byte_range();
 6717            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 6718
 6719            // Check if this node contains our offset
 6720            if node_range.start <= offset && node_range.end >= offset {
 6721                // If it contains offset, check for task
 6722                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 6723                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 6724                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 6725                }
 6726            }
 6727
 6728            if !cursor.goto_parent() {
 6729                break;
 6730            }
 6731        }
 6732        None
 6733    }
 6734
 6735    fn render_run_indicator(
 6736        &self,
 6737        _style: &EditorStyle,
 6738        is_active: bool,
 6739        row: DisplayRow,
 6740        breakpoint: Option<(Anchor, Breakpoint)>,
 6741        cx: &mut Context<Self>,
 6742    ) -> IconButton {
 6743        let color = Color::Muted;
 6744        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6745
 6746        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 6747            .shape(ui::IconButtonShape::Square)
 6748            .icon_size(IconSize::XSmall)
 6749            .icon_color(color)
 6750            .toggle_state(is_active)
 6751            .on_click(cx.listener(move |editor, _e, window, cx| {
 6752                window.focus(&editor.focus_handle(cx));
 6753                editor.toggle_code_actions(
 6754                    &ToggleCodeActions {
 6755                        deployed_from_indicator: Some(row),
 6756                    },
 6757                    window,
 6758                    cx,
 6759                );
 6760            }))
 6761            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6762                editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
 6763            }))
 6764    }
 6765
 6766    pub fn context_menu_visible(&self) -> bool {
 6767        !self.edit_prediction_preview_is_active()
 6768            && self
 6769                .context_menu
 6770                .borrow()
 6771                .as_ref()
 6772                .map_or(false, |menu| menu.visible())
 6773    }
 6774
 6775    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 6776        self.context_menu
 6777            .borrow()
 6778            .as_ref()
 6779            .map(|menu| menu.origin())
 6780    }
 6781
 6782    pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
 6783        self.context_menu_options = Some(options);
 6784    }
 6785
 6786    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 6787    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 6788
 6789    fn render_edit_prediction_popover(
 6790        &mut self,
 6791        text_bounds: &Bounds<Pixels>,
 6792        content_origin: gpui::Point<Pixels>,
 6793        editor_snapshot: &EditorSnapshot,
 6794        visible_row_range: Range<DisplayRow>,
 6795        scroll_top: f32,
 6796        scroll_bottom: f32,
 6797        line_layouts: &[LineWithInvisibles],
 6798        line_height: Pixels,
 6799        scroll_pixel_position: gpui::Point<Pixels>,
 6800        newest_selection_head: Option<DisplayPoint>,
 6801        editor_width: Pixels,
 6802        style: &EditorStyle,
 6803        window: &mut Window,
 6804        cx: &mut App,
 6805    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6806        let active_inline_completion = self.active_inline_completion.as_ref()?;
 6807
 6808        if self.edit_prediction_visible_in_cursor_popover(true) {
 6809            return None;
 6810        }
 6811
 6812        match &active_inline_completion.completion {
 6813            InlineCompletion::Move { target, .. } => {
 6814                let target_display_point = target.to_display_point(editor_snapshot);
 6815
 6816                if self.edit_prediction_requires_modifier() {
 6817                    if !self.edit_prediction_preview_is_active() {
 6818                        return None;
 6819                    }
 6820
 6821                    self.render_edit_prediction_modifier_jump_popover(
 6822                        text_bounds,
 6823                        content_origin,
 6824                        visible_row_range,
 6825                        line_layouts,
 6826                        line_height,
 6827                        scroll_pixel_position,
 6828                        newest_selection_head,
 6829                        target_display_point,
 6830                        window,
 6831                        cx,
 6832                    )
 6833                } else {
 6834                    self.render_edit_prediction_eager_jump_popover(
 6835                        text_bounds,
 6836                        content_origin,
 6837                        editor_snapshot,
 6838                        visible_row_range,
 6839                        scroll_top,
 6840                        scroll_bottom,
 6841                        line_height,
 6842                        scroll_pixel_position,
 6843                        target_display_point,
 6844                        editor_width,
 6845                        window,
 6846                        cx,
 6847                    )
 6848                }
 6849            }
 6850            InlineCompletion::Edit {
 6851                display_mode: EditDisplayMode::Inline,
 6852                ..
 6853            } => None,
 6854            InlineCompletion::Edit {
 6855                display_mode: EditDisplayMode::TabAccept,
 6856                edits,
 6857                ..
 6858            } => {
 6859                let range = &edits.first()?.0;
 6860                let target_display_point = range.end.to_display_point(editor_snapshot);
 6861
 6862                self.render_edit_prediction_end_of_line_popover(
 6863                    "Accept",
 6864                    editor_snapshot,
 6865                    visible_row_range,
 6866                    target_display_point,
 6867                    line_height,
 6868                    scroll_pixel_position,
 6869                    content_origin,
 6870                    editor_width,
 6871                    window,
 6872                    cx,
 6873                )
 6874            }
 6875            InlineCompletion::Edit {
 6876                edits,
 6877                edit_preview,
 6878                display_mode: EditDisplayMode::DiffPopover,
 6879                snapshot,
 6880            } => self.render_edit_prediction_diff_popover(
 6881                text_bounds,
 6882                content_origin,
 6883                editor_snapshot,
 6884                visible_row_range,
 6885                line_layouts,
 6886                line_height,
 6887                scroll_pixel_position,
 6888                newest_selection_head,
 6889                editor_width,
 6890                style,
 6891                edits,
 6892                edit_preview,
 6893                snapshot,
 6894                window,
 6895                cx,
 6896            ),
 6897        }
 6898    }
 6899
 6900    fn render_edit_prediction_modifier_jump_popover(
 6901        &mut self,
 6902        text_bounds: &Bounds<Pixels>,
 6903        content_origin: gpui::Point<Pixels>,
 6904        visible_row_range: Range<DisplayRow>,
 6905        line_layouts: &[LineWithInvisibles],
 6906        line_height: Pixels,
 6907        scroll_pixel_position: gpui::Point<Pixels>,
 6908        newest_selection_head: Option<DisplayPoint>,
 6909        target_display_point: DisplayPoint,
 6910        window: &mut Window,
 6911        cx: &mut App,
 6912    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6913        let scrolled_content_origin =
 6914            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 6915
 6916        const SCROLL_PADDING_Y: Pixels = px(12.);
 6917
 6918        if target_display_point.row() < visible_row_range.start {
 6919            return self.render_edit_prediction_scroll_popover(
 6920                |_| SCROLL_PADDING_Y,
 6921                IconName::ArrowUp,
 6922                visible_row_range,
 6923                line_layouts,
 6924                newest_selection_head,
 6925                scrolled_content_origin,
 6926                window,
 6927                cx,
 6928            );
 6929        } else if target_display_point.row() >= visible_row_range.end {
 6930            return self.render_edit_prediction_scroll_popover(
 6931                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 6932                IconName::ArrowDown,
 6933                visible_row_range,
 6934                line_layouts,
 6935                newest_selection_head,
 6936                scrolled_content_origin,
 6937                window,
 6938                cx,
 6939            );
 6940        }
 6941
 6942        const POLE_WIDTH: Pixels = px(2.);
 6943
 6944        let line_layout =
 6945            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 6946        let target_column = target_display_point.column() as usize;
 6947
 6948        let target_x = line_layout.x_for_index(target_column);
 6949        let target_y =
 6950            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 6951
 6952        let flag_on_right = target_x < text_bounds.size.width / 2.;
 6953
 6954        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 6955        border_color.l += 0.001;
 6956
 6957        let mut element = v_flex()
 6958            .items_end()
 6959            .when(flag_on_right, |el| el.items_start())
 6960            .child(if flag_on_right {
 6961                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6962                    .rounded_bl(px(0.))
 6963                    .rounded_tl(px(0.))
 6964                    .border_l_2()
 6965                    .border_color(border_color)
 6966            } else {
 6967                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6968                    .rounded_br(px(0.))
 6969                    .rounded_tr(px(0.))
 6970                    .border_r_2()
 6971                    .border_color(border_color)
 6972            })
 6973            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 6974            .into_any();
 6975
 6976        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6977
 6978        let mut origin = scrolled_content_origin + point(target_x, target_y)
 6979            - point(
 6980                if flag_on_right {
 6981                    POLE_WIDTH
 6982                } else {
 6983                    size.width - POLE_WIDTH
 6984                },
 6985                size.height - line_height,
 6986            );
 6987
 6988        origin.x = origin.x.max(content_origin.x);
 6989
 6990        element.prepaint_at(origin, window, cx);
 6991
 6992        Some((element, origin))
 6993    }
 6994
 6995    fn render_edit_prediction_scroll_popover(
 6996        &mut self,
 6997        to_y: impl Fn(Size<Pixels>) -> Pixels,
 6998        scroll_icon: IconName,
 6999        visible_row_range: Range<DisplayRow>,
 7000        line_layouts: &[LineWithInvisibles],
 7001        newest_selection_head: Option<DisplayPoint>,
 7002        scrolled_content_origin: gpui::Point<Pixels>,
 7003        window: &mut Window,
 7004        cx: &mut App,
 7005    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7006        let mut element = self
 7007            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 7008            .into_any();
 7009
 7010        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7011
 7012        let cursor = newest_selection_head?;
 7013        let cursor_row_layout =
 7014            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 7015        let cursor_column = cursor.column() as usize;
 7016
 7017        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 7018
 7019        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 7020
 7021        element.prepaint_at(origin, window, cx);
 7022        Some((element, origin))
 7023    }
 7024
 7025    fn render_edit_prediction_eager_jump_popover(
 7026        &mut self,
 7027        text_bounds: &Bounds<Pixels>,
 7028        content_origin: gpui::Point<Pixels>,
 7029        editor_snapshot: &EditorSnapshot,
 7030        visible_row_range: Range<DisplayRow>,
 7031        scroll_top: f32,
 7032        scroll_bottom: f32,
 7033        line_height: Pixels,
 7034        scroll_pixel_position: gpui::Point<Pixels>,
 7035        target_display_point: DisplayPoint,
 7036        editor_width: Pixels,
 7037        window: &mut Window,
 7038        cx: &mut App,
 7039    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7040        if target_display_point.row().as_f32() < scroll_top {
 7041            let mut element = self
 7042                .render_edit_prediction_line_popover(
 7043                    "Jump to Edit",
 7044                    Some(IconName::ArrowUp),
 7045                    window,
 7046                    cx,
 7047                )?
 7048                .into_any();
 7049
 7050            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7051            let offset = point(
 7052                (text_bounds.size.width - size.width) / 2.,
 7053                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7054            );
 7055
 7056            let origin = text_bounds.origin + offset;
 7057            element.prepaint_at(origin, window, cx);
 7058            Some((element, origin))
 7059        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 7060            let mut element = self
 7061                .render_edit_prediction_line_popover(
 7062                    "Jump to Edit",
 7063                    Some(IconName::ArrowDown),
 7064                    window,
 7065                    cx,
 7066                )?
 7067                .into_any();
 7068
 7069            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7070            let offset = point(
 7071                (text_bounds.size.width - size.width) / 2.,
 7072                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7073            );
 7074
 7075            let origin = text_bounds.origin + offset;
 7076            element.prepaint_at(origin, window, cx);
 7077            Some((element, origin))
 7078        } else {
 7079            self.render_edit_prediction_end_of_line_popover(
 7080                "Jump to Edit",
 7081                editor_snapshot,
 7082                visible_row_range,
 7083                target_display_point,
 7084                line_height,
 7085                scroll_pixel_position,
 7086                content_origin,
 7087                editor_width,
 7088                window,
 7089                cx,
 7090            )
 7091        }
 7092    }
 7093
 7094    fn render_edit_prediction_end_of_line_popover(
 7095        self: &mut Editor,
 7096        label: &'static str,
 7097        editor_snapshot: &EditorSnapshot,
 7098        visible_row_range: Range<DisplayRow>,
 7099        target_display_point: DisplayPoint,
 7100        line_height: Pixels,
 7101        scroll_pixel_position: gpui::Point<Pixels>,
 7102        content_origin: gpui::Point<Pixels>,
 7103        editor_width: Pixels,
 7104        window: &mut Window,
 7105        cx: &mut App,
 7106    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7107        let target_line_end = DisplayPoint::new(
 7108            target_display_point.row(),
 7109            editor_snapshot.line_len(target_display_point.row()),
 7110        );
 7111
 7112        let mut element = self
 7113            .render_edit_prediction_line_popover(label, None, window, cx)?
 7114            .into_any();
 7115
 7116        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7117
 7118        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 7119
 7120        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 7121        let mut origin = start_point
 7122            + line_origin
 7123            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 7124        origin.x = origin.x.max(content_origin.x);
 7125
 7126        let max_x = content_origin.x + editor_width - size.width;
 7127
 7128        if origin.x > max_x {
 7129            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 7130
 7131            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 7132                origin.y += offset;
 7133                IconName::ArrowUp
 7134            } else {
 7135                origin.y -= offset;
 7136                IconName::ArrowDown
 7137            };
 7138
 7139            element = self
 7140                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 7141                .into_any();
 7142
 7143            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7144
 7145            origin.x = content_origin.x + editor_width - size.width - px(2.);
 7146        }
 7147
 7148        element.prepaint_at(origin, window, cx);
 7149        Some((element, origin))
 7150    }
 7151
 7152    fn render_edit_prediction_diff_popover(
 7153        self: &Editor,
 7154        text_bounds: &Bounds<Pixels>,
 7155        content_origin: gpui::Point<Pixels>,
 7156        editor_snapshot: &EditorSnapshot,
 7157        visible_row_range: Range<DisplayRow>,
 7158        line_layouts: &[LineWithInvisibles],
 7159        line_height: Pixels,
 7160        scroll_pixel_position: gpui::Point<Pixels>,
 7161        newest_selection_head: Option<DisplayPoint>,
 7162        editor_width: Pixels,
 7163        style: &EditorStyle,
 7164        edits: &Vec<(Range<Anchor>, String)>,
 7165        edit_preview: &Option<language::EditPreview>,
 7166        snapshot: &language::BufferSnapshot,
 7167        window: &mut Window,
 7168        cx: &mut App,
 7169    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7170        let edit_start = edits
 7171            .first()
 7172            .unwrap()
 7173            .0
 7174            .start
 7175            .to_display_point(editor_snapshot);
 7176        let edit_end = edits
 7177            .last()
 7178            .unwrap()
 7179            .0
 7180            .end
 7181            .to_display_point(editor_snapshot);
 7182
 7183        let is_visible = visible_row_range.contains(&edit_start.row())
 7184            || visible_row_range.contains(&edit_end.row());
 7185        if !is_visible {
 7186            return None;
 7187        }
 7188
 7189        let highlighted_edits =
 7190            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 7191
 7192        let styled_text = highlighted_edits.to_styled_text(&style.text);
 7193        let line_count = highlighted_edits.text.lines().count();
 7194
 7195        const BORDER_WIDTH: Pixels = px(1.);
 7196
 7197        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7198        let has_keybind = keybind.is_some();
 7199
 7200        let mut element = h_flex()
 7201            .items_start()
 7202            .child(
 7203                h_flex()
 7204                    .bg(cx.theme().colors().editor_background)
 7205                    .border(BORDER_WIDTH)
 7206                    .shadow_sm()
 7207                    .border_color(cx.theme().colors().border)
 7208                    .rounded_l_lg()
 7209                    .when(line_count > 1, |el| el.rounded_br_lg())
 7210                    .pr_1()
 7211                    .child(styled_text),
 7212            )
 7213            .child(
 7214                h_flex()
 7215                    .h(line_height + BORDER_WIDTH * 2.)
 7216                    .px_1p5()
 7217                    .gap_1()
 7218                    // Workaround: For some reason, there's a gap if we don't do this
 7219                    .ml(-BORDER_WIDTH)
 7220                    .shadow(smallvec![gpui::BoxShadow {
 7221                        color: gpui::black().opacity(0.05),
 7222                        offset: point(px(1.), px(1.)),
 7223                        blur_radius: px(2.),
 7224                        spread_radius: px(0.),
 7225                    }])
 7226                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 7227                    .border(BORDER_WIDTH)
 7228                    .border_color(cx.theme().colors().border)
 7229                    .rounded_r_lg()
 7230                    .id("edit_prediction_diff_popover_keybind")
 7231                    .when(!has_keybind, |el| {
 7232                        let status_colors = cx.theme().status();
 7233
 7234                        el.bg(status_colors.error_background)
 7235                            .border_color(status_colors.error.opacity(0.6))
 7236                            .child(Icon::new(IconName::Info).color(Color::Error))
 7237                            .cursor_default()
 7238                            .hoverable_tooltip(move |_window, cx| {
 7239                                cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7240                            })
 7241                    })
 7242                    .children(keybind),
 7243            )
 7244            .into_any();
 7245
 7246        let longest_row =
 7247            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 7248        let longest_line_width = if visible_row_range.contains(&longest_row) {
 7249            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 7250        } else {
 7251            layout_line(
 7252                longest_row,
 7253                editor_snapshot,
 7254                style,
 7255                editor_width,
 7256                |_| false,
 7257                window,
 7258                cx,
 7259            )
 7260            .width
 7261        };
 7262
 7263        let viewport_bounds =
 7264            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 7265                right: -EditorElement::SCROLLBAR_WIDTH,
 7266                ..Default::default()
 7267            });
 7268
 7269        let x_after_longest =
 7270            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 7271                - scroll_pixel_position.x;
 7272
 7273        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7274
 7275        // Fully visible if it can be displayed within the window (allow overlapping other
 7276        // panes). However, this is only allowed if the popover starts within text_bounds.
 7277        let can_position_to_the_right = x_after_longest < text_bounds.right()
 7278            && x_after_longest + element_bounds.width < viewport_bounds.right();
 7279
 7280        let mut origin = if can_position_to_the_right {
 7281            point(
 7282                x_after_longest,
 7283                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 7284                    - scroll_pixel_position.y,
 7285            )
 7286        } else {
 7287            let cursor_row = newest_selection_head.map(|head| head.row());
 7288            let above_edit = edit_start
 7289                .row()
 7290                .0
 7291                .checked_sub(line_count as u32)
 7292                .map(DisplayRow);
 7293            let below_edit = Some(edit_end.row() + 1);
 7294            let above_cursor =
 7295                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 7296            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 7297
 7298            // Place the edit popover adjacent to the edit if there is a location
 7299            // available that is onscreen and does not obscure the cursor. Otherwise,
 7300            // place it adjacent to the cursor.
 7301            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 7302                .into_iter()
 7303                .flatten()
 7304                .find(|&start_row| {
 7305                    let end_row = start_row + line_count as u32;
 7306                    visible_row_range.contains(&start_row)
 7307                        && visible_row_range.contains(&end_row)
 7308                        && cursor_row.map_or(true, |cursor_row| {
 7309                            !((start_row..end_row).contains(&cursor_row))
 7310                        })
 7311                })?;
 7312
 7313            content_origin
 7314                + point(
 7315                    -scroll_pixel_position.x,
 7316                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 7317                )
 7318        };
 7319
 7320        origin.x -= BORDER_WIDTH;
 7321
 7322        window.defer_draw(element, origin, 1);
 7323
 7324        // Do not return an element, since it will already be drawn due to defer_draw.
 7325        None
 7326    }
 7327
 7328    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 7329        px(30.)
 7330    }
 7331
 7332    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 7333        if self.read_only(cx) {
 7334            cx.theme().players().read_only()
 7335        } else {
 7336            self.style.as_ref().unwrap().local_player
 7337        }
 7338    }
 7339
 7340    fn render_edit_prediction_accept_keybind(
 7341        &self,
 7342        window: &mut Window,
 7343        cx: &App,
 7344    ) -> Option<AnyElement> {
 7345        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 7346        let accept_keystroke = accept_binding.keystroke()?;
 7347
 7348        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7349
 7350        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 7351            Color::Accent
 7352        } else {
 7353            Color::Muted
 7354        };
 7355
 7356        h_flex()
 7357            .px_0p5()
 7358            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 7359            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7360            .text_size(TextSize::XSmall.rems(cx))
 7361            .child(h_flex().children(ui::render_modifiers(
 7362                &accept_keystroke.modifiers,
 7363                PlatformStyle::platform(),
 7364                Some(modifiers_color),
 7365                Some(IconSize::XSmall.rems().into()),
 7366                true,
 7367            )))
 7368            .when(is_platform_style_mac, |parent| {
 7369                parent.child(accept_keystroke.key.clone())
 7370            })
 7371            .when(!is_platform_style_mac, |parent| {
 7372                parent.child(
 7373                    Key::new(
 7374                        util::capitalize(&accept_keystroke.key),
 7375                        Some(Color::Default),
 7376                    )
 7377                    .size(Some(IconSize::XSmall.rems().into())),
 7378                )
 7379            })
 7380            .into_any()
 7381            .into()
 7382    }
 7383
 7384    fn render_edit_prediction_line_popover(
 7385        &self,
 7386        label: impl Into<SharedString>,
 7387        icon: Option<IconName>,
 7388        window: &mut Window,
 7389        cx: &App,
 7390    ) -> Option<Stateful<Div>> {
 7391        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 7392
 7393        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7394        let has_keybind = keybind.is_some();
 7395
 7396        let result = h_flex()
 7397            .id("ep-line-popover")
 7398            .py_0p5()
 7399            .pl_1()
 7400            .pr(padding_right)
 7401            .gap_1()
 7402            .rounded_md()
 7403            .border_1()
 7404            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7405            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 7406            .shadow_sm()
 7407            .when(!has_keybind, |el| {
 7408                let status_colors = cx.theme().status();
 7409
 7410                el.bg(status_colors.error_background)
 7411                    .border_color(status_colors.error.opacity(0.6))
 7412                    .pl_2()
 7413                    .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
 7414                    .cursor_default()
 7415                    .hoverable_tooltip(move |_window, cx| {
 7416                        cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7417                    })
 7418            })
 7419            .children(keybind)
 7420            .child(
 7421                Label::new(label)
 7422                    .size(LabelSize::Small)
 7423                    .when(!has_keybind, |el| {
 7424                        el.color(cx.theme().status().error.into()).strikethrough()
 7425                    }),
 7426            )
 7427            .when(!has_keybind, |el| {
 7428                el.child(
 7429                    h_flex().ml_1().child(
 7430                        Icon::new(IconName::Info)
 7431                            .size(IconSize::Small)
 7432                            .color(cx.theme().status().error.into()),
 7433                    ),
 7434                )
 7435            })
 7436            .when_some(icon, |element, icon| {
 7437                element.child(
 7438                    div()
 7439                        .mt(px(1.5))
 7440                        .child(Icon::new(icon).size(IconSize::Small)),
 7441                )
 7442            });
 7443
 7444        Some(result)
 7445    }
 7446
 7447    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 7448        let accent_color = cx.theme().colors().text_accent;
 7449        let editor_bg_color = cx.theme().colors().editor_background;
 7450        editor_bg_color.blend(accent_color.opacity(0.1))
 7451    }
 7452
 7453    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 7454        let accent_color = cx.theme().colors().text_accent;
 7455        let editor_bg_color = cx.theme().colors().editor_background;
 7456        editor_bg_color.blend(accent_color.opacity(0.6))
 7457    }
 7458
 7459    fn render_edit_prediction_cursor_popover(
 7460        &self,
 7461        min_width: Pixels,
 7462        max_width: Pixels,
 7463        cursor_point: Point,
 7464        style: &EditorStyle,
 7465        accept_keystroke: Option<&gpui::Keystroke>,
 7466        _window: &Window,
 7467        cx: &mut Context<Editor>,
 7468    ) -> Option<AnyElement> {
 7469        let provider = self.edit_prediction_provider.as_ref()?;
 7470
 7471        if provider.provider.needs_terms_acceptance(cx) {
 7472            return Some(
 7473                h_flex()
 7474                    .min_w(min_width)
 7475                    .flex_1()
 7476                    .px_2()
 7477                    .py_1()
 7478                    .gap_3()
 7479                    .elevation_2(cx)
 7480                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 7481                    .id("accept-terms")
 7482                    .cursor_pointer()
 7483                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 7484                    .on_click(cx.listener(|this, _event, window, cx| {
 7485                        cx.stop_propagation();
 7486                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 7487                        window.dispatch_action(
 7488                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 7489                            cx,
 7490                        );
 7491                    }))
 7492                    .child(
 7493                        h_flex()
 7494                            .flex_1()
 7495                            .gap_2()
 7496                            .child(Icon::new(IconName::ZedPredict))
 7497                            .child(Label::new("Accept Terms of Service"))
 7498                            .child(div().w_full())
 7499                            .child(
 7500                                Icon::new(IconName::ArrowUpRight)
 7501                                    .color(Color::Muted)
 7502                                    .size(IconSize::Small),
 7503                            )
 7504                            .into_any_element(),
 7505                    )
 7506                    .into_any(),
 7507            );
 7508        }
 7509
 7510        let is_refreshing = provider.provider.is_refreshing(cx);
 7511
 7512        fn pending_completion_container() -> Div {
 7513            h_flex()
 7514                .h_full()
 7515                .flex_1()
 7516                .gap_2()
 7517                .child(Icon::new(IconName::ZedPredict))
 7518        }
 7519
 7520        let completion = match &self.active_inline_completion {
 7521            Some(prediction) => {
 7522                if !self.has_visible_completions_menu() {
 7523                    const RADIUS: Pixels = px(6.);
 7524                    const BORDER_WIDTH: Pixels = px(1.);
 7525
 7526                    return Some(
 7527                        h_flex()
 7528                            .elevation_2(cx)
 7529                            .border(BORDER_WIDTH)
 7530                            .border_color(cx.theme().colors().border)
 7531                            .when(accept_keystroke.is_none(), |el| {
 7532                                el.border_color(cx.theme().status().error)
 7533                            })
 7534                            .rounded(RADIUS)
 7535                            .rounded_tl(px(0.))
 7536                            .overflow_hidden()
 7537                            .child(div().px_1p5().child(match &prediction.completion {
 7538                                InlineCompletion::Move { target, snapshot } => {
 7539                                    use text::ToPoint as _;
 7540                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 7541                                    {
 7542                                        Icon::new(IconName::ZedPredictDown)
 7543                                    } else {
 7544                                        Icon::new(IconName::ZedPredictUp)
 7545                                    }
 7546                                }
 7547                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 7548                            }))
 7549                            .child(
 7550                                h_flex()
 7551                                    .gap_1()
 7552                                    .py_1()
 7553                                    .px_2()
 7554                                    .rounded_r(RADIUS - BORDER_WIDTH)
 7555                                    .border_l_1()
 7556                                    .border_color(cx.theme().colors().border)
 7557                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7558                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 7559                                        el.child(
 7560                                            Label::new("Hold")
 7561                                                .size(LabelSize::Small)
 7562                                                .when(accept_keystroke.is_none(), |el| {
 7563                                                    el.strikethrough()
 7564                                                })
 7565                                                .line_height_style(LineHeightStyle::UiLabel),
 7566                                        )
 7567                                    })
 7568                                    .id("edit_prediction_cursor_popover_keybind")
 7569                                    .when(accept_keystroke.is_none(), |el| {
 7570                                        let status_colors = cx.theme().status();
 7571
 7572                                        el.bg(status_colors.error_background)
 7573                                            .border_color(status_colors.error.opacity(0.6))
 7574                                            .child(Icon::new(IconName::Info).color(Color::Error))
 7575                                            .cursor_default()
 7576                                            .hoverable_tooltip(move |_window, cx| {
 7577                                                cx.new(|_| MissingEditPredictionKeybindingTooltip)
 7578                                                    .into()
 7579                                            })
 7580                                    })
 7581                                    .when_some(
 7582                                        accept_keystroke.as_ref(),
 7583                                        |el, accept_keystroke| {
 7584                                            el.child(h_flex().children(ui::render_modifiers(
 7585                                                &accept_keystroke.modifiers,
 7586                                                PlatformStyle::platform(),
 7587                                                Some(Color::Default),
 7588                                                Some(IconSize::XSmall.rems().into()),
 7589                                                false,
 7590                                            )))
 7591                                        },
 7592                                    ),
 7593                            )
 7594                            .into_any(),
 7595                    );
 7596                }
 7597
 7598                self.render_edit_prediction_cursor_popover_preview(
 7599                    prediction,
 7600                    cursor_point,
 7601                    style,
 7602                    cx,
 7603                )?
 7604            }
 7605
 7606            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 7607                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 7608                    stale_completion,
 7609                    cursor_point,
 7610                    style,
 7611                    cx,
 7612                )?,
 7613
 7614                None => {
 7615                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 7616                }
 7617            },
 7618
 7619            None => pending_completion_container().child(Label::new("No Prediction")),
 7620        };
 7621
 7622        let completion = if is_refreshing {
 7623            completion
 7624                .with_animation(
 7625                    "loading-completion",
 7626                    Animation::new(Duration::from_secs(2))
 7627                        .repeat()
 7628                        .with_easing(pulsating_between(0.4, 0.8)),
 7629                    |label, delta| label.opacity(delta),
 7630                )
 7631                .into_any_element()
 7632        } else {
 7633            completion.into_any_element()
 7634        };
 7635
 7636        let has_completion = self.active_inline_completion.is_some();
 7637
 7638        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7639        Some(
 7640            h_flex()
 7641                .min_w(min_width)
 7642                .max_w(max_width)
 7643                .flex_1()
 7644                .elevation_2(cx)
 7645                .border_color(cx.theme().colors().border)
 7646                .child(
 7647                    div()
 7648                        .flex_1()
 7649                        .py_1()
 7650                        .px_2()
 7651                        .overflow_hidden()
 7652                        .child(completion),
 7653                )
 7654                .when_some(accept_keystroke, |el, accept_keystroke| {
 7655                    if !accept_keystroke.modifiers.modified() {
 7656                        return el;
 7657                    }
 7658
 7659                    el.child(
 7660                        h_flex()
 7661                            .h_full()
 7662                            .border_l_1()
 7663                            .rounded_r_lg()
 7664                            .border_color(cx.theme().colors().border)
 7665                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7666                            .gap_1()
 7667                            .py_1()
 7668                            .px_2()
 7669                            .child(
 7670                                h_flex()
 7671                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7672                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 7673                                    .child(h_flex().children(ui::render_modifiers(
 7674                                        &accept_keystroke.modifiers,
 7675                                        PlatformStyle::platform(),
 7676                                        Some(if !has_completion {
 7677                                            Color::Muted
 7678                                        } else {
 7679                                            Color::Default
 7680                                        }),
 7681                                        None,
 7682                                        false,
 7683                                    ))),
 7684                            )
 7685                            .child(Label::new("Preview").into_any_element())
 7686                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 7687                    )
 7688                })
 7689                .into_any(),
 7690        )
 7691    }
 7692
 7693    fn render_edit_prediction_cursor_popover_preview(
 7694        &self,
 7695        completion: &InlineCompletionState,
 7696        cursor_point: Point,
 7697        style: &EditorStyle,
 7698        cx: &mut Context<Editor>,
 7699    ) -> Option<Div> {
 7700        use text::ToPoint as _;
 7701
 7702        fn render_relative_row_jump(
 7703            prefix: impl Into<String>,
 7704            current_row: u32,
 7705            target_row: u32,
 7706        ) -> Div {
 7707            let (row_diff, arrow) = if target_row < current_row {
 7708                (current_row - target_row, IconName::ArrowUp)
 7709            } else {
 7710                (target_row - current_row, IconName::ArrowDown)
 7711            };
 7712
 7713            h_flex()
 7714                .child(
 7715                    Label::new(format!("{}{}", prefix.into(), row_diff))
 7716                        .color(Color::Muted)
 7717                        .size(LabelSize::Small),
 7718                )
 7719                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 7720        }
 7721
 7722        match &completion.completion {
 7723            InlineCompletion::Move {
 7724                target, snapshot, ..
 7725            } => Some(
 7726                h_flex()
 7727                    .px_2()
 7728                    .gap_2()
 7729                    .flex_1()
 7730                    .child(
 7731                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 7732                            Icon::new(IconName::ZedPredictDown)
 7733                        } else {
 7734                            Icon::new(IconName::ZedPredictUp)
 7735                        },
 7736                    )
 7737                    .child(Label::new("Jump to Edit")),
 7738            ),
 7739
 7740            InlineCompletion::Edit {
 7741                edits,
 7742                edit_preview,
 7743                snapshot,
 7744                display_mode: _,
 7745            } => {
 7746                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 7747
 7748                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 7749                    &snapshot,
 7750                    &edits,
 7751                    edit_preview.as_ref()?,
 7752                    true,
 7753                    cx,
 7754                )
 7755                .first_line_preview();
 7756
 7757                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 7758                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 7759
 7760                let preview = h_flex()
 7761                    .gap_1()
 7762                    .min_w_16()
 7763                    .child(styled_text)
 7764                    .when(has_more_lines, |parent| parent.child(""));
 7765
 7766                let left = if first_edit_row != cursor_point.row {
 7767                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 7768                        .into_any_element()
 7769                } else {
 7770                    Icon::new(IconName::ZedPredict).into_any_element()
 7771                };
 7772
 7773                Some(
 7774                    h_flex()
 7775                        .h_full()
 7776                        .flex_1()
 7777                        .gap_2()
 7778                        .pr_1()
 7779                        .overflow_x_hidden()
 7780                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7781                        .child(left)
 7782                        .child(preview),
 7783                )
 7784            }
 7785        }
 7786    }
 7787
 7788    fn render_context_menu(
 7789        &self,
 7790        style: &EditorStyle,
 7791        max_height_in_lines: u32,
 7792        window: &mut Window,
 7793        cx: &mut Context<Editor>,
 7794    ) -> Option<AnyElement> {
 7795        let menu = self.context_menu.borrow();
 7796        let menu = menu.as_ref()?;
 7797        if !menu.visible() {
 7798            return None;
 7799        };
 7800        Some(menu.render(style, max_height_in_lines, window, cx))
 7801    }
 7802
 7803    fn render_context_menu_aside(
 7804        &mut self,
 7805        max_size: Size<Pixels>,
 7806        window: &mut Window,
 7807        cx: &mut Context<Editor>,
 7808    ) -> Option<AnyElement> {
 7809        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 7810            if menu.visible() {
 7811                menu.render_aside(self, max_size, window, cx)
 7812            } else {
 7813                None
 7814            }
 7815        })
 7816    }
 7817
 7818    fn hide_context_menu(
 7819        &mut self,
 7820        window: &mut Window,
 7821        cx: &mut Context<Self>,
 7822    ) -> Option<CodeContextMenu> {
 7823        cx.notify();
 7824        self.completion_tasks.clear();
 7825        let context_menu = self.context_menu.borrow_mut().take();
 7826        self.stale_inline_completion_in_menu.take();
 7827        self.update_visible_inline_completion(window, cx);
 7828        context_menu
 7829    }
 7830
 7831    fn show_snippet_choices(
 7832        &mut self,
 7833        choices: &Vec<String>,
 7834        selection: Range<Anchor>,
 7835        cx: &mut Context<Self>,
 7836    ) {
 7837        if selection.start.buffer_id.is_none() {
 7838            return;
 7839        }
 7840        let buffer_id = selection.start.buffer_id.unwrap();
 7841        let buffer = self.buffer().read(cx).buffer(buffer_id);
 7842        let id = post_inc(&mut self.next_completion_id);
 7843
 7844        if let Some(buffer) = buffer {
 7845            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 7846                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 7847            ));
 7848        }
 7849    }
 7850
 7851    pub fn insert_snippet(
 7852        &mut self,
 7853        insertion_ranges: &[Range<usize>],
 7854        snippet: Snippet,
 7855        window: &mut Window,
 7856        cx: &mut Context<Self>,
 7857    ) -> Result<()> {
 7858        struct Tabstop<T> {
 7859            is_end_tabstop: bool,
 7860            ranges: Vec<Range<T>>,
 7861            choices: Option<Vec<String>>,
 7862        }
 7863
 7864        let tabstops = self.buffer.update(cx, |buffer, cx| {
 7865            let snippet_text: Arc<str> = snippet.text.clone().into();
 7866            let edits = insertion_ranges
 7867                .iter()
 7868                .cloned()
 7869                .map(|range| (range, snippet_text.clone()));
 7870            buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
 7871
 7872            let snapshot = &*buffer.read(cx);
 7873            let snippet = &snippet;
 7874            snippet
 7875                .tabstops
 7876                .iter()
 7877                .map(|tabstop| {
 7878                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 7879                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 7880                    });
 7881                    let mut tabstop_ranges = tabstop
 7882                        .ranges
 7883                        .iter()
 7884                        .flat_map(|tabstop_range| {
 7885                            let mut delta = 0_isize;
 7886                            insertion_ranges.iter().map(move |insertion_range| {
 7887                                let insertion_start = insertion_range.start as isize + delta;
 7888                                delta +=
 7889                                    snippet.text.len() as isize - insertion_range.len() as isize;
 7890
 7891                                let start = ((insertion_start + tabstop_range.start) as usize)
 7892                                    .min(snapshot.len());
 7893                                let end = ((insertion_start + tabstop_range.end) as usize)
 7894                                    .min(snapshot.len());
 7895                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 7896                            })
 7897                        })
 7898                        .collect::<Vec<_>>();
 7899                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 7900
 7901                    Tabstop {
 7902                        is_end_tabstop,
 7903                        ranges: tabstop_ranges,
 7904                        choices: tabstop.choices.clone(),
 7905                    }
 7906                })
 7907                .collect::<Vec<_>>()
 7908        });
 7909        if let Some(tabstop) = tabstops.first() {
 7910            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7911                s.select_ranges(tabstop.ranges.iter().cloned());
 7912            });
 7913
 7914            if let Some(choices) = &tabstop.choices {
 7915                if let Some(selection) = tabstop.ranges.first() {
 7916                    self.show_snippet_choices(choices, selection.clone(), cx)
 7917                }
 7918            }
 7919
 7920            // If we're already at the last tabstop and it's at the end of the snippet,
 7921            // we're done, we don't need to keep the state around.
 7922            if !tabstop.is_end_tabstop {
 7923                let choices = tabstops
 7924                    .iter()
 7925                    .map(|tabstop| tabstop.choices.clone())
 7926                    .collect();
 7927
 7928                let ranges = tabstops
 7929                    .into_iter()
 7930                    .map(|tabstop| tabstop.ranges)
 7931                    .collect::<Vec<_>>();
 7932
 7933                self.snippet_stack.push(SnippetState {
 7934                    active_index: 0,
 7935                    ranges,
 7936                    choices,
 7937                });
 7938            }
 7939
 7940            // Check whether the just-entered snippet ends with an auto-closable bracket.
 7941            if self.autoclose_regions.is_empty() {
 7942                let snapshot = self.buffer.read(cx).snapshot(cx);
 7943                for selection in &mut self.selections.all::<Point>(cx) {
 7944                    let selection_head = selection.head();
 7945                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 7946                        continue;
 7947                    };
 7948
 7949                    let mut bracket_pair = None;
 7950                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 7951                    let prev_chars = snapshot
 7952                        .reversed_chars_at(selection_head)
 7953                        .collect::<String>();
 7954                    for (pair, enabled) in scope.brackets() {
 7955                        if enabled
 7956                            && pair.close
 7957                            && prev_chars.starts_with(pair.start.as_str())
 7958                            && next_chars.starts_with(pair.end.as_str())
 7959                        {
 7960                            bracket_pair = Some(pair.clone());
 7961                            break;
 7962                        }
 7963                    }
 7964                    if let Some(pair) = bracket_pair {
 7965                        let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
 7966                        let autoclose_enabled =
 7967                            self.use_autoclose && snapshot_settings.use_autoclose;
 7968                        if autoclose_enabled {
 7969                            let start = snapshot.anchor_after(selection_head);
 7970                            let end = snapshot.anchor_after(selection_head);
 7971                            self.autoclose_regions.push(AutocloseRegion {
 7972                                selection_id: selection.id,
 7973                                range: start..end,
 7974                                pair,
 7975                            });
 7976                        }
 7977                    }
 7978                }
 7979            }
 7980        }
 7981        Ok(())
 7982    }
 7983
 7984    pub fn move_to_next_snippet_tabstop(
 7985        &mut self,
 7986        window: &mut Window,
 7987        cx: &mut Context<Self>,
 7988    ) -> bool {
 7989        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 7990    }
 7991
 7992    pub fn move_to_prev_snippet_tabstop(
 7993        &mut self,
 7994        window: &mut Window,
 7995        cx: &mut Context<Self>,
 7996    ) -> bool {
 7997        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 7998    }
 7999
 8000    pub fn move_to_snippet_tabstop(
 8001        &mut self,
 8002        bias: Bias,
 8003        window: &mut Window,
 8004        cx: &mut Context<Self>,
 8005    ) -> bool {
 8006        if let Some(mut snippet) = self.snippet_stack.pop() {
 8007            match bias {
 8008                Bias::Left => {
 8009                    if snippet.active_index > 0 {
 8010                        snippet.active_index -= 1;
 8011                    } else {
 8012                        self.snippet_stack.push(snippet);
 8013                        return false;
 8014                    }
 8015                }
 8016                Bias::Right => {
 8017                    if snippet.active_index + 1 < snippet.ranges.len() {
 8018                        snippet.active_index += 1;
 8019                    } else {
 8020                        self.snippet_stack.push(snippet);
 8021                        return false;
 8022                    }
 8023                }
 8024            }
 8025            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 8026                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8027                    s.select_anchor_ranges(current_ranges.iter().cloned())
 8028                });
 8029
 8030                if let Some(choices) = &snippet.choices[snippet.active_index] {
 8031                    if let Some(selection) = current_ranges.first() {
 8032                        self.show_snippet_choices(&choices, selection.clone(), cx);
 8033                    }
 8034                }
 8035
 8036                // If snippet state is not at the last tabstop, push it back on the stack
 8037                if snippet.active_index + 1 < snippet.ranges.len() {
 8038                    self.snippet_stack.push(snippet);
 8039                }
 8040                return true;
 8041            }
 8042        }
 8043
 8044        false
 8045    }
 8046
 8047    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 8048        self.transact(window, cx, |this, window, cx| {
 8049            this.select_all(&SelectAll, window, cx);
 8050            this.insert("", window, cx);
 8051        });
 8052    }
 8053
 8054    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 8055        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8056        self.transact(window, cx, |this, window, cx| {
 8057            this.select_autoclose_pair(window, cx);
 8058            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 8059            if !this.linked_edit_ranges.is_empty() {
 8060                let selections = this.selections.all::<MultiBufferPoint>(cx);
 8061                let snapshot = this.buffer.read(cx).snapshot(cx);
 8062
 8063                for selection in selections.iter() {
 8064                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 8065                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 8066                    if selection_start.buffer_id != selection_end.buffer_id {
 8067                        continue;
 8068                    }
 8069                    if let Some(ranges) =
 8070                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 8071                    {
 8072                        for (buffer, entries) in ranges {
 8073                            linked_ranges.entry(buffer).or_default().extend(entries);
 8074                        }
 8075                    }
 8076                }
 8077            }
 8078
 8079            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8080            let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 8081            for selection in &mut selections {
 8082                if selection.is_empty() {
 8083                    let old_head = selection.head();
 8084                    let mut new_head =
 8085                        movement::left(&display_map, old_head.to_display_point(&display_map))
 8086                            .to_point(&display_map);
 8087                    if let Some((buffer, line_buffer_range)) = display_map
 8088                        .buffer_snapshot
 8089                        .buffer_line_for_row(MultiBufferRow(old_head.row))
 8090                    {
 8091                        let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
 8092                        let indent_len = match indent_size.kind {
 8093                            IndentKind::Space => {
 8094                                buffer.settings_at(line_buffer_range.start, cx).tab_size
 8095                            }
 8096                            IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 8097                        };
 8098                        if old_head.column <= indent_size.len && old_head.column > 0 {
 8099                            let indent_len = indent_len.get();
 8100                            new_head = cmp::min(
 8101                                new_head,
 8102                                MultiBufferPoint::new(
 8103                                    old_head.row,
 8104                                    ((old_head.column - 1) / indent_len) * indent_len,
 8105                                ),
 8106                            );
 8107                        }
 8108                    }
 8109
 8110                    selection.set_head(new_head, SelectionGoal::None);
 8111                }
 8112            }
 8113
 8114            this.signature_help_state.set_backspace_pressed(true);
 8115            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8116                s.select(selections)
 8117            });
 8118            this.insert("", window, cx);
 8119            let empty_str: Arc<str> = Arc::from("");
 8120            for (buffer, edits) in linked_ranges {
 8121                let snapshot = buffer.read(cx).snapshot();
 8122                use text::ToPoint as TP;
 8123
 8124                let edits = edits
 8125                    .into_iter()
 8126                    .map(|range| {
 8127                        let end_point = TP::to_point(&range.end, &snapshot);
 8128                        let mut start_point = TP::to_point(&range.start, &snapshot);
 8129
 8130                        if end_point == start_point {
 8131                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 8132                                .saturating_sub(1);
 8133                            start_point =
 8134                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 8135                        };
 8136
 8137                        (start_point..end_point, empty_str.clone())
 8138                    })
 8139                    .sorted_by_key(|(range, _)| range.start)
 8140                    .collect::<Vec<_>>();
 8141                buffer.update(cx, |this, cx| {
 8142                    this.edit(edits, None, cx);
 8143                })
 8144            }
 8145            this.refresh_inline_completion(true, false, window, cx);
 8146            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 8147        });
 8148    }
 8149
 8150    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 8151        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8152        self.transact(window, cx, |this, window, cx| {
 8153            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8154                s.move_with(|map, selection| {
 8155                    if selection.is_empty() {
 8156                        let cursor = movement::right(map, selection.head());
 8157                        selection.end = cursor;
 8158                        selection.reversed = true;
 8159                        selection.goal = SelectionGoal::None;
 8160                    }
 8161                })
 8162            });
 8163            this.insert("", window, cx);
 8164            this.refresh_inline_completion(true, false, window, cx);
 8165        });
 8166    }
 8167
 8168    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 8169        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8170        if self.move_to_prev_snippet_tabstop(window, cx) {
 8171            return;
 8172        }
 8173        self.outdent(&Outdent, window, cx);
 8174    }
 8175
 8176    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 8177        if self.move_to_next_snippet_tabstop(window, cx) {
 8178            self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8179            return;
 8180        }
 8181        if self.read_only(cx) {
 8182            return;
 8183        }
 8184        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8185        let mut selections = self.selections.all_adjusted(cx);
 8186        let buffer = self.buffer.read(cx);
 8187        let snapshot = buffer.snapshot(cx);
 8188        let rows_iter = selections.iter().map(|s| s.head().row);
 8189        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 8190
 8191        let mut edits = Vec::new();
 8192        let mut prev_edited_row = 0;
 8193        let mut row_delta = 0;
 8194        for selection in &mut selections {
 8195            if selection.start.row != prev_edited_row {
 8196                row_delta = 0;
 8197            }
 8198            prev_edited_row = selection.end.row;
 8199
 8200            // If the selection is non-empty, then increase the indentation of the selected lines.
 8201            if !selection.is_empty() {
 8202                row_delta =
 8203                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8204                continue;
 8205            }
 8206
 8207            // If the selection is empty and the cursor is in the leading whitespace before the
 8208            // suggested indentation, then auto-indent the line.
 8209            let cursor = selection.head();
 8210            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 8211            if let Some(suggested_indent) =
 8212                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 8213            {
 8214                if cursor.column < suggested_indent.len
 8215                    && cursor.column <= current_indent.len
 8216                    && current_indent.len <= suggested_indent.len
 8217                {
 8218                    selection.start = Point::new(cursor.row, suggested_indent.len);
 8219                    selection.end = selection.start;
 8220                    if row_delta == 0 {
 8221                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 8222                            cursor.row,
 8223                            current_indent,
 8224                            suggested_indent,
 8225                        ));
 8226                        row_delta = suggested_indent.len - current_indent.len;
 8227                    }
 8228                    continue;
 8229                }
 8230            }
 8231
 8232            // Otherwise, insert a hard or soft tab.
 8233            let settings = buffer.language_settings_at(cursor, cx);
 8234            let tab_size = if settings.hard_tabs {
 8235                IndentSize::tab()
 8236            } else {
 8237                let tab_size = settings.tab_size.get();
 8238                let char_column = snapshot
 8239                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 8240                    .flat_map(str::chars)
 8241                    .count()
 8242                    + row_delta as usize;
 8243                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 8244                IndentSize::spaces(chars_to_next_tab_stop)
 8245            };
 8246            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 8247            selection.end = selection.start;
 8248            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 8249            row_delta += tab_size.len;
 8250        }
 8251
 8252        self.transact(window, cx, |this, window, cx| {
 8253            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8254            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8255                s.select(selections)
 8256            });
 8257            this.refresh_inline_completion(true, false, window, cx);
 8258        });
 8259    }
 8260
 8261    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 8262        if self.read_only(cx) {
 8263            return;
 8264        }
 8265        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8266        let mut selections = self.selections.all::<Point>(cx);
 8267        let mut prev_edited_row = 0;
 8268        let mut row_delta = 0;
 8269        let mut edits = Vec::new();
 8270        let buffer = self.buffer.read(cx);
 8271        let snapshot = buffer.snapshot(cx);
 8272        for selection in &mut selections {
 8273            if selection.start.row != prev_edited_row {
 8274                row_delta = 0;
 8275            }
 8276            prev_edited_row = selection.end.row;
 8277
 8278            row_delta =
 8279                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8280        }
 8281
 8282        self.transact(window, cx, |this, window, cx| {
 8283            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8284            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8285                s.select(selections)
 8286            });
 8287        });
 8288    }
 8289
 8290    fn indent_selection(
 8291        buffer: &MultiBuffer,
 8292        snapshot: &MultiBufferSnapshot,
 8293        selection: &mut Selection<Point>,
 8294        edits: &mut Vec<(Range<Point>, String)>,
 8295        delta_for_start_row: u32,
 8296        cx: &App,
 8297    ) -> u32 {
 8298        let settings = buffer.language_settings_at(selection.start, cx);
 8299        let tab_size = settings.tab_size.get();
 8300        let indent_kind = if settings.hard_tabs {
 8301            IndentKind::Tab
 8302        } else {
 8303            IndentKind::Space
 8304        };
 8305        let mut start_row = selection.start.row;
 8306        let mut end_row = selection.end.row + 1;
 8307
 8308        // If a selection ends at the beginning of a line, don't indent
 8309        // that last line.
 8310        if selection.end.column == 0 && selection.end.row > selection.start.row {
 8311            end_row -= 1;
 8312        }
 8313
 8314        // Avoid re-indenting a row that has already been indented by a
 8315        // previous selection, but still update this selection's column
 8316        // to reflect that indentation.
 8317        if delta_for_start_row > 0 {
 8318            start_row += 1;
 8319            selection.start.column += delta_for_start_row;
 8320            if selection.end.row == selection.start.row {
 8321                selection.end.column += delta_for_start_row;
 8322            }
 8323        }
 8324
 8325        let mut delta_for_end_row = 0;
 8326        let has_multiple_rows = start_row + 1 != end_row;
 8327        for row in start_row..end_row {
 8328            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 8329            let indent_delta = match (current_indent.kind, indent_kind) {
 8330                (IndentKind::Space, IndentKind::Space) => {
 8331                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 8332                    IndentSize::spaces(columns_to_next_tab_stop)
 8333                }
 8334                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 8335                (_, IndentKind::Tab) => IndentSize::tab(),
 8336            };
 8337
 8338            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 8339                0
 8340            } else {
 8341                selection.start.column
 8342            };
 8343            let row_start = Point::new(row, start);
 8344            edits.push((
 8345                row_start..row_start,
 8346                indent_delta.chars().collect::<String>(),
 8347            ));
 8348
 8349            // Update this selection's endpoints to reflect the indentation.
 8350            if row == selection.start.row {
 8351                selection.start.column += indent_delta.len;
 8352            }
 8353            if row == selection.end.row {
 8354                selection.end.column += indent_delta.len;
 8355                delta_for_end_row = indent_delta.len;
 8356            }
 8357        }
 8358
 8359        if selection.start.row == selection.end.row {
 8360            delta_for_start_row + delta_for_end_row
 8361        } else {
 8362            delta_for_end_row
 8363        }
 8364    }
 8365
 8366    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 8367        if self.read_only(cx) {
 8368            return;
 8369        }
 8370        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8371        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8372        let selections = self.selections.all::<Point>(cx);
 8373        let mut deletion_ranges = Vec::new();
 8374        let mut last_outdent = None;
 8375        {
 8376            let buffer = self.buffer.read(cx);
 8377            let snapshot = buffer.snapshot(cx);
 8378            for selection in &selections {
 8379                let settings = buffer.language_settings_at(selection.start, cx);
 8380                let tab_size = settings.tab_size.get();
 8381                let mut rows = selection.spanned_rows(false, &display_map);
 8382
 8383                // Avoid re-outdenting a row that has already been outdented by a
 8384                // previous selection.
 8385                if let Some(last_row) = last_outdent {
 8386                    if last_row == rows.start {
 8387                        rows.start = rows.start.next_row();
 8388                    }
 8389                }
 8390                let has_multiple_rows = rows.len() > 1;
 8391                for row in rows.iter_rows() {
 8392                    let indent_size = snapshot.indent_size_for_line(row);
 8393                    if indent_size.len > 0 {
 8394                        let deletion_len = match indent_size.kind {
 8395                            IndentKind::Space => {
 8396                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 8397                                if columns_to_prev_tab_stop == 0 {
 8398                                    tab_size
 8399                                } else {
 8400                                    columns_to_prev_tab_stop
 8401                                }
 8402                            }
 8403                            IndentKind::Tab => 1,
 8404                        };
 8405                        let start = if has_multiple_rows
 8406                            || deletion_len > selection.start.column
 8407                            || indent_size.len < selection.start.column
 8408                        {
 8409                            0
 8410                        } else {
 8411                            selection.start.column - deletion_len
 8412                        };
 8413                        deletion_ranges.push(
 8414                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 8415                        );
 8416                        last_outdent = Some(row);
 8417                    }
 8418                }
 8419            }
 8420        }
 8421
 8422        self.transact(window, cx, |this, window, cx| {
 8423            this.buffer.update(cx, |buffer, cx| {
 8424                let empty_str: Arc<str> = Arc::default();
 8425                buffer.edit(
 8426                    deletion_ranges
 8427                        .into_iter()
 8428                        .map(|range| (range, empty_str.clone())),
 8429                    None,
 8430                    cx,
 8431                );
 8432            });
 8433            let selections = this.selections.all::<usize>(cx);
 8434            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8435                s.select(selections)
 8436            });
 8437        });
 8438    }
 8439
 8440    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 8441        if self.read_only(cx) {
 8442            return;
 8443        }
 8444        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8445        let selections = self
 8446            .selections
 8447            .all::<usize>(cx)
 8448            .into_iter()
 8449            .map(|s| s.range());
 8450
 8451        self.transact(window, cx, |this, window, cx| {
 8452            this.buffer.update(cx, |buffer, cx| {
 8453                buffer.autoindent_ranges(selections, cx);
 8454            });
 8455            let selections = this.selections.all::<usize>(cx);
 8456            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8457                s.select(selections)
 8458            });
 8459        });
 8460    }
 8461
 8462    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 8463        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8464        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8465        let selections = self.selections.all::<Point>(cx);
 8466
 8467        let mut new_cursors = Vec::new();
 8468        let mut edit_ranges = Vec::new();
 8469        let mut selections = selections.iter().peekable();
 8470        while let Some(selection) = selections.next() {
 8471            let mut rows = selection.spanned_rows(false, &display_map);
 8472            let goal_display_column = selection.head().to_display_point(&display_map).column();
 8473
 8474            // Accumulate contiguous regions of rows that we want to delete.
 8475            while let Some(next_selection) = selections.peek() {
 8476                let next_rows = next_selection.spanned_rows(false, &display_map);
 8477                if next_rows.start <= rows.end {
 8478                    rows.end = next_rows.end;
 8479                    selections.next().unwrap();
 8480                } else {
 8481                    break;
 8482                }
 8483            }
 8484
 8485            let buffer = &display_map.buffer_snapshot;
 8486            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 8487            let edit_end;
 8488            let cursor_buffer_row;
 8489            if buffer.max_point().row >= rows.end.0 {
 8490                // If there's a line after the range, delete the \n from the end of the row range
 8491                // and position the cursor on the next line.
 8492                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 8493                cursor_buffer_row = rows.end;
 8494            } else {
 8495                // If there isn't a line after the range, delete the \n from the line before the
 8496                // start of the row range and position the cursor there.
 8497                edit_start = edit_start.saturating_sub(1);
 8498                edit_end = buffer.len();
 8499                cursor_buffer_row = rows.start.previous_row();
 8500            }
 8501
 8502            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 8503            *cursor.column_mut() =
 8504                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 8505
 8506            new_cursors.push((
 8507                selection.id,
 8508                buffer.anchor_after(cursor.to_point(&display_map)),
 8509            ));
 8510            edit_ranges.push(edit_start..edit_end);
 8511        }
 8512
 8513        self.transact(window, cx, |this, window, cx| {
 8514            let buffer = this.buffer.update(cx, |buffer, cx| {
 8515                let empty_str: Arc<str> = Arc::default();
 8516                buffer.edit(
 8517                    edit_ranges
 8518                        .into_iter()
 8519                        .map(|range| (range, empty_str.clone())),
 8520                    None,
 8521                    cx,
 8522                );
 8523                buffer.snapshot(cx)
 8524            });
 8525            let new_selections = new_cursors
 8526                .into_iter()
 8527                .map(|(id, cursor)| {
 8528                    let cursor = cursor.to_point(&buffer);
 8529                    Selection {
 8530                        id,
 8531                        start: cursor,
 8532                        end: cursor,
 8533                        reversed: false,
 8534                        goal: SelectionGoal::None,
 8535                    }
 8536                })
 8537                .collect();
 8538
 8539            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8540                s.select(new_selections);
 8541            });
 8542        });
 8543    }
 8544
 8545    pub fn join_lines_impl(
 8546        &mut self,
 8547        insert_whitespace: bool,
 8548        window: &mut Window,
 8549        cx: &mut Context<Self>,
 8550    ) {
 8551        if self.read_only(cx) {
 8552            return;
 8553        }
 8554        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 8555        for selection in self.selections.all::<Point>(cx) {
 8556            let start = MultiBufferRow(selection.start.row);
 8557            // Treat single line selections as if they include the next line. Otherwise this action
 8558            // would do nothing for single line selections individual cursors.
 8559            let end = if selection.start.row == selection.end.row {
 8560                MultiBufferRow(selection.start.row + 1)
 8561            } else {
 8562                MultiBufferRow(selection.end.row)
 8563            };
 8564
 8565            if let Some(last_row_range) = row_ranges.last_mut() {
 8566                if start <= last_row_range.end {
 8567                    last_row_range.end = end;
 8568                    continue;
 8569                }
 8570            }
 8571            row_ranges.push(start..end);
 8572        }
 8573
 8574        let snapshot = self.buffer.read(cx).snapshot(cx);
 8575        let mut cursor_positions = Vec::new();
 8576        for row_range in &row_ranges {
 8577            let anchor = snapshot.anchor_before(Point::new(
 8578                row_range.end.previous_row().0,
 8579                snapshot.line_len(row_range.end.previous_row()),
 8580            ));
 8581            cursor_positions.push(anchor..anchor);
 8582        }
 8583
 8584        self.transact(window, cx, |this, window, cx| {
 8585            for row_range in row_ranges.into_iter().rev() {
 8586                for row in row_range.iter_rows().rev() {
 8587                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 8588                    let next_line_row = row.next_row();
 8589                    let indent = snapshot.indent_size_for_line(next_line_row);
 8590                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 8591
 8592                    let replace =
 8593                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 8594                            " "
 8595                        } else {
 8596                            ""
 8597                        };
 8598
 8599                    this.buffer.update(cx, |buffer, cx| {
 8600                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 8601                    });
 8602                }
 8603            }
 8604
 8605            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8606                s.select_anchor_ranges(cursor_positions)
 8607            });
 8608        });
 8609    }
 8610
 8611    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 8612        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8613        self.join_lines_impl(true, window, cx);
 8614    }
 8615
 8616    pub fn sort_lines_case_sensitive(
 8617        &mut self,
 8618        _: &SortLinesCaseSensitive,
 8619        window: &mut Window,
 8620        cx: &mut Context<Self>,
 8621    ) {
 8622        self.manipulate_lines(window, cx, |lines| lines.sort())
 8623    }
 8624
 8625    pub fn sort_lines_case_insensitive(
 8626        &mut self,
 8627        _: &SortLinesCaseInsensitive,
 8628        window: &mut Window,
 8629        cx: &mut Context<Self>,
 8630    ) {
 8631        self.manipulate_lines(window, cx, |lines| {
 8632            lines.sort_by_key(|line| line.to_lowercase())
 8633        })
 8634    }
 8635
 8636    pub fn unique_lines_case_insensitive(
 8637        &mut self,
 8638        _: &UniqueLinesCaseInsensitive,
 8639        window: &mut Window,
 8640        cx: &mut Context<Self>,
 8641    ) {
 8642        self.manipulate_lines(window, cx, |lines| {
 8643            let mut seen = HashSet::default();
 8644            lines.retain(|line| seen.insert(line.to_lowercase()));
 8645        })
 8646    }
 8647
 8648    pub fn unique_lines_case_sensitive(
 8649        &mut self,
 8650        _: &UniqueLinesCaseSensitive,
 8651        window: &mut Window,
 8652        cx: &mut Context<Self>,
 8653    ) {
 8654        self.manipulate_lines(window, cx, |lines| {
 8655            let mut seen = HashSet::default();
 8656            lines.retain(|line| seen.insert(*line));
 8657        })
 8658    }
 8659
 8660    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 8661        let Some(project) = self.project.clone() else {
 8662            return;
 8663        };
 8664        self.reload(project, window, cx)
 8665            .detach_and_notify_err(window, cx);
 8666    }
 8667
 8668    pub fn restore_file(
 8669        &mut self,
 8670        _: &::git::RestoreFile,
 8671        window: &mut Window,
 8672        cx: &mut Context<Self>,
 8673    ) {
 8674        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8675        let mut buffer_ids = HashSet::default();
 8676        let snapshot = self.buffer().read(cx).snapshot(cx);
 8677        for selection in self.selections.all::<usize>(cx) {
 8678            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 8679        }
 8680
 8681        let buffer = self.buffer().read(cx);
 8682        let ranges = buffer_ids
 8683            .into_iter()
 8684            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 8685            .collect::<Vec<_>>();
 8686
 8687        self.restore_hunks_in_ranges(ranges, window, cx);
 8688    }
 8689
 8690    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 8691        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8692        let selections = self
 8693            .selections
 8694            .all(cx)
 8695            .into_iter()
 8696            .map(|s| s.range())
 8697            .collect();
 8698        self.restore_hunks_in_ranges(selections, window, cx);
 8699    }
 8700
 8701    pub fn restore_hunks_in_ranges(
 8702        &mut self,
 8703        ranges: Vec<Range<Point>>,
 8704        window: &mut Window,
 8705        cx: &mut Context<Editor>,
 8706    ) {
 8707        let mut revert_changes = HashMap::default();
 8708        let chunk_by = self
 8709            .snapshot(window, cx)
 8710            .hunks_for_ranges(ranges)
 8711            .into_iter()
 8712            .chunk_by(|hunk| hunk.buffer_id);
 8713        for (buffer_id, hunks) in &chunk_by {
 8714            let hunks = hunks.collect::<Vec<_>>();
 8715            for hunk in &hunks {
 8716                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 8717            }
 8718            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
 8719        }
 8720        drop(chunk_by);
 8721        if !revert_changes.is_empty() {
 8722            self.transact(window, cx, |editor, window, cx| {
 8723                editor.restore(revert_changes, window, cx);
 8724            });
 8725        }
 8726    }
 8727
 8728    pub fn open_active_item_in_terminal(
 8729        &mut self,
 8730        _: &OpenInTerminal,
 8731        window: &mut Window,
 8732        cx: &mut Context<Self>,
 8733    ) {
 8734        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 8735            let project_path = buffer.read(cx).project_path(cx)?;
 8736            let project = self.project.as_ref()?.read(cx);
 8737            let entry = project.entry_for_path(&project_path, cx)?;
 8738            let parent = match &entry.canonical_path {
 8739                Some(canonical_path) => canonical_path.to_path_buf(),
 8740                None => project.absolute_path(&project_path, cx)?,
 8741            }
 8742            .parent()?
 8743            .to_path_buf();
 8744            Some(parent)
 8745        }) {
 8746            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 8747        }
 8748    }
 8749
 8750    fn set_breakpoint_context_menu(
 8751        &mut self,
 8752        display_row: DisplayRow,
 8753        position: Option<Anchor>,
 8754        clicked_point: gpui::Point<Pixels>,
 8755        window: &mut Window,
 8756        cx: &mut Context<Self>,
 8757    ) {
 8758        if !cx.has_flag::<Debugger>() {
 8759            return;
 8760        }
 8761        let source = self
 8762            .buffer
 8763            .read(cx)
 8764            .snapshot(cx)
 8765            .anchor_before(Point::new(display_row.0, 0u32));
 8766
 8767        let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
 8768
 8769        self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
 8770            self,
 8771            source,
 8772            clicked_point,
 8773            context_menu,
 8774            window,
 8775            cx,
 8776        );
 8777    }
 8778
 8779    fn add_edit_breakpoint_block(
 8780        &mut self,
 8781        anchor: Anchor,
 8782        breakpoint: &Breakpoint,
 8783        edit_action: BreakpointPromptEditAction,
 8784        window: &mut Window,
 8785        cx: &mut Context<Self>,
 8786    ) {
 8787        let weak_editor = cx.weak_entity();
 8788        let bp_prompt = cx.new(|cx| {
 8789            BreakpointPromptEditor::new(
 8790                weak_editor,
 8791                anchor,
 8792                breakpoint.clone(),
 8793                edit_action,
 8794                window,
 8795                cx,
 8796            )
 8797        });
 8798
 8799        let height = bp_prompt.update(cx, |this, cx| {
 8800            this.prompt
 8801                .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
 8802        });
 8803        let cloned_prompt = bp_prompt.clone();
 8804        let blocks = vec![BlockProperties {
 8805            style: BlockStyle::Sticky,
 8806            placement: BlockPlacement::Above(anchor),
 8807            height: Some(height),
 8808            render: Arc::new(move |cx| {
 8809                *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
 8810                cloned_prompt.clone().into_any_element()
 8811            }),
 8812            priority: 0,
 8813        }];
 8814
 8815        let focus_handle = bp_prompt.focus_handle(cx);
 8816        window.focus(&focus_handle);
 8817
 8818        let block_ids = self.insert_blocks(blocks, None, cx);
 8819        bp_prompt.update(cx, |prompt, _| {
 8820            prompt.add_block_ids(block_ids);
 8821        });
 8822    }
 8823
 8824    fn breakpoint_at_cursor_head(
 8825        &self,
 8826        window: &mut Window,
 8827        cx: &mut Context<Self>,
 8828    ) -> Option<(Anchor, Breakpoint)> {
 8829        let cursor_position: Point = self.selections.newest(cx).head();
 8830        self.breakpoint_at_row(cursor_position.row, window, cx)
 8831    }
 8832
 8833    pub(crate) fn breakpoint_at_row(
 8834        &self,
 8835        row: u32,
 8836        window: &mut Window,
 8837        cx: &mut Context<Self>,
 8838    ) -> Option<(Anchor, Breakpoint)> {
 8839        let snapshot = self.snapshot(window, cx);
 8840        let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
 8841
 8842        let project = self.project.clone()?;
 8843
 8844        let buffer_id = breakpoint_position.buffer_id.or_else(|| {
 8845            snapshot
 8846                .buffer_snapshot
 8847                .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
 8848        })?;
 8849
 8850        let enclosing_excerpt = breakpoint_position.excerpt_id;
 8851        let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
 8852        let buffer_snapshot = buffer.read(cx).snapshot();
 8853
 8854        let row = buffer_snapshot
 8855            .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
 8856            .row;
 8857
 8858        let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
 8859        let anchor_end = snapshot
 8860            .buffer_snapshot
 8861            .anchor_after(Point::new(row, line_len));
 8862
 8863        let bp = self
 8864            .breakpoint_store
 8865            .as_ref()?
 8866            .read_with(cx, |breakpoint_store, cx| {
 8867                breakpoint_store
 8868                    .breakpoints(
 8869                        &buffer,
 8870                        Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
 8871                        &buffer_snapshot,
 8872                        cx,
 8873                    )
 8874                    .next()
 8875                    .and_then(|(anchor, bp)| {
 8876                        let breakpoint_row = buffer_snapshot
 8877                            .summary_for_anchor::<text::PointUtf16>(anchor)
 8878                            .row;
 8879
 8880                        if breakpoint_row == row {
 8881                            snapshot
 8882                                .buffer_snapshot
 8883                                .anchor_in_excerpt(enclosing_excerpt, *anchor)
 8884                                .map(|anchor| (anchor, bp.clone()))
 8885                        } else {
 8886                            None
 8887                        }
 8888                    })
 8889            });
 8890        bp
 8891    }
 8892
 8893    pub fn edit_log_breakpoint(
 8894        &mut self,
 8895        _: &EditLogBreakpoint,
 8896        window: &mut Window,
 8897        cx: &mut Context<Self>,
 8898    ) {
 8899        let (anchor, bp) = self
 8900            .breakpoint_at_cursor_head(window, cx)
 8901            .unwrap_or_else(|| {
 8902                let cursor_position: Point = self.selections.newest(cx).head();
 8903
 8904                let breakpoint_position = self
 8905                    .snapshot(window, cx)
 8906                    .display_snapshot
 8907                    .buffer_snapshot
 8908                    .anchor_after(Point::new(cursor_position.row, 0));
 8909
 8910                (
 8911                    breakpoint_position,
 8912                    Breakpoint {
 8913                        message: None,
 8914                        state: BreakpointState::Enabled,
 8915                        condition: None,
 8916                        hit_condition: None,
 8917                    },
 8918                )
 8919            });
 8920
 8921        self.add_edit_breakpoint_block(anchor, &bp, BreakpointPromptEditAction::Log, window, cx);
 8922    }
 8923
 8924    pub fn enable_breakpoint(
 8925        &mut self,
 8926        _: &crate::actions::EnableBreakpoint,
 8927        window: &mut Window,
 8928        cx: &mut Context<Self>,
 8929    ) {
 8930        if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
 8931            if breakpoint.is_disabled() {
 8932                self.edit_breakpoint_at_anchor(
 8933                    anchor,
 8934                    breakpoint,
 8935                    BreakpointEditAction::InvertState,
 8936                    cx,
 8937                );
 8938            }
 8939        }
 8940    }
 8941
 8942    pub fn disable_breakpoint(
 8943        &mut self,
 8944        _: &crate::actions::DisableBreakpoint,
 8945        window: &mut Window,
 8946        cx: &mut Context<Self>,
 8947    ) {
 8948        if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
 8949            if breakpoint.is_enabled() {
 8950                self.edit_breakpoint_at_anchor(
 8951                    anchor,
 8952                    breakpoint,
 8953                    BreakpointEditAction::InvertState,
 8954                    cx,
 8955                );
 8956            }
 8957        }
 8958    }
 8959
 8960    pub fn toggle_breakpoint(
 8961        &mut self,
 8962        _: &crate::actions::ToggleBreakpoint,
 8963        window: &mut Window,
 8964        cx: &mut Context<Self>,
 8965    ) {
 8966        let edit_action = BreakpointEditAction::Toggle;
 8967
 8968        if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
 8969            self.edit_breakpoint_at_anchor(anchor, breakpoint, edit_action, cx);
 8970        } else {
 8971            let cursor_position: Point = self.selections.newest(cx).head();
 8972
 8973            let breakpoint_position = self
 8974                .snapshot(window, cx)
 8975                .display_snapshot
 8976                .buffer_snapshot
 8977                .anchor_after(Point::new(cursor_position.row, 0));
 8978
 8979            self.edit_breakpoint_at_anchor(
 8980                breakpoint_position,
 8981                Breakpoint::new_standard(),
 8982                edit_action,
 8983                cx,
 8984            );
 8985        }
 8986    }
 8987
 8988    pub fn edit_breakpoint_at_anchor(
 8989        &mut self,
 8990        breakpoint_position: Anchor,
 8991        breakpoint: Breakpoint,
 8992        edit_action: BreakpointEditAction,
 8993        cx: &mut Context<Self>,
 8994    ) {
 8995        let Some(breakpoint_store) = &self.breakpoint_store else {
 8996            return;
 8997        };
 8998
 8999        let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
 9000            if breakpoint_position == Anchor::min() {
 9001                self.buffer()
 9002                    .read(cx)
 9003                    .excerpt_buffer_ids()
 9004                    .into_iter()
 9005                    .next()
 9006            } else {
 9007                None
 9008            }
 9009        }) else {
 9010            return;
 9011        };
 9012
 9013        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
 9014            return;
 9015        };
 9016
 9017        breakpoint_store.update(cx, |breakpoint_store, cx| {
 9018            breakpoint_store.toggle_breakpoint(
 9019                buffer,
 9020                (breakpoint_position.text_anchor, breakpoint),
 9021                edit_action,
 9022                cx,
 9023            );
 9024        });
 9025
 9026        cx.notify();
 9027    }
 9028
 9029    #[cfg(any(test, feature = "test-support"))]
 9030    pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
 9031        self.breakpoint_store.clone()
 9032    }
 9033
 9034    pub fn prepare_restore_change(
 9035        &self,
 9036        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 9037        hunk: &MultiBufferDiffHunk,
 9038        cx: &mut App,
 9039    ) -> Option<()> {
 9040        if hunk.is_created_file() {
 9041            return None;
 9042        }
 9043        let buffer = self.buffer.read(cx);
 9044        let diff = buffer.diff_for(hunk.buffer_id)?;
 9045        let buffer = buffer.buffer(hunk.buffer_id)?;
 9046        let buffer = buffer.read(cx);
 9047        let original_text = diff
 9048            .read(cx)
 9049            .base_text()
 9050            .as_rope()
 9051            .slice(hunk.diff_base_byte_range.clone());
 9052        let buffer_snapshot = buffer.snapshot();
 9053        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 9054        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 9055            probe
 9056                .0
 9057                .start
 9058                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 9059                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 9060        }) {
 9061            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 9062            Some(())
 9063        } else {
 9064            None
 9065        }
 9066    }
 9067
 9068    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 9069        self.manipulate_lines(window, cx, |lines| lines.reverse())
 9070    }
 9071
 9072    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 9073        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 9074    }
 9075
 9076    fn manipulate_lines<Fn>(
 9077        &mut self,
 9078        window: &mut Window,
 9079        cx: &mut Context<Self>,
 9080        mut callback: Fn,
 9081    ) where
 9082        Fn: FnMut(&mut Vec<&str>),
 9083    {
 9084        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9085
 9086        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9087        let buffer = self.buffer.read(cx).snapshot(cx);
 9088
 9089        let mut edits = Vec::new();
 9090
 9091        let selections = self.selections.all::<Point>(cx);
 9092        let mut selections = selections.iter().peekable();
 9093        let mut contiguous_row_selections = Vec::new();
 9094        let mut new_selections = Vec::new();
 9095        let mut added_lines = 0;
 9096        let mut removed_lines = 0;
 9097
 9098        while let Some(selection) = selections.next() {
 9099            let (start_row, end_row) = consume_contiguous_rows(
 9100                &mut contiguous_row_selections,
 9101                selection,
 9102                &display_map,
 9103                &mut selections,
 9104            );
 9105
 9106            let start_point = Point::new(start_row.0, 0);
 9107            let end_point = Point::new(
 9108                end_row.previous_row().0,
 9109                buffer.line_len(end_row.previous_row()),
 9110            );
 9111            let text = buffer
 9112                .text_for_range(start_point..end_point)
 9113                .collect::<String>();
 9114
 9115            let mut lines = text.split('\n').collect_vec();
 9116
 9117            let lines_before = lines.len();
 9118            callback(&mut lines);
 9119            let lines_after = lines.len();
 9120
 9121            edits.push((start_point..end_point, lines.join("\n")));
 9122
 9123            // Selections must change based on added and removed line count
 9124            let start_row =
 9125                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 9126            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 9127            new_selections.push(Selection {
 9128                id: selection.id,
 9129                start: start_row,
 9130                end: end_row,
 9131                goal: SelectionGoal::None,
 9132                reversed: selection.reversed,
 9133            });
 9134
 9135            if lines_after > lines_before {
 9136                added_lines += lines_after - lines_before;
 9137            } else if lines_before > lines_after {
 9138                removed_lines += lines_before - lines_after;
 9139            }
 9140        }
 9141
 9142        self.transact(window, cx, |this, window, cx| {
 9143            let buffer = this.buffer.update(cx, |buffer, cx| {
 9144                buffer.edit(edits, None, cx);
 9145                buffer.snapshot(cx)
 9146            });
 9147
 9148            // Recalculate offsets on newly edited buffer
 9149            let new_selections = new_selections
 9150                .iter()
 9151                .map(|s| {
 9152                    let start_point = Point::new(s.start.0, 0);
 9153                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 9154                    Selection {
 9155                        id: s.id,
 9156                        start: buffer.point_to_offset(start_point),
 9157                        end: buffer.point_to_offset(end_point),
 9158                        goal: s.goal,
 9159                        reversed: s.reversed,
 9160                    }
 9161                })
 9162                .collect();
 9163
 9164            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9165                s.select(new_selections);
 9166            });
 9167
 9168            this.request_autoscroll(Autoscroll::fit(), cx);
 9169        });
 9170    }
 9171
 9172    pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
 9173        self.manipulate_text(window, cx, |text| {
 9174            let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
 9175            if has_upper_case_characters {
 9176                text.to_lowercase()
 9177            } else {
 9178                text.to_uppercase()
 9179            }
 9180        })
 9181    }
 9182
 9183    pub fn convert_to_upper_case(
 9184        &mut self,
 9185        _: &ConvertToUpperCase,
 9186        window: &mut Window,
 9187        cx: &mut Context<Self>,
 9188    ) {
 9189        self.manipulate_text(window, cx, |text| text.to_uppercase())
 9190    }
 9191
 9192    pub fn convert_to_lower_case(
 9193        &mut self,
 9194        _: &ConvertToLowerCase,
 9195        window: &mut Window,
 9196        cx: &mut Context<Self>,
 9197    ) {
 9198        self.manipulate_text(window, cx, |text| text.to_lowercase())
 9199    }
 9200
 9201    pub fn convert_to_title_case(
 9202        &mut self,
 9203        _: &ConvertToTitleCase,
 9204        window: &mut Window,
 9205        cx: &mut Context<Self>,
 9206    ) {
 9207        self.manipulate_text(window, cx, |text| {
 9208            text.split('\n')
 9209                .map(|line| line.to_case(Case::Title))
 9210                .join("\n")
 9211        })
 9212    }
 9213
 9214    pub fn convert_to_snake_case(
 9215        &mut self,
 9216        _: &ConvertToSnakeCase,
 9217        window: &mut Window,
 9218        cx: &mut Context<Self>,
 9219    ) {
 9220        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 9221    }
 9222
 9223    pub fn convert_to_kebab_case(
 9224        &mut self,
 9225        _: &ConvertToKebabCase,
 9226        window: &mut Window,
 9227        cx: &mut Context<Self>,
 9228    ) {
 9229        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 9230    }
 9231
 9232    pub fn convert_to_upper_camel_case(
 9233        &mut self,
 9234        _: &ConvertToUpperCamelCase,
 9235        window: &mut Window,
 9236        cx: &mut Context<Self>,
 9237    ) {
 9238        self.manipulate_text(window, cx, |text| {
 9239            text.split('\n')
 9240                .map(|line| line.to_case(Case::UpperCamel))
 9241                .join("\n")
 9242        })
 9243    }
 9244
 9245    pub fn convert_to_lower_camel_case(
 9246        &mut self,
 9247        _: &ConvertToLowerCamelCase,
 9248        window: &mut Window,
 9249        cx: &mut Context<Self>,
 9250    ) {
 9251        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 9252    }
 9253
 9254    pub fn convert_to_opposite_case(
 9255        &mut self,
 9256        _: &ConvertToOppositeCase,
 9257        window: &mut Window,
 9258        cx: &mut Context<Self>,
 9259    ) {
 9260        self.manipulate_text(window, cx, |text| {
 9261            text.chars()
 9262                .fold(String::with_capacity(text.len()), |mut t, c| {
 9263                    if c.is_uppercase() {
 9264                        t.extend(c.to_lowercase());
 9265                    } else {
 9266                        t.extend(c.to_uppercase());
 9267                    }
 9268                    t
 9269                })
 9270        })
 9271    }
 9272
 9273    pub fn convert_to_rot13(
 9274        &mut self,
 9275        _: &ConvertToRot13,
 9276        window: &mut Window,
 9277        cx: &mut Context<Self>,
 9278    ) {
 9279        self.manipulate_text(window, cx, |text| {
 9280            text.chars()
 9281                .map(|c| match c {
 9282                    'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
 9283                    'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
 9284                    _ => c,
 9285                })
 9286                .collect()
 9287        })
 9288    }
 9289
 9290    pub fn convert_to_rot47(
 9291        &mut self,
 9292        _: &ConvertToRot47,
 9293        window: &mut Window,
 9294        cx: &mut Context<Self>,
 9295    ) {
 9296        self.manipulate_text(window, cx, |text| {
 9297            text.chars()
 9298                .map(|c| {
 9299                    let code_point = c as u32;
 9300                    if code_point >= 33 && code_point <= 126 {
 9301                        return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
 9302                    }
 9303                    c
 9304                })
 9305                .collect()
 9306        })
 9307    }
 9308
 9309    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 9310    where
 9311        Fn: FnMut(&str) -> String,
 9312    {
 9313        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9314        let buffer = self.buffer.read(cx).snapshot(cx);
 9315
 9316        let mut new_selections = Vec::new();
 9317        let mut edits = Vec::new();
 9318        let mut selection_adjustment = 0i32;
 9319
 9320        for selection in self.selections.all::<usize>(cx) {
 9321            let selection_is_empty = selection.is_empty();
 9322
 9323            let (start, end) = if selection_is_empty {
 9324                let word_range = movement::surrounding_word(
 9325                    &display_map,
 9326                    selection.start.to_display_point(&display_map),
 9327                );
 9328                let start = word_range.start.to_offset(&display_map, Bias::Left);
 9329                let end = word_range.end.to_offset(&display_map, Bias::Left);
 9330                (start, end)
 9331            } else {
 9332                (selection.start, selection.end)
 9333            };
 9334
 9335            let text = buffer.text_for_range(start..end).collect::<String>();
 9336            let old_length = text.len() as i32;
 9337            let text = callback(&text);
 9338
 9339            new_selections.push(Selection {
 9340                start: (start as i32 - selection_adjustment) as usize,
 9341                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 9342                goal: SelectionGoal::None,
 9343                ..selection
 9344            });
 9345
 9346            selection_adjustment += old_length - text.len() as i32;
 9347
 9348            edits.push((start..end, text));
 9349        }
 9350
 9351        self.transact(window, cx, |this, window, cx| {
 9352            this.buffer.update(cx, |buffer, cx| {
 9353                buffer.edit(edits, None, cx);
 9354            });
 9355
 9356            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9357                s.select(new_selections);
 9358            });
 9359
 9360            this.request_autoscroll(Autoscroll::fit(), cx);
 9361        });
 9362    }
 9363
 9364    pub fn duplicate(
 9365        &mut self,
 9366        upwards: bool,
 9367        whole_lines: bool,
 9368        window: &mut Window,
 9369        cx: &mut Context<Self>,
 9370    ) {
 9371        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9372
 9373        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9374        let buffer = &display_map.buffer_snapshot;
 9375        let selections = self.selections.all::<Point>(cx);
 9376
 9377        let mut edits = Vec::new();
 9378        let mut selections_iter = selections.iter().peekable();
 9379        while let Some(selection) = selections_iter.next() {
 9380            let mut rows = selection.spanned_rows(false, &display_map);
 9381            // duplicate line-wise
 9382            if whole_lines || selection.start == selection.end {
 9383                // Avoid duplicating the same lines twice.
 9384                while let Some(next_selection) = selections_iter.peek() {
 9385                    let next_rows = next_selection.spanned_rows(false, &display_map);
 9386                    if next_rows.start < rows.end {
 9387                        rows.end = next_rows.end;
 9388                        selections_iter.next().unwrap();
 9389                    } else {
 9390                        break;
 9391                    }
 9392                }
 9393
 9394                // Copy the text from the selected row region and splice it either at the start
 9395                // or end of the region.
 9396                let start = Point::new(rows.start.0, 0);
 9397                let end = Point::new(
 9398                    rows.end.previous_row().0,
 9399                    buffer.line_len(rows.end.previous_row()),
 9400                );
 9401                let text = buffer
 9402                    .text_for_range(start..end)
 9403                    .chain(Some("\n"))
 9404                    .collect::<String>();
 9405                let insert_location = if upwards {
 9406                    Point::new(rows.end.0, 0)
 9407                } else {
 9408                    start
 9409                };
 9410                edits.push((insert_location..insert_location, text));
 9411            } else {
 9412                // duplicate character-wise
 9413                let start = selection.start;
 9414                let end = selection.end;
 9415                let text = buffer.text_for_range(start..end).collect::<String>();
 9416                edits.push((selection.end..selection.end, text));
 9417            }
 9418        }
 9419
 9420        self.transact(window, cx, |this, _, cx| {
 9421            this.buffer.update(cx, |buffer, cx| {
 9422                buffer.edit(edits, None, cx);
 9423            });
 9424
 9425            this.request_autoscroll(Autoscroll::fit(), cx);
 9426        });
 9427    }
 9428
 9429    pub fn duplicate_line_up(
 9430        &mut self,
 9431        _: &DuplicateLineUp,
 9432        window: &mut Window,
 9433        cx: &mut Context<Self>,
 9434    ) {
 9435        self.duplicate(true, true, window, cx);
 9436    }
 9437
 9438    pub fn duplicate_line_down(
 9439        &mut self,
 9440        _: &DuplicateLineDown,
 9441        window: &mut Window,
 9442        cx: &mut Context<Self>,
 9443    ) {
 9444        self.duplicate(false, true, window, cx);
 9445    }
 9446
 9447    pub fn duplicate_selection(
 9448        &mut self,
 9449        _: &DuplicateSelection,
 9450        window: &mut Window,
 9451        cx: &mut Context<Self>,
 9452    ) {
 9453        self.duplicate(false, false, window, cx);
 9454    }
 9455
 9456    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 9457        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9458
 9459        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9460        let buffer = self.buffer.read(cx).snapshot(cx);
 9461
 9462        let mut edits = Vec::new();
 9463        let mut unfold_ranges = Vec::new();
 9464        let mut refold_creases = Vec::new();
 9465
 9466        let selections = self.selections.all::<Point>(cx);
 9467        let mut selections = selections.iter().peekable();
 9468        let mut contiguous_row_selections = Vec::new();
 9469        let mut new_selections = Vec::new();
 9470
 9471        while let Some(selection) = selections.next() {
 9472            // Find all the selections that span a contiguous row range
 9473            let (start_row, end_row) = consume_contiguous_rows(
 9474                &mut contiguous_row_selections,
 9475                selection,
 9476                &display_map,
 9477                &mut selections,
 9478            );
 9479
 9480            // Move the text spanned by the row range to be before the line preceding the row range
 9481            if start_row.0 > 0 {
 9482                let range_to_move = Point::new(
 9483                    start_row.previous_row().0,
 9484                    buffer.line_len(start_row.previous_row()),
 9485                )
 9486                    ..Point::new(
 9487                        end_row.previous_row().0,
 9488                        buffer.line_len(end_row.previous_row()),
 9489                    );
 9490                let insertion_point = display_map
 9491                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 9492                    .0;
 9493
 9494                // Don't move lines across excerpts
 9495                if buffer
 9496                    .excerpt_containing(insertion_point..range_to_move.end)
 9497                    .is_some()
 9498                {
 9499                    let text = buffer
 9500                        .text_for_range(range_to_move.clone())
 9501                        .flat_map(|s| s.chars())
 9502                        .skip(1)
 9503                        .chain(['\n'])
 9504                        .collect::<String>();
 9505
 9506                    edits.push((
 9507                        buffer.anchor_after(range_to_move.start)
 9508                            ..buffer.anchor_before(range_to_move.end),
 9509                        String::new(),
 9510                    ));
 9511                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9512                    edits.push((insertion_anchor..insertion_anchor, text));
 9513
 9514                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 9515
 9516                    // Move selections up
 9517                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9518                        |mut selection| {
 9519                            selection.start.row -= row_delta;
 9520                            selection.end.row -= row_delta;
 9521                            selection
 9522                        },
 9523                    ));
 9524
 9525                    // Move folds up
 9526                    unfold_ranges.push(range_to_move.clone());
 9527                    for fold in display_map.folds_in_range(
 9528                        buffer.anchor_before(range_to_move.start)
 9529                            ..buffer.anchor_after(range_to_move.end),
 9530                    ) {
 9531                        let mut start = fold.range.start.to_point(&buffer);
 9532                        let mut end = fold.range.end.to_point(&buffer);
 9533                        start.row -= row_delta;
 9534                        end.row -= row_delta;
 9535                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9536                    }
 9537                }
 9538            }
 9539
 9540            // If we didn't move line(s), preserve the existing selections
 9541            new_selections.append(&mut contiguous_row_selections);
 9542        }
 9543
 9544        self.transact(window, cx, |this, window, cx| {
 9545            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9546            this.buffer.update(cx, |buffer, cx| {
 9547                for (range, text) in edits {
 9548                    buffer.edit([(range, text)], None, cx);
 9549                }
 9550            });
 9551            this.fold_creases(refold_creases, true, window, cx);
 9552            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9553                s.select(new_selections);
 9554            })
 9555        });
 9556    }
 9557
 9558    pub fn move_line_down(
 9559        &mut self,
 9560        _: &MoveLineDown,
 9561        window: &mut Window,
 9562        cx: &mut Context<Self>,
 9563    ) {
 9564        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9565
 9566        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9567        let buffer = self.buffer.read(cx).snapshot(cx);
 9568
 9569        let mut edits = Vec::new();
 9570        let mut unfold_ranges = Vec::new();
 9571        let mut refold_creases = Vec::new();
 9572
 9573        let selections = self.selections.all::<Point>(cx);
 9574        let mut selections = selections.iter().peekable();
 9575        let mut contiguous_row_selections = Vec::new();
 9576        let mut new_selections = Vec::new();
 9577
 9578        while let Some(selection) = selections.next() {
 9579            // Find all the selections that span a contiguous row range
 9580            let (start_row, end_row) = consume_contiguous_rows(
 9581                &mut contiguous_row_selections,
 9582                selection,
 9583                &display_map,
 9584                &mut selections,
 9585            );
 9586
 9587            // Move the text spanned by the row range to be after the last line of the row range
 9588            if end_row.0 <= buffer.max_point().row {
 9589                let range_to_move =
 9590                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 9591                let insertion_point = display_map
 9592                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 9593                    .0;
 9594
 9595                // Don't move lines across excerpt boundaries
 9596                if buffer
 9597                    .excerpt_containing(range_to_move.start..insertion_point)
 9598                    .is_some()
 9599                {
 9600                    let mut text = String::from("\n");
 9601                    text.extend(buffer.text_for_range(range_to_move.clone()));
 9602                    text.pop(); // Drop trailing newline
 9603                    edits.push((
 9604                        buffer.anchor_after(range_to_move.start)
 9605                            ..buffer.anchor_before(range_to_move.end),
 9606                        String::new(),
 9607                    ));
 9608                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9609                    edits.push((insertion_anchor..insertion_anchor, text));
 9610
 9611                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 9612
 9613                    // Move selections down
 9614                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9615                        |mut selection| {
 9616                            selection.start.row += row_delta;
 9617                            selection.end.row += row_delta;
 9618                            selection
 9619                        },
 9620                    ));
 9621
 9622                    // Move folds down
 9623                    unfold_ranges.push(range_to_move.clone());
 9624                    for fold in display_map.folds_in_range(
 9625                        buffer.anchor_before(range_to_move.start)
 9626                            ..buffer.anchor_after(range_to_move.end),
 9627                    ) {
 9628                        let mut start = fold.range.start.to_point(&buffer);
 9629                        let mut end = fold.range.end.to_point(&buffer);
 9630                        start.row += row_delta;
 9631                        end.row += row_delta;
 9632                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9633                    }
 9634                }
 9635            }
 9636
 9637            // If we didn't move line(s), preserve the existing selections
 9638            new_selections.append(&mut contiguous_row_selections);
 9639        }
 9640
 9641        self.transact(window, cx, |this, window, cx| {
 9642            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9643            this.buffer.update(cx, |buffer, cx| {
 9644                for (range, text) in edits {
 9645                    buffer.edit([(range, text)], None, cx);
 9646                }
 9647            });
 9648            this.fold_creases(refold_creases, true, window, cx);
 9649            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9650                s.select(new_selections)
 9651            });
 9652        });
 9653    }
 9654
 9655    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 9656        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9657        let text_layout_details = &self.text_layout_details(window);
 9658        self.transact(window, cx, |this, window, cx| {
 9659            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9660                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 9661                s.move_with(|display_map, selection| {
 9662                    if !selection.is_empty() {
 9663                        return;
 9664                    }
 9665
 9666                    let mut head = selection.head();
 9667                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 9668                    if head.column() == display_map.line_len(head.row()) {
 9669                        transpose_offset = display_map
 9670                            .buffer_snapshot
 9671                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9672                    }
 9673
 9674                    if transpose_offset == 0 {
 9675                        return;
 9676                    }
 9677
 9678                    *head.column_mut() += 1;
 9679                    head = display_map.clip_point(head, Bias::Right);
 9680                    let goal = SelectionGoal::HorizontalPosition(
 9681                        display_map
 9682                            .x_for_display_point(head, text_layout_details)
 9683                            .into(),
 9684                    );
 9685                    selection.collapse_to(head, goal);
 9686
 9687                    let transpose_start = display_map
 9688                        .buffer_snapshot
 9689                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9690                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 9691                        let transpose_end = display_map
 9692                            .buffer_snapshot
 9693                            .clip_offset(transpose_offset + 1, Bias::Right);
 9694                        if let Some(ch) =
 9695                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 9696                        {
 9697                            edits.push((transpose_start..transpose_offset, String::new()));
 9698                            edits.push((transpose_end..transpose_end, ch.to_string()));
 9699                        }
 9700                    }
 9701                });
 9702                edits
 9703            });
 9704            this.buffer
 9705                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 9706            let selections = this.selections.all::<usize>(cx);
 9707            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9708                s.select(selections);
 9709            });
 9710        });
 9711    }
 9712
 9713    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 9714        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9715        self.rewrap_impl(RewrapOptions::default(), cx)
 9716    }
 9717
 9718    pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
 9719        let buffer = self.buffer.read(cx).snapshot(cx);
 9720        let selections = self.selections.all::<Point>(cx);
 9721        let mut selections = selections.iter().peekable();
 9722
 9723        let mut edits = Vec::new();
 9724        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 9725
 9726        while let Some(selection) = selections.next() {
 9727            let mut start_row = selection.start.row;
 9728            let mut end_row = selection.end.row;
 9729
 9730            // Skip selections that overlap with a range that has already been rewrapped.
 9731            let selection_range = start_row..end_row;
 9732            if rewrapped_row_ranges
 9733                .iter()
 9734                .any(|range| range.overlaps(&selection_range))
 9735            {
 9736                continue;
 9737            }
 9738
 9739            let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
 9740
 9741            // Since not all lines in the selection may be at the same indent
 9742            // level, choose the indent size that is the most common between all
 9743            // of the lines.
 9744            //
 9745            // If there is a tie, we use the deepest indent.
 9746            let (indent_size, indent_end) = {
 9747                let mut indent_size_occurrences = HashMap::default();
 9748                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 9749
 9750                for row in start_row..=end_row {
 9751                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 9752                    rows_by_indent_size.entry(indent).or_default().push(row);
 9753                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 9754                }
 9755
 9756                let indent_size = indent_size_occurrences
 9757                    .into_iter()
 9758                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 9759                    .map(|(indent, _)| indent)
 9760                    .unwrap_or_default();
 9761                let row = rows_by_indent_size[&indent_size][0];
 9762                let indent_end = Point::new(row, indent_size.len);
 9763
 9764                (indent_size, indent_end)
 9765            };
 9766
 9767            let mut line_prefix = indent_size.chars().collect::<String>();
 9768
 9769            let mut inside_comment = false;
 9770            if let Some(comment_prefix) =
 9771                buffer
 9772                    .language_scope_at(selection.head())
 9773                    .and_then(|language| {
 9774                        language
 9775                            .line_comment_prefixes()
 9776                            .iter()
 9777                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 9778                            .cloned()
 9779                    })
 9780            {
 9781                line_prefix.push_str(&comment_prefix);
 9782                inside_comment = true;
 9783            }
 9784
 9785            let language_settings = buffer.language_settings_at(selection.head(), cx);
 9786            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 9787                RewrapBehavior::InComments => inside_comment,
 9788                RewrapBehavior::InSelections => !selection.is_empty(),
 9789                RewrapBehavior::Anywhere => true,
 9790            };
 9791
 9792            let should_rewrap = options.override_language_settings
 9793                || allow_rewrap_based_on_language
 9794                || self.hard_wrap.is_some();
 9795            if !should_rewrap {
 9796                continue;
 9797            }
 9798
 9799            if selection.is_empty() {
 9800                'expand_upwards: while start_row > 0 {
 9801                    let prev_row = start_row - 1;
 9802                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 9803                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 9804                    {
 9805                        start_row = prev_row;
 9806                    } else {
 9807                        break 'expand_upwards;
 9808                    }
 9809                }
 9810
 9811                'expand_downwards: while end_row < buffer.max_point().row {
 9812                    let next_row = end_row + 1;
 9813                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 9814                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 9815                    {
 9816                        end_row = next_row;
 9817                    } else {
 9818                        break 'expand_downwards;
 9819                    }
 9820                }
 9821            }
 9822
 9823            let start = Point::new(start_row, 0);
 9824            let start_offset = start.to_offset(&buffer);
 9825            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 9826            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 9827            let Some(lines_without_prefixes) = selection_text
 9828                .lines()
 9829                .map(|line| {
 9830                    line.strip_prefix(&line_prefix)
 9831                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 9832                        .ok_or_else(|| {
 9833                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 9834                        })
 9835                })
 9836                .collect::<Result<Vec<_>, _>>()
 9837                .log_err()
 9838            else {
 9839                continue;
 9840            };
 9841
 9842            let wrap_column = self.hard_wrap.unwrap_or_else(|| {
 9843                buffer
 9844                    .language_settings_at(Point::new(start_row, 0), cx)
 9845                    .preferred_line_length as usize
 9846            });
 9847            let wrapped_text = wrap_with_prefix(
 9848                line_prefix,
 9849                lines_without_prefixes.join("\n"),
 9850                wrap_column,
 9851                tab_size,
 9852                options.preserve_existing_whitespace,
 9853            );
 9854
 9855            // TODO: should always use char-based diff while still supporting cursor behavior that
 9856            // matches vim.
 9857            let mut diff_options = DiffOptions::default();
 9858            if options.override_language_settings {
 9859                diff_options.max_word_diff_len = 0;
 9860                diff_options.max_word_diff_line_count = 0;
 9861            } else {
 9862                diff_options.max_word_diff_len = usize::MAX;
 9863                diff_options.max_word_diff_line_count = usize::MAX;
 9864            }
 9865
 9866            for (old_range, new_text) in
 9867                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
 9868            {
 9869                let edit_start = buffer.anchor_after(start_offset + old_range.start);
 9870                let edit_end = buffer.anchor_after(start_offset + old_range.end);
 9871                edits.push((edit_start..edit_end, new_text));
 9872            }
 9873
 9874            rewrapped_row_ranges.push(start_row..=end_row);
 9875        }
 9876
 9877        self.buffer
 9878            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 9879    }
 9880
 9881    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 9882        let mut text = String::new();
 9883        let buffer = self.buffer.read(cx).snapshot(cx);
 9884        let mut selections = self.selections.all::<Point>(cx);
 9885        let mut clipboard_selections = Vec::with_capacity(selections.len());
 9886        {
 9887            let max_point = buffer.max_point();
 9888            let mut is_first = true;
 9889            for selection in &mut selections {
 9890                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 9891                if is_entire_line {
 9892                    selection.start = Point::new(selection.start.row, 0);
 9893                    if !selection.is_empty() && selection.end.column == 0 {
 9894                        selection.end = cmp::min(max_point, selection.end);
 9895                    } else {
 9896                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 9897                    }
 9898                    selection.goal = SelectionGoal::None;
 9899                }
 9900                if is_first {
 9901                    is_first = false;
 9902                } else {
 9903                    text += "\n";
 9904                }
 9905                let mut len = 0;
 9906                for chunk in buffer.text_for_range(selection.start..selection.end) {
 9907                    text.push_str(chunk);
 9908                    len += chunk.len();
 9909                }
 9910                clipboard_selections.push(ClipboardSelection {
 9911                    len,
 9912                    is_entire_line,
 9913                    first_line_indent: buffer
 9914                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 9915                        .len,
 9916                });
 9917            }
 9918        }
 9919
 9920        self.transact(window, cx, |this, window, cx| {
 9921            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9922                s.select(selections);
 9923            });
 9924            this.insert("", window, cx);
 9925        });
 9926        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 9927    }
 9928
 9929    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 9930        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9931        let item = self.cut_common(window, cx);
 9932        cx.write_to_clipboard(item);
 9933    }
 9934
 9935    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 9936        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9937        self.change_selections(None, window, cx, |s| {
 9938            s.move_with(|snapshot, sel| {
 9939                if sel.is_empty() {
 9940                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 9941                }
 9942            });
 9943        });
 9944        let item = self.cut_common(window, cx);
 9945        cx.set_global(KillRing(item))
 9946    }
 9947
 9948    pub fn kill_ring_yank(
 9949        &mut self,
 9950        _: &KillRingYank,
 9951        window: &mut Window,
 9952        cx: &mut Context<Self>,
 9953    ) {
 9954        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9955        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 9956            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 9957                (kill_ring.text().to_string(), kill_ring.metadata_json())
 9958            } else {
 9959                return;
 9960            }
 9961        } else {
 9962            return;
 9963        };
 9964        self.do_paste(&text, metadata, false, window, cx);
 9965    }
 9966
 9967    pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
 9968        self.do_copy(true, cx);
 9969    }
 9970
 9971    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 9972        self.do_copy(false, cx);
 9973    }
 9974
 9975    fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
 9976        let selections = self.selections.all::<Point>(cx);
 9977        let buffer = self.buffer.read(cx).read(cx);
 9978        let mut text = String::new();
 9979
 9980        let mut clipboard_selections = Vec::with_capacity(selections.len());
 9981        {
 9982            let max_point = buffer.max_point();
 9983            let mut is_first = true;
 9984            for selection in &selections {
 9985                let mut start = selection.start;
 9986                let mut end = selection.end;
 9987                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 9988                if is_entire_line {
 9989                    start = Point::new(start.row, 0);
 9990                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 9991                }
 9992
 9993                let mut trimmed_selections = Vec::new();
 9994                if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
 9995                    let row = MultiBufferRow(start.row);
 9996                    let first_indent = buffer.indent_size_for_line(row);
 9997                    if first_indent.len == 0 || start.column > first_indent.len {
 9998                        trimmed_selections.push(start..end);
 9999                    } else {
10000                        trimmed_selections.push(
10001                            Point::new(row.0, first_indent.len)
10002                                ..Point::new(row.0, buffer.line_len(row)),
10003                        );
10004                        for row in start.row + 1..=end.row {
10005                            let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10006                            if row_indent_size.len >= first_indent.len {
10007                                trimmed_selections.push(
10008                                    Point::new(row, first_indent.len)
10009                                        ..Point::new(row, buffer.line_len(MultiBufferRow(row))),
10010                                );
10011                            } else {
10012                                trimmed_selections.clear();
10013                                trimmed_selections.push(start..end);
10014                                break;
10015                            }
10016                        }
10017                    }
10018                } else {
10019                    trimmed_selections.push(start..end);
10020                }
10021
10022                for trimmed_range in trimmed_selections {
10023                    if is_first {
10024                        is_first = false;
10025                    } else {
10026                        text += "\n";
10027                    }
10028                    let mut len = 0;
10029                    for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10030                        text.push_str(chunk);
10031                        len += chunk.len();
10032                    }
10033                    clipboard_selections.push(ClipboardSelection {
10034                        len,
10035                        is_entire_line,
10036                        first_line_indent: buffer
10037                            .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10038                            .len,
10039                    });
10040                }
10041            }
10042        }
10043
10044        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10045            text,
10046            clipboard_selections,
10047        ));
10048    }
10049
10050    pub fn do_paste(
10051        &mut self,
10052        text: &String,
10053        clipboard_selections: Option<Vec<ClipboardSelection>>,
10054        handle_entire_lines: bool,
10055        window: &mut Window,
10056        cx: &mut Context<Self>,
10057    ) {
10058        if self.read_only(cx) {
10059            return;
10060        }
10061
10062        let clipboard_text = Cow::Borrowed(text);
10063
10064        self.transact(window, cx, |this, window, cx| {
10065            if let Some(mut clipboard_selections) = clipboard_selections {
10066                let old_selections = this.selections.all::<usize>(cx);
10067                let all_selections_were_entire_line =
10068                    clipboard_selections.iter().all(|s| s.is_entire_line);
10069                let first_selection_indent_column =
10070                    clipboard_selections.first().map(|s| s.first_line_indent);
10071                if clipboard_selections.len() != old_selections.len() {
10072                    clipboard_selections.drain(..);
10073                }
10074                let cursor_offset = this.selections.last::<usize>(cx).head();
10075                let mut auto_indent_on_paste = true;
10076
10077                this.buffer.update(cx, |buffer, cx| {
10078                    let snapshot = buffer.read(cx);
10079                    auto_indent_on_paste = snapshot
10080                        .language_settings_at(cursor_offset, cx)
10081                        .auto_indent_on_paste;
10082
10083                    let mut start_offset = 0;
10084                    let mut edits = Vec::new();
10085                    let mut original_indent_columns = Vec::new();
10086                    for (ix, selection) in old_selections.iter().enumerate() {
10087                        let to_insert;
10088                        let entire_line;
10089                        let original_indent_column;
10090                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10091                            let end_offset = start_offset + clipboard_selection.len;
10092                            to_insert = &clipboard_text[start_offset..end_offset];
10093                            entire_line = clipboard_selection.is_entire_line;
10094                            start_offset = end_offset + 1;
10095                            original_indent_column = Some(clipboard_selection.first_line_indent);
10096                        } else {
10097                            to_insert = clipboard_text.as_str();
10098                            entire_line = all_selections_were_entire_line;
10099                            original_indent_column = first_selection_indent_column
10100                        }
10101
10102                        // If the corresponding selection was empty when this slice of the
10103                        // clipboard text was written, then the entire line containing the
10104                        // selection was copied. If this selection is also currently empty,
10105                        // then paste the line before the current line of the buffer.
10106                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
10107                            let column = selection.start.to_point(&snapshot).column as usize;
10108                            let line_start = selection.start - column;
10109                            line_start..line_start
10110                        } else {
10111                            selection.range()
10112                        };
10113
10114                        edits.push((range, to_insert));
10115                        original_indent_columns.push(original_indent_column);
10116                    }
10117                    drop(snapshot);
10118
10119                    buffer.edit(
10120                        edits,
10121                        if auto_indent_on_paste {
10122                            Some(AutoindentMode::Block {
10123                                original_indent_columns,
10124                            })
10125                        } else {
10126                            None
10127                        },
10128                        cx,
10129                    );
10130                });
10131
10132                let selections = this.selections.all::<usize>(cx);
10133                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10134                    s.select(selections)
10135                });
10136            } else {
10137                this.insert(&clipboard_text, window, cx);
10138            }
10139        });
10140    }
10141
10142    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10143        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10144        if let Some(item) = cx.read_from_clipboard() {
10145            let entries = item.entries();
10146
10147            match entries.first() {
10148                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10149                // of all the pasted entries.
10150                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10151                    .do_paste(
10152                        clipboard_string.text(),
10153                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10154                        true,
10155                        window,
10156                        cx,
10157                    ),
10158                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10159            }
10160        }
10161    }
10162
10163    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10164        if self.read_only(cx) {
10165            return;
10166        }
10167
10168        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10169
10170        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10171            if let Some((selections, _)) =
10172                self.selection_history.transaction(transaction_id).cloned()
10173            {
10174                self.change_selections(None, window, cx, |s| {
10175                    s.select_anchors(selections.to_vec());
10176                });
10177            } else {
10178                log::error!(
10179                    "No entry in selection_history found for undo. \
10180                     This may correspond to a bug where undo does not update the selection. \
10181                     If this is occurring, please add details to \
10182                     https://github.com/zed-industries/zed/issues/22692"
10183                );
10184            }
10185            self.request_autoscroll(Autoscroll::fit(), cx);
10186            self.unmark_text(window, cx);
10187            self.refresh_inline_completion(true, false, window, cx);
10188            cx.emit(EditorEvent::Edited { transaction_id });
10189            cx.emit(EditorEvent::TransactionUndone { transaction_id });
10190        }
10191    }
10192
10193    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10194        if self.read_only(cx) {
10195            return;
10196        }
10197
10198        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10199
10200        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10201            if let Some((_, Some(selections))) =
10202                self.selection_history.transaction(transaction_id).cloned()
10203            {
10204                self.change_selections(None, window, cx, |s| {
10205                    s.select_anchors(selections.to_vec());
10206                });
10207            } else {
10208                log::error!(
10209                    "No entry in selection_history found for redo. \
10210                     This may correspond to a bug where undo does not update the selection. \
10211                     If this is occurring, please add details to \
10212                     https://github.com/zed-industries/zed/issues/22692"
10213                );
10214            }
10215            self.request_autoscroll(Autoscroll::fit(), cx);
10216            self.unmark_text(window, cx);
10217            self.refresh_inline_completion(true, false, window, cx);
10218            cx.emit(EditorEvent::Edited { transaction_id });
10219        }
10220    }
10221
10222    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10223        self.buffer
10224            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10225    }
10226
10227    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10228        self.buffer
10229            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10230    }
10231
10232    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10233        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10234        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10235            s.move_with(|map, selection| {
10236                let cursor = if selection.is_empty() {
10237                    movement::left(map, selection.start)
10238                } else {
10239                    selection.start
10240                };
10241                selection.collapse_to(cursor, SelectionGoal::None);
10242            });
10243        })
10244    }
10245
10246    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10247        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10248        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10249            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10250        })
10251    }
10252
10253    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10254        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10255        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10256            s.move_with(|map, selection| {
10257                let cursor = if selection.is_empty() {
10258                    movement::right(map, selection.end)
10259                } else {
10260                    selection.end
10261                };
10262                selection.collapse_to(cursor, SelectionGoal::None)
10263            });
10264        })
10265    }
10266
10267    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10268        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10269        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10270            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10271        })
10272    }
10273
10274    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10275        if self.take_rename(true, window, cx).is_some() {
10276            return;
10277        }
10278
10279        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10280            cx.propagate();
10281            return;
10282        }
10283
10284        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10285
10286        let text_layout_details = &self.text_layout_details(window);
10287        let selection_count = self.selections.count();
10288        let first_selection = self.selections.first_anchor();
10289
10290        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10291            s.move_with(|map, selection| {
10292                if !selection.is_empty() {
10293                    selection.goal = SelectionGoal::None;
10294                }
10295                let (cursor, goal) = movement::up(
10296                    map,
10297                    selection.start,
10298                    selection.goal,
10299                    false,
10300                    text_layout_details,
10301                );
10302                selection.collapse_to(cursor, goal);
10303            });
10304        });
10305
10306        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10307        {
10308            cx.propagate();
10309        }
10310    }
10311
10312    pub fn move_up_by_lines(
10313        &mut self,
10314        action: &MoveUpByLines,
10315        window: &mut Window,
10316        cx: &mut Context<Self>,
10317    ) {
10318        if self.take_rename(true, window, cx).is_some() {
10319            return;
10320        }
10321
10322        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10323            cx.propagate();
10324            return;
10325        }
10326
10327        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10328
10329        let text_layout_details = &self.text_layout_details(window);
10330
10331        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10332            s.move_with(|map, selection| {
10333                if !selection.is_empty() {
10334                    selection.goal = SelectionGoal::None;
10335                }
10336                let (cursor, goal) = movement::up_by_rows(
10337                    map,
10338                    selection.start,
10339                    action.lines,
10340                    selection.goal,
10341                    false,
10342                    text_layout_details,
10343                );
10344                selection.collapse_to(cursor, goal);
10345            });
10346        })
10347    }
10348
10349    pub fn move_down_by_lines(
10350        &mut self,
10351        action: &MoveDownByLines,
10352        window: &mut Window,
10353        cx: &mut Context<Self>,
10354    ) {
10355        if self.take_rename(true, window, cx).is_some() {
10356            return;
10357        }
10358
10359        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10360            cx.propagate();
10361            return;
10362        }
10363
10364        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10365
10366        let text_layout_details = &self.text_layout_details(window);
10367
10368        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10369            s.move_with(|map, selection| {
10370                if !selection.is_empty() {
10371                    selection.goal = SelectionGoal::None;
10372                }
10373                let (cursor, goal) = movement::down_by_rows(
10374                    map,
10375                    selection.start,
10376                    action.lines,
10377                    selection.goal,
10378                    false,
10379                    text_layout_details,
10380                );
10381                selection.collapse_to(cursor, goal);
10382            });
10383        })
10384    }
10385
10386    pub fn select_down_by_lines(
10387        &mut self,
10388        action: &SelectDownByLines,
10389        window: &mut Window,
10390        cx: &mut Context<Self>,
10391    ) {
10392        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10393        let text_layout_details = &self.text_layout_details(window);
10394        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10395            s.move_heads_with(|map, head, goal| {
10396                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10397            })
10398        })
10399    }
10400
10401    pub fn select_up_by_lines(
10402        &mut self,
10403        action: &SelectUpByLines,
10404        window: &mut Window,
10405        cx: &mut Context<Self>,
10406    ) {
10407        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10408        let text_layout_details = &self.text_layout_details(window);
10409        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10410            s.move_heads_with(|map, head, goal| {
10411                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10412            })
10413        })
10414    }
10415
10416    pub fn select_page_up(
10417        &mut self,
10418        _: &SelectPageUp,
10419        window: &mut Window,
10420        cx: &mut Context<Self>,
10421    ) {
10422        let Some(row_count) = self.visible_row_count() else {
10423            return;
10424        };
10425
10426        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10427
10428        let text_layout_details = &self.text_layout_details(window);
10429
10430        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10431            s.move_heads_with(|map, head, goal| {
10432                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10433            })
10434        })
10435    }
10436
10437    pub fn move_page_up(
10438        &mut self,
10439        action: &MovePageUp,
10440        window: &mut Window,
10441        cx: &mut Context<Self>,
10442    ) {
10443        if self.take_rename(true, window, cx).is_some() {
10444            return;
10445        }
10446
10447        if self
10448            .context_menu
10449            .borrow_mut()
10450            .as_mut()
10451            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10452            .unwrap_or(false)
10453        {
10454            return;
10455        }
10456
10457        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10458            cx.propagate();
10459            return;
10460        }
10461
10462        let Some(row_count) = self.visible_row_count() else {
10463            return;
10464        };
10465
10466        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10467
10468        let autoscroll = if action.center_cursor {
10469            Autoscroll::center()
10470        } else {
10471            Autoscroll::fit()
10472        };
10473
10474        let text_layout_details = &self.text_layout_details(window);
10475
10476        self.change_selections(Some(autoscroll), window, cx, |s| {
10477            s.move_with(|map, selection| {
10478                if !selection.is_empty() {
10479                    selection.goal = SelectionGoal::None;
10480                }
10481                let (cursor, goal) = movement::up_by_rows(
10482                    map,
10483                    selection.end,
10484                    row_count,
10485                    selection.goal,
10486                    false,
10487                    text_layout_details,
10488                );
10489                selection.collapse_to(cursor, goal);
10490            });
10491        });
10492    }
10493
10494    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10495        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10496        let text_layout_details = &self.text_layout_details(window);
10497        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10498            s.move_heads_with(|map, head, goal| {
10499                movement::up(map, head, goal, false, text_layout_details)
10500            })
10501        })
10502    }
10503
10504    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10505        self.take_rename(true, window, cx);
10506
10507        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10508            cx.propagate();
10509            return;
10510        }
10511
10512        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10513
10514        let text_layout_details = &self.text_layout_details(window);
10515        let selection_count = self.selections.count();
10516        let first_selection = self.selections.first_anchor();
10517
10518        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10519            s.move_with(|map, selection| {
10520                if !selection.is_empty() {
10521                    selection.goal = SelectionGoal::None;
10522                }
10523                let (cursor, goal) = movement::down(
10524                    map,
10525                    selection.end,
10526                    selection.goal,
10527                    false,
10528                    text_layout_details,
10529                );
10530                selection.collapse_to(cursor, goal);
10531            });
10532        });
10533
10534        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10535        {
10536            cx.propagate();
10537        }
10538    }
10539
10540    pub fn select_page_down(
10541        &mut self,
10542        _: &SelectPageDown,
10543        window: &mut Window,
10544        cx: &mut Context<Self>,
10545    ) {
10546        let Some(row_count) = self.visible_row_count() else {
10547            return;
10548        };
10549
10550        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10551
10552        let text_layout_details = &self.text_layout_details(window);
10553
10554        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10555            s.move_heads_with(|map, head, goal| {
10556                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10557            })
10558        })
10559    }
10560
10561    pub fn move_page_down(
10562        &mut self,
10563        action: &MovePageDown,
10564        window: &mut Window,
10565        cx: &mut Context<Self>,
10566    ) {
10567        if self.take_rename(true, window, cx).is_some() {
10568            return;
10569        }
10570
10571        if self
10572            .context_menu
10573            .borrow_mut()
10574            .as_mut()
10575            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10576            .unwrap_or(false)
10577        {
10578            return;
10579        }
10580
10581        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10582            cx.propagate();
10583            return;
10584        }
10585
10586        let Some(row_count) = self.visible_row_count() else {
10587            return;
10588        };
10589
10590        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10591
10592        let autoscroll = if action.center_cursor {
10593            Autoscroll::center()
10594        } else {
10595            Autoscroll::fit()
10596        };
10597
10598        let text_layout_details = &self.text_layout_details(window);
10599        self.change_selections(Some(autoscroll), window, cx, |s| {
10600            s.move_with(|map, selection| {
10601                if !selection.is_empty() {
10602                    selection.goal = SelectionGoal::None;
10603                }
10604                let (cursor, goal) = movement::down_by_rows(
10605                    map,
10606                    selection.end,
10607                    row_count,
10608                    selection.goal,
10609                    false,
10610                    text_layout_details,
10611                );
10612                selection.collapse_to(cursor, goal);
10613            });
10614        });
10615    }
10616
10617    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10618        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10619        let text_layout_details = &self.text_layout_details(window);
10620        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10621            s.move_heads_with(|map, head, goal| {
10622                movement::down(map, head, goal, false, text_layout_details)
10623            })
10624        });
10625    }
10626
10627    pub fn context_menu_first(
10628        &mut self,
10629        _: &ContextMenuFirst,
10630        _window: &mut Window,
10631        cx: &mut Context<Self>,
10632    ) {
10633        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10634            context_menu.select_first(self.completion_provider.as_deref(), cx);
10635        }
10636    }
10637
10638    pub fn context_menu_prev(
10639        &mut self,
10640        _: &ContextMenuPrevious,
10641        _window: &mut Window,
10642        cx: &mut Context<Self>,
10643    ) {
10644        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10645            context_menu.select_prev(self.completion_provider.as_deref(), cx);
10646        }
10647    }
10648
10649    pub fn context_menu_next(
10650        &mut self,
10651        _: &ContextMenuNext,
10652        _window: &mut Window,
10653        cx: &mut Context<Self>,
10654    ) {
10655        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10656            context_menu.select_next(self.completion_provider.as_deref(), cx);
10657        }
10658    }
10659
10660    pub fn context_menu_last(
10661        &mut self,
10662        _: &ContextMenuLast,
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_last(self.completion_provider.as_deref(), cx);
10668        }
10669    }
10670
10671    pub fn move_to_previous_word_start(
10672        &mut self,
10673        _: &MoveToPreviousWordStart,
10674        window: &mut Window,
10675        cx: &mut Context<Self>,
10676    ) {
10677        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10678        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10679            s.move_cursors_with(|map, head, _| {
10680                (
10681                    movement::previous_word_start(map, head),
10682                    SelectionGoal::None,
10683                )
10684            });
10685        })
10686    }
10687
10688    pub fn move_to_previous_subword_start(
10689        &mut self,
10690        _: &MoveToPreviousSubwordStart,
10691        window: &mut Window,
10692        cx: &mut Context<Self>,
10693    ) {
10694        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10695        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10696            s.move_cursors_with(|map, head, _| {
10697                (
10698                    movement::previous_subword_start(map, head),
10699                    SelectionGoal::None,
10700                )
10701            });
10702        })
10703    }
10704
10705    pub fn select_to_previous_word_start(
10706        &mut self,
10707        _: &SelectToPreviousWordStart,
10708        window: &mut Window,
10709        cx: &mut Context<Self>,
10710    ) {
10711        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10712        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10713            s.move_heads_with(|map, head, _| {
10714                (
10715                    movement::previous_word_start(map, head),
10716                    SelectionGoal::None,
10717                )
10718            });
10719        })
10720    }
10721
10722    pub fn select_to_previous_subword_start(
10723        &mut self,
10724        _: &SelectToPreviousSubwordStart,
10725        window: &mut Window,
10726        cx: &mut Context<Self>,
10727    ) {
10728        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10729        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10730            s.move_heads_with(|map, head, _| {
10731                (
10732                    movement::previous_subword_start(map, head),
10733                    SelectionGoal::None,
10734                )
10735            });
10736        })
10737    }
10738
10739    pub fn delete_to_previous_word_start(
10740        &mut self,
10741        action: &DeleteToPreviousWordStart,
10742        window: &mut Window,
10743        cx: &mut Context<Self>,
10744    ) {
10745        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10746        self.transact(window, cx, |this, window, cx| {
10747            this.select_autoclose_pair(window, cx);
10748            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10749                s.move_with(|map, selection| {
10750                    if selection.is_empty() {
10751                        let cursor = if action.ignore_newlines {
10752                            movement::previous_word_start(map, selection.head())
10753                        } else {
10754                            movement::previous_word_start_or_newline(map, selection.head())
10755                        };
10756                        selection.set_head(cursor, SelectionGoal::None);
10757                    }
10758                });
10759            });
10760            this.insert("", window, cx);
10761        });
10762    }
10763
10764    pub fn delete_to_previous_subword_start(
10765        &mut self,
10766        _: &DeleteToPreviousSubwordStart,
10767        window: &mut Window,
10768        cx: &mut Context<Self>,
10769    ) {
10770        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10771        self.transact(window, cx, |this, window, cx| {
10772            this.select_autoclose_pair(window, cx);
10773            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10774                s.move_with(|map, selection| {
10775                    if selection.is_empty() {
10776                        let cursor = movement::previous_subword_start(map, selection.head());
10777                        selection.set_head(cursor, SelectionGoal::None);
10778                    }
10779                });
10780            });
10781            this.insert("", window, cx);
10782        });
10783    }
10784
10785    pub fn move_to_next_word_end(
10786        &mut self,
10787        _: &MoveToNextWordEnd,
10788        window: &mut Window,
10789        cx: &mut Context<Self>,
10790    ) {
10791        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10792        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10793            s.move_cursors_with(|map, head, _| {
10794                (movement::next_word_end(map, head), SelectionGoal::None)
10795            });
10796        })
10797    }
10798
10799    pub fn move_to_next_subword_end(
10800        &mut self,
10801        _: &MoveToNextSubwordEnd,
10802        window: &mut Window,
10803        cx: &mut Context<Self>,
10804    ) {
10805        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10806        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10807            s.move_cursors_with(|map, head, _| {
10808                (movement::next_subword_end(map, head), SelectionGoal::None)
10809            });
10810        })
10811    }
10812
10813    pub fn select_to_next_word_end(
10814        &mut self,
10815        _: &SelectToNextWordEnd,
10816        window: &mut Window,
10817        cx: &mut Context<Self>,
10818    ) {
10819        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10820        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10821            s.move_heads_with(|map, head, _| {
10822                (movement::next_word_end(map, head), SelectionGoal::None)
10823            });
10824        })
10825    }
10826
10827    pub fn select_to_next_subword_end(
10828        &mut self,
10829        _: &SelectToNextSubwordEnd,
10830        window: &mut Window,
10831        cx: &mut Context<Self>,
10832    ) {
10833        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10834        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10835            s.move_heads_with(|map, head, _| {
10836                (movement::next_subword_end(map, head), SelectionGoal::None)
10837            });
10838        })
10839    }
10840
10841    pub fn delete_to_next_word_end(
10842        &mut self,
10843        action: &DeleteToNextWordEnd,
10844        window: &mut Window,
10845        cx: &mut Context<Self>,
10846    ) {
10847        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10848        self.transact(window, cx, |this, window, cx| {
10849            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10850                s.move_with(|map, selection| {
10851                    if selection.is_empty() {
10852                        let cursor = if action.ignore_newlines {
10853                            movement::next_word_end(map, selection.head())
10854                        } else {
10855                            movement::next_word_end_or_newline(map, selection.head())
10856                        };
10857                        selection.set_head(cursor, SelectionGoal::None);
10858                    }
10859                });
10860            });
10861            this.insert("", window, cx);
10862        });
10863    }
10864
10865    pub fn delete_to_next_subword_end(
10866        &mut self,
10867        _: &DeleteToNextSubwordEnd,
10868        window: &mut Window,
10869        cx: &mut Context<Self>,
10870    ) {
10871        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10872        self.transact(window, cx, |this, window, cx| {
10873            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10874                s.move_with(|map, selection| {
10875                    if selection.is_empty() {
10876                        let cursor = movement::next_subword_end(map, selection.head());
10877                        selection.set_head(cursor, SelectionGoal::None);
10878                    }
10879                });
10880            });
10881            this.insert("", window, cx);
10882        });
10883    }
10884
10885    pub fn move_to_beginning_of_line(
10886        &mut self,
10887        action: &MoveToBeginningOfLine,
10888        window: &mut Window,
10889        cx: &mut Context<Self>,
10890    ) {
10891        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10892        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10893            s.move_cursors_with(|map, head, _| {
10894                (
10895                    movement::indented_line_beginning(
10896                        map,
10897                        head,
10898                        action.stop_at_soft_wraps,
10899                        action.stop_at_indent,
10900                    ),
10901                    SelectionGoal::None,
10902                )
10903            });
10904        })
10905    }
10906
10907    pub fn select_to_beginning_of_line(
10908        &mut self,
10909        action: &SelectToBeginningOfLine,
10910        window: &mut Window,
10911        cx: &mut Context<Self>,
10912    ) {
10913        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10914        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10915            s.move_heads_with(|map, head, _| {
10916                (
10917                    movement::indented_line_beginning(
10918                        map,
10919                        head,
10920                        action.stop_at_soft_wraps,
10921                        action.stop_at_indent,
10922                    ),
10923                    SelectionGoal::None,
10924                )
10925            });
10926        });
10927    }
10928
10929    pub fn delete_to_beginning_of_line(
10930        &mut self,
10931        action: &DeleteToBeginningOfLine,
10932        window: &mut Window,
10933        cx: &mut Context<Self>,
10934    ) {
10935        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10936        self.transact(window, cx, |this, window, cx| {
10937            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10938                s.move_with(|_, selection| {
10939                    selection.reversed = true;
10940                });
10941            });
10942
10943            this.select_to_beginning_of_line(
10944                &SelectToBeginningOfLine {
10945                    stop_at_soft_wraps: false,
10946                    stop_at_indent: action.stop_at_indent,
10947                },
10948                window,
10949                cx,
10950            );
10951            this.backspace(&Backspace, window, cx);
10952        });
10953    }
10954
10955    pub fn move_to_end_of_line(
10956        &mut self,
10957        action: &MoveToEndOfLine,
10958        window: &mut Window,
10959        cx: &mut Context<Self>,
10960    ) {
10961        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10962        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10963            s.move_cursors_with(|map, head, _| {
10964                (
10965                    movement::line_end(map, head, action.stop_at_soft_wraps),
10966                    SelectionGoal::None,
10967                )
10968            });
10969        })
10970    }
10971
10972    pub fn select_to_end_of_line(
10973        &mut self,
10974        action: &SelectToEndOfLine,
10975        window: &mut Window,
10976        cx: &mut Context<Self>,
10977    ) {
10978        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10979        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10980            s.move_heads_with(|map, head, _| {
10981                (
10982                    movement::line_end(map, head, action.stop_at_soft_wraps),
10983                    SelectionGoal::None,
10984                )
10985            });
10986        })
10987    }
10988
10989    pub fn delete_to_end_of_line(
10990        &mut self,
10991        _: &DeleteToEndOfLine,
10992        window: &mut Window,
10993        cx: &mut Context<Self>,
10994    ) {
10995        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10996        self.transact(window, cx, |this, window, cx| {
10997            this.select_to_end_of_line(
10998                &SelectToEndOfLine {
10999                    stop_at_soft_wraps: false,
11000                },
11001                window,
11002                cx,
11003            );
11004            this.delete(&Delete, window, cx);
11005        });
11006    }
11007
11008    pub fn cut_to_end_of_line(
11009        &mut self,
11010        _: &CutToEndOfLine,
11011        window: &mut Window,
11012        cx: &mut Context<Self>,
11013    ) {
11014        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11015        self.transact(window, cx, |this, window, cx| {
11016            this.select_to_end_of_line(
11017                &SelectToEndOfLine {
11018                    stop_at_soft_wraps: false,
11019                },
11020                window,
11021                cx,
11022            );
11023            this.cut(&Cut, window, cx);
11024        });
11025    }
11026
11027    pub fn move_to_start_of_paragraph(
11028        &mut self,
11029        _: &MoveToStartOfParagraph,
11030        window: &mut Window,
11031        cx: &mut Context<Self>,
11032    ) {
11033        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11034            cx.propagate();
11035            return;
11036        }
11037        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11038        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11039            s.move_with(|map, selection| {
11040                selection.collapse_to(
11041                    movement::start_of_paragraph(map, selection.head(), 1),
11042                    SelectionGoal::None,
11043                )
11044            });
11045        })
11046    }
11047
11048    pub fn move_to_end_of_paragraph(
11049        &mut self,
11050        _: &MoveToEndOfParagraph,
11051        window: &mut Window,
11052        cx: &mut Context<Self>,
11053    ) {
11054        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11055            cx.propagate();
11056            return;
11057        }
11058        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11059        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11060            s.move_with(|map, selection| {
11061                selection.collapse_to(
11062                    movement::end_of_paragraph(map, selection.head(), 1),
11063                    SelectionGoal::None,
11064                )
11065            });
11066        })
11067    }
11068
11069    pub fn select_to_start_of_paragraph(
11070        &mut self,
11071        _: &SelectToStartOfParagraph,
11072        window: &mut Window,
11073        cx: &mut Context<Self>,
11074    ) {
11075        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11076            cx.propagate();
11077            return;
11078        }
11079        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11080        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11081            s.move_heads_with(|map, head, _| {
11082                (
11083                    movement::start_of_paragraph(map, head, 1),
11084                    SelectionGoal::None,
11085                )
11086            });
11087        })
11088    }
11089
11090    pub fn select_to_end_of_paragraph(
11091        &mut self,
11092        _: &SelectToEndOfParagraph,
11093        window: &mut Window,
11094        cx: &mut Context<Self>,
11095    ) {
11096        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11097            cx.propagate();
11098            return;
11099        }
11100        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11101        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11102            s.move_heads_with(|map, head, _| {
11103                (
11104                    movement::end_of_paragraph(map, head, 1),
11105                    SelectionGoal::None,
11106                )
11107            });
11108        })
11109    }
11110
11111    pub fn move_to_start_of_excerpt(
11112        &mut self,
11113        _: &MoveToStartOfExcerpt,
11114        window: &mut Window,
11115        cx: &mut Context<Self>,
11116    ) {
11117        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11118            cx.propagate();
11119            return;
11120        }
11121        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11122        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11123            s.move_with(|map, selection| {
11124                selection.collapse_to(
11125                    movement::start_of_excerpt(
11126                        map,
11127                        selection.head(),
11128                        workspace::searchable::Direction::Prev,
11129                    ),
11130                    SelectionGoal::None,
11131                )
11132            });
11133        })
11134    }
11135
11136    pub fn move_to_start_of_next_excerpt(
11137        &mut self,
11138        _: &MoveToStartOfNextExcerpt,
11139        window: &mut Window,
11140        cx: &mut Context<Self>,
11141    ) {
11142        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11143            cx.propagate();
11144            return;
11145        }
11146
11147        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11148            s.move_with(|map, selection| {
11149                selection.collapse_to(
11150                    movement::start_of_excerpt(
11151                        map,
11152                        selection.head(),
11153                        workspace::searchable::Direction::Next,
11154                    ),
11155                    SelectionGoal::None,
11156                )
11157            });
11158        })
11159    }
11160
11161    pub fn move_to_end_of_excerpt(
11162        &mut self,
11163        _: &MoveToEndOfExcerpt,
11164        window: &mut Window,
11165        cx: &mut Context<Self>,
11166    ) {
11167        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11168            cx.propagate();
11169            return;
11170        }
11171        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11172        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11173            s.move_with(|map, selection| {
11174                selection.collapse_to(
11175                    movement::end_of_excerpt(
11176                        map,
11177                        selection.head(),
11178                        workspace::searchable::Direction::Next,
11179                    ),
11180                    SelectionGoal::None,
11181                )
11182            });
11183        })
11184    }
11185
11186    pub fn move_to_end_of_previous_excerpt(
11187        &mut self,
11188        _: &MoveToEndOfPreviousExcerpt,
11189        window: &mut Window,
11190        cx: &mut Context<Self>,
11191    ) {
11192        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11193            cx.propagate();
11194            return;
11195        }
11196        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11197        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11198            s.move_with(|map, selection| {
11199                selection.collapse_to(
11200                    movement::end_of_excerpt(
11201                        map,
11202                        selection.head(),
11203                        workspace::searchable::Direction::Prev,
11204                    ),
11205                    SelectionGoal::None,
11206                )
11207            });
11208        })
11209    }
11210
11211    pub fn select_to_start_of_excerpt(
11212        &mut self,
11213        _: &SelectToStartOfExcerpt,
11214        window: &mut Window,
11215        cx: &mut Context<Self>,
11216    ) {
11217        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11218            cx.propagate();
11219            return;
11220        }
11221        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11222        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11223            s.move_heads_with(|map, head, _| {
11224                (
11225                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11226                    SelectionGoal::None,
11227                )
11228            });
11229        })
11230    }
11231
11232    pub fn select_to_start_of_next_excerpt(
11233        &mut self,
11234        _: &SelectToStartOfNextExcerpt,
11235        window: &mut Window,
11236        cx: &mut Context<Self>,
11237    ) {
11238        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11239            cx.propagate();
11240            return;
11241        }
11242        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11243        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11244            s.move_heads_with(|map, head, _| {
11245                (
11246                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11247                    SelectionGoal::None,
11248                )
11249            });
11250        })
11251    }
11252
11253    pub fn select_to_end_of_excerpt(
11254        &mut self,
11255        _: &SelectToEndOfExcerpt,
11256        window: &mut Window,
11257        cx: &mut Context<Self>,
11258    ) {
11259        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11260            cx.propagate();
11261            return;
11262        }
11263        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11264        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11265            s.move_heads_with(|map, head, _| {
11266                (
11267                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11268                    SelectionGoal::None,
11269                )
11270            });
11271        })
11272    }
11273
11274    pub fn select_to_end_of_previous_excerpt(
11275        &mut self,
11276        _: &SelectToEndOfPreviousExcerpt,
11277        window: &mut Window,
11278        cx: &mut Context<Self>,
11279    ) {
11280        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11281            cx.propagate();
11282            return;
11283        }
11284        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11285        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11286            s.move_heads_with(|map, head, _| {
11287                (
11288                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11289                    SelectionGoal::None,
11290                )
11291            });
11292        })
11293    }
11294
11295    pub fn move_to_beginning(
11296        &mut self,
11297        _: &MoveToBeginning,
11298        window: &mut Window,
11299        cx: &mut Context<Self>,
11300    ) {
11301        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11302            cx.propagate();
11303            return;
11304        }
11305        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11306        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11307            s.select_ranges(vec![0..0]);
11308        });
11309    }
11310
11311    pub fn select_to_beginning(
11312        &mut self,
11313        _: &SelectToBeginning,
11314        window: &mut Window,
11315        cx: &mut Context<Self>,
11316    ) {
11317        let mut selection = self.selections.last::<Point>(cx);
11318        selection.set_head(Point::zero(), SelectionGoal::None);
11319        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11320        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11321            s.select(vec![selection]);
11322        });
11323    }
11324
11325    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11326        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11327            cx.propagate();
11328            return;
11329        }
11330        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11331        let cursor = self.buffer.read(cx).read(cx).len();
11332        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11333            s.select_ranges(vec![cursor..cursor])
11334        });
11335    }
11336
11337    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11338        self.nav_history = nav_history;
11339    }
11340
11341    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11342        self.nav_history.as_ref()
11343    }
11344
11345    pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11346        self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11347    }
11348
11349    fn push_to_nav_history(
11350        &mut self,
11351        cursor_anchor: Anchor,
11352        new_position: Option<Point>,
11353        is_deactivate: bool,
11354        cx: &mut Context<Self>,
11355    ) {
11356        if let Some(nav_history) = self.nav_history.as_mut() {
11357            let buffer = self.buffer.read(cx).read(cx);
11358            let cursor_position = cursor_anchor.to_point(&buffer);
11359            let scroll_state = self.scroll_manager.anchor();
11360            let scroll_top_row = scroll_state.top_row(&buffer);
11361            drop(buffer);
11362
11363            if let Some(new_position) = new_position {
11364                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11365                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11366                    return;
11367                }
11368            }
11369
11370            nav_history.push(
11371                Some(NavigationData {
11372                    cursor_anchor,
11373                    cursor_position,
11374                    scroll_anchor: scroll_state,
11375                    scroll_top_row,
11376                }),
11377                cx,
11378            );
11379            cx.emit(EditorEvent::PushedToNavHistory {
11380                anchor: cursor_anchor,
11381                is_deactivate,
11382            })
11383        }
11384    }
11385
11386    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11387        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11388        let buffer = self.buffer.read(cx).snapshot(cx);
11389        let mut selection = self.selections.first::<usize>(cx);
11390        selection.set_head(buffer.len(), SelectionGoal::None);
11391        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11392            s.select(vec![selection]);
11393        });
11394    }
11395
11396    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11397        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11398        let end = self.buffer.read(cx).read(cx).len();
11399        self.change_selections(None, window, cx, |s| {
11400            s.select_ranges(vec![0..end]);
11401        });
11402    }
11403
11404    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11405        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11406        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11407        let mut selections = self.selections.all::<Point>(cx);
11408        let max_point = display_map.buffer_snapshot.max_point();
11409        for selection in &mut selections {
11410            let rows = selection.spanned_rows(true, &display_map);
11411            selection.start = Point::new(rows.start.0, 0);
11412            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11413            selection.reversed = false;
11414        }
11415        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11416            s.select(selections);
11417        });
11418    }
11419
11420    pub fn split_selection_into_lines(
11421        &mut self,
11422        _: &SplitSelectionIntoLines,
11423        window: &mut Window,
11424        cx: &mut Context<Self>,
11425    ) {
11426        let selections = self
11427            .selections
11428            .all::<Point>(cx)
11429            .into_iter()
11430            .map(|selection| selection.start..selection.end)
11431            .collect::<Vec<_>>();
11432        self.unfold_ranges(&selections, true, true, cx);
11433
11434        let mut new_selection_ranges = Vec::new();
11435        {
11436            let buffer = self.buffer.read(cx).read(cx);
11437            for selection in selections {
11438                for row in selection.start.row..selection.end.row {
11439                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11440                    new_selection_ranges.push(cursor..cursor);
11441                }
11442
11443                let is_multiline_selection = selection.start.row != selection.end.row;
11444                // Don't insert last one if it's a multi-line selection ending at the start of a line,
11445                // so this action feels more ergonomic when paired with other selection operations
11446                let should_skip_last = is_multiline_selection && selection.end.column == 0;
11447                if !should_skip_last {
11448                    new_selection_ranges.push(selection.end..selection.end);
11449                }
11450            }
11451        }
11452        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11453            s.select_ranges(new_selection_ranges);
11454        });
11455    }
11456
11457    pub fn add_selection_above(
11458        &mut self,
11459        _: &AddSelectionAbove,
11460        window: &mut Window,
11461        cx: &mut Context<Self>,
11462    ) {
11463        self.add_selection(true, window, cx);
11464    }
11465
11466    pub fn add_selection_below(
11467        &mut self,
11468        _: &AddSelectionBelow,
11469        window: &mut Window,
11470        cx: &mut Context<Self>,
11471    ) {
11472        self.add_selection(false, window, cx);
11473    }
11474
11475    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11476        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11477
11478        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11479        let mut selections = self.selections.all::<Point>(cx);
11480        let text_layout_details = self.text_layout_details(window);
11481        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11482            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11483            let range = oldest_selection.display_range(&display_map).sorted();
11484
11485            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11486            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11487            let positions = start_x.min(end_x)..start_x.max(end_x);
11488
11489            selections.clear();
11490            let mut stack = Vec::new();
11491            for row in range.start.row().0..=range.end.row().0 {
11492                if let Some(selection) = self.selections.build_columnar_selection(
11493                    &display_map,
11494                    DisplayRow(row),
11495                    &positions,
11496                    oldest_selection.reversed,
11497                    &text_layout_details,
11498                ) {
11499                    stack.push(selection.id);
11500                    selections.push(selection);
11501                }
11502            }
11503
11504            if above {
11505                stack.reverse();
11506            }
11507
11508            AddSelectionsState { above, stack }
11509        });
11510
11511        let last_added_selection = *state.stack.last().unwrap();
11512        let mut new_selections = Vec::new();
11513        if above == state.above {
11514            let end_row = if above {
11515                DisplayRow(0)
11516            } else {
11517                display_map.max_point().row()
11518            };
11519
11520            'outer: for selection in selections {
11521                if selection.id == last_added_selection {
11522                    let range = selection.display_range(&display_map).sorted();
11523                    debug_assert_eq!(range.start.row(), range.end.row());
11524                    let mut row = range.start.row();
11525                    let positions =
11526                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11527                            px(start)..px(end)
11528                        } else {
11529                            let start_x =
11530                                display_map.x_for_display_point(range.start, &text_layout_details);
11531                            let end_x =
11532                                display_map.x_for_display_point(range.end, &text_layout_details);
11533                            start_x.min(end_x)..start_x.max(end_x)
11534                        };
11535
11536                    while row != end_row {
11537                        if above {
11538                            row.0 -= 1;
11539                        } else {
11540                            row.0 += 1;
11541                        }
11542
11543                        if let Some(new_selection) = self.selections.build_columnar_selection(
11544                            &display_map,
11545                            row,
11546                            &positions,
11547                            selection.reversed,
11548                            &text_layout_details,
11549                        ) {
11550                            state.stack.push(new_selection.id);
11551                            if above {
11552                                new_selections.push(new_selection);
11553                                new_selections.push(selection);
11554                            } else {
11555                                new_selections.push(selection);
11556                                new_selections.push(new_selection);
11557                            }
11558
11559                            continue 'outer;
11560                        }
11561                    }
11562                }
11563
11564                new_selections.push(selection);
11565            }
11566        } else {
11567            new_selections = selections;
11568            new_selections.retain(|s| s.id != last_added_selection);
11569            state.stack.pop();
11570        }
11571
11572        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11573            s.select(new_selections);
11574        });
11575        if state.stack.len() > 1 {
11576            self.add_selections_state = Some(state);
11577        }
11578    }
11579
11580    pub fn select_next_match_internal(
11581        &mut self,
11582        display_map: &DisplaySnapshot,
11583        replace_newest: bool,
11584        autoscroll: Option<Autoscroll>,
11585        window: &mut Window,
11586        cx: &mut Context<Self>,
11587    ) -> Result<()> {
11588        fn select_next_match_ranges(
11589            this: &mut Editor,
11590            range: Range<usize>,
11591            replace_newest: bool,
11592            auto_scroll: Option<Autoscroll>,
11593            window: &mut Window,
11594            cx: &mut Context<Editor>,
11595        ) {
11596            this.unfold_ranges(&[range.clone()], false, true, cx);
11597            this.change_selections(auto_scroll, window, cx, |s| {
11598                if replace_newest {
11599                    s.delete(s.newest_anchor().id);
11600                }
11601                s.insert_range(range.clone());
11602            });
11603        }
11604
11605        let buffer = &display_map.buffer_snapshot;
11606        let mut selections = self.selections.all::<usize>(cx);
11607        if let Some(mut select_next_state) = self.select_next_state.take() {
11608            let query = &select_next_state.query;
11609            if !select_next_state.done {
11610                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11611                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11612                let mut next_selected_range = None;
11613
11614                let bytes_after_last_selection =
11615                    buffer.bytes_in_range(last_selection.end..buffer.len());
11616                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11617                let query_matches = query
11618                    .stream_find_iter(bytes_after_last_selection)
11619                    .map(|result| (last_selection.end, result))
11620                    .chain(
11621                        query
11622                            .stream_find_iter(bytes_before_first_selection)
11623                            .map(|result| (0, result)),
11624                    );
11625
11626                for (start_offset, query_match) in query_matches {
11627                    let query_match = query_match.unwrap(); // can only fail due to I/O
11628                    let offset_range =
11629                        start_offset + query_match.start()..start_offset + query_match.end();
11630                    let display_range = offset_range.start.to_display_point(display_map)
11631                        ..offset_range.end.to_display_point(display_map);
11632
11633                    if !select_next_state.wordwise
11634                        || (!movement::is_inside_word(display_map, display_range.start)
11635                            && !movement::is_inside_word(display_map, display_range.end))
11636                    {
11637                        // TODO: This is n^2, because we might check all the selections
11638                        if !selections
11639                            .iter()
11640                            .any(|selection| selection.range().overlaps(&offset_range))
11641                        {
11642                            next_selected_range = Some(offset_range);
11643                            break;
11644                        }
11645                    }
11646                }
11647
11648                if let Some(next_selected_range) = next_selected_range {
11649                    select_next_match_ranges(
11650                        self,
11651                        next_selected_range,
11652                        replace_newest,
11653                        autoscroll,
11654                        window,
11655                        cx,
11656                    );
11657                } else {
11658                    select_next_state.done = true;
11659                }
11660            }
11661
11662            self.select_next_state = Some(select_next_state);
11663        } else {
11664            let mut only_carets = true;
11665            let mut same_text_selected = true;
11666            let mut selected_text = None;
11667
11668            let mut selections_iter = selections.iter().peekable();
11669            while let Some(selection) = selections_iter.next() {
11670                if selection.start != selection.end {
11671                    only_carets = false;
11672                }
11673
11674                if same_text_selected {
11675                    if selected_text.is_none() {
11676                        selected_text =
11677                            Some(buffer.text_for_range(selection.range()).collect::<String>());
11678                    }
11679
11680                    if let Some(next_selection) = selections_iter.peek() {
11681                        if next_selection.range().len() == selection.range().len() {
11682                            let next_selected_text = buffer
11683                                .text_for_range(next_selection.range())
11684                                .collect::<String>();
11685                            if Some(next_selected_text) != selected_text {
11686                                same_text_selected = false;
11687                                selected_text = None;
11688                            }
11689                        } else {
11690                            same_text_selected = false;
11691                            selected_text = None;
11692                        }
11693                    }
11694                }
11695            }
11696
11697            if only_carets {
11698                for selection in &mut selections {
11699                    let word_range = movement::surrounding_word(
11700                        display_map,
11701                        selection.start.to_display_point(display_map),
11702                    );
11703                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
11704                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
11705                    selection.goal = SelectionGoal::None;
11706                    selection.reversed = false;
11707                    select_next_match_ranges(
11708                        self,
11709                        selection.start..selection.end,
11710                        replace_newest,
11711                        autoscroll,
11712                        window,
11713                        cx,
11714                    );
11715                }
11716
11717                if selections.len() == 1 {
11718                    let selection = selections
11719                        .last()
11720                        .expect("ensured that there's only one selection");
11721                    let query = buffer
11722                        .text_for_range(selection.start..selection.end)
11723                        .collect::<String>();
11724                    let is_empty = query.is_empty();
11725                    let select_state = SelectNextState {
11726                        query: AhoCorasick::new(&[query])?,
11727                        wordwise: true,
11728                        done: is_empty,
11729                    };
11730                    self.select_next_state = Some(select_state);
11731                } else {
11732                    self.select_next_state = None;
11733                }
11734            } else if let Some(selected_text) = selected_text {
11735                self.select_next_state = Some(SelectNextState {
11736                    query: AhoCorasick::new(&[selected_text])?,
11737                    wordwise: false,
11738                    done: false,
11739                });
11740                self.select_next_match_internal(
11741                    display_map,
11742                    replace_newest,
11743                    autoscroll,
11744                    window,
11745                    cx,
11746                )?;
11747            }
11748        }
11749        Ok(())
11750    }
11751
11752    pub fn select_all_matches(
11753        &mut self,
11754        _action: &SelectAllMatches,
11755        window: &mut Window,
11756        cx: &mut Context<Self>,
11757    ) -> Result<()> {
11758        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11759
11760        self.push_to_selection_history();
11761        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11762
11763        self.select_next_match_internal(&display_map, false, None, window, cx)?;
11764        let Some(select_next_state) = self.select_next_state.as_mut() else {
11765            return Ok(());
11766        };
11767        if select_next_state.done {
11768            return Ok(());
11769        }
11770
11771        let mut new_selections = self.selections.all::<usize>(cx);
11772
11773        let buffer = &display_map.buffer_snapshot;
11774        let query_matches = select_next_state
11775            .query
11776            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11777
11778        for query_match in query_matches {
11779            let query_match = query_match.unwrap(); // can only fail due to I/O
11780            let offset_range = query_match.start()..query_match.end();
11781            let display_range = offset_range.start.to_display_point(&display_map)
11782                ..offset_range.end.to_display_point(&display_map);
11783
11784            if !select_next_state.wordwise
11785                || (!movement::is_inside_word(&display_map, display_range.start)
11786                    && !movement::is_inside_word(&display_map, display_range.end))
11787            {
11788                self.selections.change_with(cx, |selections| {
11789                    new_selections.push(Selection {
11790                        id: selections.new_selection_id(),
11791                        start: offset_range.start,
11792                        end: offset_range.end,
11793                        reversed: false,
11794                        goal: SelectionGoal::None,
11795                    });
11796                });
11797            }
11798        }
11799
11800        new_selections.sort_by_key(|selection| selection.start);
11801        let mut ix = 0;
11802        while ix + 1 < new_selections.len() {
11803            let current_selection = &new_selections[ix];
11804            let next_selection = &new_selections[ix + 1];
11805            if current_selection.range().overlaps(&next_selection.range()) {
11806                if current_selection.id < next_selection.id {
11807                    new_selections.remove(ix + 1);
11808                } else {
11809                    new_selections.remove(ix);
11810                }
11811            } else {
11812                ix += 1;
11813            }
11814        }
11815
11816        let reversed = self.selections.oldest::<usize>(cx).reversed;
11817
11818        for selection in new_selections.iter_mut() {
11819            selection.reversed = reversed;
11820        }
11821
11822        select_next_state.done = true;
11823        self.unfold_ranges(
11824            &new_selections
11825                .iter()
11826                .map(|selection| selection.range())
11827                .collect::<Vec<_>>(),
11828            false,
11829            false,
11830            cx,
11831        );
11832        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
11833            selections.select(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 mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14214        let format = project.update(cx, |project, cx| {
14215            project.format(buffers, target, true, trigger, cx)
14216        });
14217
14218        cx.spawn_in(window, async move |_, cx| {
14219            let transaction = futures::select_biased! {
14220                transaction = format.log_err().fuse() => transaction,
14221                () = timeout => {
14222                    log::warn!("timed out waiting for formatting");
14223                    None
14224                }
14225            };
14226
14227            buffer
14228                .update(cx, |buffer, cx| {
14229                    if let Some(transaction) = transaction {
14230                        if !buffer.is_singleton() {
14231                            buffer.push_transaction(&transaction.0, cx);
14232                        }
14233                    }
14234                    cx.notify();
14235                })
14236                .ok();
14237
14238            Ok(())
14239        })
14240    }
14241
14242    fn organize_imports(
14243        &mut self,
14244        _: &OrganizeImports,
14245        window: &mut Window,
14246        cx: &mut Context<Self>,
14247    ) -> Option<Task<Result<()>>> {
14248        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14249        let project = match &self.project {
14250            Some(project) => project.clone(),
14251            None => return None,
14252        };
14253        Some(self.perform_code_action_kind(
14254            project,
14255            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14256            window,
14257            cx,
14258        ))
14259    }
14260
14261    fn perform_code_action_kind(
14262        &mut self,
14263        project: Entity<Project>,
14264        kind: CodeActionKind,
14265        window: &mut Window,
14266        cx: &mut Context<Self>,
14267    ) -> Task<Result<()>> {
14268        let buffer = self.buffer.clone();
14269        let buffers = buffer.read(cx).all_buffers();
14270        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14271        let apply_action = project.update(cx, |project, cx| {
14272            project.apply_code_action_kind(buffers, kind, true, cx)
14273        });
14274        cx.spawn_in(window, async move |_, cx| {
14275            let transaction = futures::select_biased! {
14276                () = timeout => {
14277                    log::warn!("timed out waiting for executing code action");
14278                    None
14279                }
14280                transaction = apply_action.log_err().fuse() => transaction,
14281            };
14282            buffer
14283                .update(cx, |buffer, cx| {
14284                    // check if we need this
14285                    if let Some(transaction) = transaction {
14286                        if !buffer.is_singleton() {
14287                            buffer.push_transaction(&transaction.0, cx);
14288                        }
14289                    }
14290                    cx.notify();
14291                })
14292                .ok();
14293            Ok(())
14294        })
14295    }
14296
14297    fn restart_language_server(
14298        &mut self,
14299        _: &RestartLanguageServer,
14300        _: &mut Window,
14301        cx: &mut Context<Self>,
14302    ) {
14303        if let Some(project) = self.project.clone() {
14304            self.buffer.update(cx, |multi_buffer, cx| {
14305                project.update(cx, |project, cx| {
14306                    project.restart_language_servers_for_buffers(
14307                        multi_buffer.all_buffers().into_iter().collect(),
14308                        cx,
14309                    );
14310                });
14311            })
14312        }
14313    }
14314
14315    fn stop_language_server(
14316        &mut self,
14317        _: &StopLanguageServer,
14318        _: &mut Window,
14319        cx: &mut Context<Self>,
14320    ) {
14321        if let Some(project) = self.project.clone() {
14322            self.buffer.update(cx, |multi_buffer, cx| {
14323                project.update(cx, |project, cx| {
14324                    project.stop_language_servers_for_buffers(
14325                        multi_buffer.all_buffers().into_iter().collect(),
14326                        cx,
14327                    );
14328                    cx.emit(project::Event::RefreshInlayHints);
14329                });
14330            });
14331        }
14332    }
14333
14334    fn cancel_language_server_work(
14335        workspace: &mut Workspace,
14336        _: &actions::CancelLanguageServerWork,
14337        _: &mut Window,
14338        cx: &mut Context<Workspace>,
14339    ) {
14340        let project = workspace.project();
14341        let buffers = workspace
14342            .active_item(cx)
14343            .and_then(|item| item.act_as::<Editor>(cx))
14344            .map_or(HashSet::default(), |editor| {
14345                editor.read(cx).buffer.read(cx).all_buffers()
14346            });
14347        project.update(cx, |project, cx| {
14348            project.cancel_language_server_work_for_buffers(buffers, cx);
14349        });
14350    }
14351
14352    fn show_character_palette(
14353        &mut self,
14354        _: &ShowCharacterPalette,
14355        window: &mut Window,
14356        _: &mut Context<Self>,
14357    ) {
14358        window.show_character_palette();
14359    }
14360
14361    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14362        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
14363            let buffer = self.buffer.read(cx).snapshot(cx);
14364            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
14365            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
14366            let is_valid = buffer
14367                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14368                .any(|entry| {
14369                    entry.diagnostic.is_primary
14370                        && !entry.range.is_empty()
14371                        && entry.range.start == primary_range_start
14372                        && entry.diagnostic.message == active_diagnostics.primary_message
14373                });
14374
14375            if is_valid != active_diagnostics.is_valid {
14376                active_diagnostics.is_valid = is_valid;
14377                if is_valid {
14378                    let mut new_styles = HashMap::default();
14379                    for (block_id, diagnostic) in &active_diagnostics.blocks {
14380                        new_styles.insert(
14381                            *block_id,
14382                            diagnostic_block_renderer(diagnostic.clone(), None, true),
14383                        );
14384                    }
14385                    self.display_map.update(cx, |display_map, _cx| {
14386                        display_map.replace_blocks(new_styles);
14387                    });
14388                } else {
14389                    self.dismiss_diagnostics(cx);
14390                }
14391            }
14392        }
14393    }
14394
14395    fn activate_diagnostics(
14396        &mut self,
14397        buffer_id: BufferId,
14398        group_id: usize,
14399        window: &mut Window,
14400        cx: &mut Context<Self>,
14401    ) {
14402        self.dismiss_diagnostics(cx);
14403        let snapshot = self.snapshot(window, cx);
14404        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
14405            let buffer = self.buffer.read(cx).snapshot(cx);
14406
14407            let mut primary_range = None;
14408            let mut primary_message = None;
14409            let diagnostic_group = buffer
14410                .diagnostic_group(buffer_id, group_id)
14411                .filter_map(|entry| {
14412                    let start = entry.range.start;
14413                    let end = entry.range.end;
14414                    if snapshot.is_line_folded(MultiBufferRow(start.row))
14415                        && (start.row == end.row
14416                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
14417                    {
14418                        return None;
14419                    }
14420                    if entry.diagnostic.is_primary {
14421                        primary_range = Some(entry.range.clone());
14422                        primary_message = Some(entry.diagnostic.message.clone());
14423                    }
14424                    Some(entry)
14425                })
14426                .collect::<Vec<_>>();
14427            let primary_range = primary_range?;
14428            let primary_message = primary_message?;
14429
14430            let blocks = display_map
14431                .insert_blocks(
14432                    diagnostic_group.iter().map(|entry| {
14433                        let diagnostic = entry.diagnostic.clone();
14434                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
14435                        BlockProperties {
14436                            style: BlockStyle::Fixed,
14437                            placement: BlockPlacement::Below(
14438                                buffer.anchor_after(entry.range.start),
14439                            ),
14440                            height: Some(message_height),
14441                            render: diagnostic_block_renderer(diagnostic, None, true),
14442                            priority: 0,
14443                        }
14444                    }),
14445                    cx,
14446                )
14447                .into_iter()
14448                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
14449                .collect();
14450
14451            Some(ActiveDiagnosticGroup {
14452                primary_range: buffer.anchor_before(primary_range.start)
14453                    ..buffer.anchor_after(primary_range.end),
14454                primary_message,
14455                group_id,
14456                blocks,
14457                is_valid: true,
14458            })
14459        });
14460    }
14461
14462    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14463        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
14464            self.display_map.update(cx, |display_map, cx| {
14465                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
14466            });
14467            cx.notify();
14468        }
14469    }
14470
14471    /// Disable inline diagnostics rendering for this editor.
14472    pub fn disable_inline_diagnostics(&mut self) {
14473        self.inline_diagnostics_enabled = false;
14474        self.inline_diagnostics_update = Task::ready(());
14475        self.inline_diagnostics.clear();
14476    }
14477
14478    pub fn inline_diagnostics_enabled(&self) -> bool {
14479        self.inline_diagnostics_enabled
14480    }
14481
14482    pub fn show_inline_diagnostics(&self) -> bool {
14483        self.show_inline_diagnostics
14484    }
14485
14486    pub fn toggle_inline_diagnostics(
14487        &mut self,
14488        _: &ToggleInlineDiagnostics,
14489        window: &mut Window,
14490        cx: &mut Context<Editor>,
14491    ) {
14492        self.show_inline_diagnostics = !self.show_inline_diagnostics;
14493        self.refresh_inline_diagnostics(false, window, cx);
14494    }
14495
14496    fn refresh_inline_diagnostics(
14497        &mut self,
14498        debounce: bool,
14499        window: &mut Window,
14500        cx: &mut Context<Self>,
14501    ) {
14502        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14503            self.inline_diagnostics_update = Task::ready(());
14504            self.inline_diagnostics.clear();
14505            return;
14506        }
14507
14508        let debounce_ms = ProjectSettings::get_global(cx)
14509            .diagnostics
14510            .inline
14511            .update_debounce_ms;
14512        let debounce = if debounce && debounce_ms > 0 {
14513            Some(Duration::from_millis(debounce_ms))
14514        } else {
14515            None
14516        };
14517        self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14518            if let Some(debounce) = debounce {
14519                cx.background_executor().timer(debounce).await;
14520            }
14521            let Some(snapshot) = editor
14522                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14523                .ok()
14524            else {
14525                return;
14526            };
14527
14528            let new_inline_diagnostics = cx
14529                .background_spawn(async move {
14530                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14531                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14532                        let message = diagnostic_entry
14533                            .diagnostic
14534                            .message
14535                            .split_once('\n')
14536                            .map(|(line, _)| line)
14537                            .map(SharedString::new)
14538                            .unwrap_or_else(|| {
14539                                SharedString::from(diagnostic_entry.diagnostic.message)
14540                            });
14541                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14542                        let (Ok(i) | Err(i)) = inline_diagnostics
14543                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14544                        inline_diagnostics.insert(
14545                            i,
14546                            (
14547                                start_anchor,
14548                                InlineDiagnostic {
14549                                    message,
14550                                    group_id: diagnostic_entry.diagnostic.group_id,
14551                                    start: diagnostic_entry.range.start.to_point(&snapshot),
14552                                    is_primary: diagnostic_entry.diagnostic.is_primary,
14553                                    severity: diagnostic_entry.diagnostic.severity,
14554                                },
14555                            ),
14556                        );
14557                    }
14558                    inline_diagnostics
14559                })
14560                .await;
14561
14562            editor
14563                .update(cx, |editor, cx| {
14564                    editor.inline_diagnostics = new_inline_diagnostics;
14565                    cx.notify();
14566                })
14567                .ok();
14568        });
14569    }
14570
14571    pub fn set_selections_from_remote(
14572        &mut self,
14573        selections: Vec<Selection<Anchor>>,
14574        pending_selection: Option<Selection<Anchor>>,
14575        window: &mut Window,
14576        cx: &mut Context<Self>,
14577    ) {
14578        let old_cursor_position = self.selections.newest_anchor().head();
14579        self.selections.change_with(cx, |s| {
14580            s.select_anchors(selections);
14581            if let Some(pending_selection) = pending_selection {
14582                s.set_pending(pending_selection, SelectMode::Character);
14583            } else {
14584                s.clear_pending();
14585            }
14586        });
14587        self.selections_did_change(false, &old_cursor_position, true, window, cx);
14588    }
14589
14590    fn push_to_selection_history(&mut self) {
14591        self.selection_history.push(SelectionHistoryEntry {
14592            selections: self.selections.disjoint_anchors(),
14593            select_next_state: self.select_next_state.clone(),
14594            select_prev_state: self.select_prev_state.clone(),
14595            add_selections_state: self.add_selections_state.clone(),
14596        });
14597    }
14598
14599    pub fn transact(
14600        &mut self,
14601        window: &mut Window,
14602        cx: &mut Context<Self>,
14603        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14604    ) -> Option<TransactionId> {
14605        self.start_transaction_at(Instant::now(), window, cx);
14606        update(self, window, cx);
14607        self.end_transaction_at(Instant::now(), cx)
14608    }
14609
14610    pub fn start_transaction_at(
14611        &mut self,
14612        now: Instant,
14613        window: &mut Window,
14614        cx: &mut Context<Self>,
14615    ) {
14616        self.end_selection(window, cx);
14617        if let Some(tx_id) = self
14618            .buffer
14619            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14620        {
14621            self.selection_history
14622                .insert_transaction(tx_id, self.selections.disjoint_anchors());
14623            cx.emit(EditorEvent::TransactionBegun {
14624                transaction_id: tx_id,
14625            })
14626        }
14627    }
14628
14629    pub fn end_transaction_at(
14630        &mut self,
14631        now: Instant,
14632        cx: &mut Context<Self>,
14633    ) -> Option<TransactionId> {
14634        if let Some(transaction_id) = self
14635            .buffer
14636            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14637        {
14638            if let Some((_, end_selections)) =
14639                self.selection_history.transaction_mut(transaction_id)
14640            {
14641                *end_selections = Some(self.selections.disjoint_anchors());
14642            } else {
14643                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14644            }
14645
14646            cx.emit(EditorEvent::Edited { transaction_id });
14647            Some(transaction_id)
14648        } else {
14649            None
14650        }
14651    }
14652
14653    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14654        if self.selection_mark_mode {
14655            self.change_selections(None, window, cx, |s| {
14656                s.move_with(|_, sel| {
14657                    sel.collapse_to(sel.head(), SelectionGoal::None);
14658                });
14659            })
14660        }
14661        self.selection_mark_mode = true;
14662        cx.notify();
14663    }
14664
14665    pub fn swap_selection_ends(
14666        &mut self,
14667        _: &actions::SwapSelectionEnds,
14668        window: &mut Window,
14669        cx: &mut Context<Self>,
14670    ) {
14671        self.change_selections(None, window, cx, |s| {
14672            s.move_with(|_, sel| {
14673                if sel.start != sel.end {
14674                    sel.reversed = !sel.reversed
14675                }
14676            });
14677        });
14678        self.request_autoscroll(Autoscroll::newest(), cx);
14679        cx.notify();
14680    }
14681
14682    pub fn toggle_fold(
14683        &mut self,
14684        _: &actions::ToggleFold,
14685        window: &mut Window,
14686        cx: &mut Context<Self>,
14687    ) {
14688        if self.is_singleton(cx) {
14689            let selection = self.selections.newest::<Point>(cx);
14690
14691            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14692            let range = if selection.is_empty() {
14693                let point = selection.head().to_display_point(&display_map);
14694                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14695                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14696                    .to_point(&display_map);
14697                start..end
14698            } else {
14699                selection.range()
14700            };
14701            if display_map.folds_in_range(range).next().is_some() {
14702                self.unfold_lines(&Default::default(), window, cx)
14703            } else {
14704                self.fold(&Default::default(), window, cx)
14705            }
14706        } else {
14707            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14708            let buffer_ids: HashSet<_> = self
14709                .selections
14710                .disjoint_anchor_ranges()
14711                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14712                .collect();
14713
14714            let should_unfold = buffer_ids
14715                .iter()
14716                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14717
14718            for buffer_id in buffer_ids {
14719                if should_unfold {
14720                    self.unfold_buffer(buffer_id, cx);
14721                } else {
14722                    self.fold_buffer(buffer_id, cx);
14723                }
14724            }
14725        }
14726    }
14727
14728    pub fn toggle_fold_recursive(
14729        &mut self,
14730        _: &actions::ToggleFoldRecursive,
14731        window: &mut Window,
14732        cx: &mut Context<Self>,
14733    ) {
14734        let selection = self.selections.newest::<Point>(cx);
14735
14736        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14737        let range = if selection.is_empty() {
14738            let point = selection.head().to_display_point(&display_map);
14739            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14740            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14741                .to_point(&display_map);
14742            start..end
14743        } else {
14744            selection.range()
14745        };
14746        if display_map.folds_in_range(range).next().is_some() {
14747            self.unfold_recursive(&Default::default(), window, cx)
14748        } else {
14749            self.fold_recursive(&Default::default(), window, cx)
14750        }
14751    }
14752
14753    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
14754        if self.is_singleton(cx) {
14755            let mut to_fold = Vec::new();
14756            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14757            let selections = self.selections.all_adjusted(cx);
14758
14759            for selection in selections {
14760                let range = selection.range().sorted();
14761                let buffer_start_row = range.start.row;
14762
14763                if range.start.row != range.end.row {
14764                    let mut found = false;
14765                    let mut row = range.start.row;
14766                    while row <= range.end.row {
14767                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
14768                        {
14769                            found = true;
14770                            row = crease.range().end.row + 1;
14771                            to_fold.push(crease);
14772                        } else {
14773                            row += 1
14774                        }
14775                    }
14776                    if found {
14777                        continue;
14778                    }
14779                }
14780
14781                for row in (0..=range.start.row).rev() {
14782                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14783                        if crease.range().end.row >= buffer_start_row {
14784                            to_fold.push(crease);
14785                            if row <= range.start.row {
14786                                break;
14787                            }
14788                        }
14789                    }
14790                }
14791            }
14792
14793            self.fold_creases(to_fold, true, window, cx);
14794        } else {
14795            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14796            let buffer_ids = self
14797                .selections
14798                .disjoint_anchor_ranges()
14799                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14800                .collect::<HashSet<_>>();
14801            for buffer_id in buffer_ids {
14802                self.fold_buffer(buffer_id, cx);
14803            }
14804        }
14805    }
14806
14807    fn fold_at_level(
14808        &mut self,
14809        fold_at: &FoldAtLevel,
14810        window: &mut Window,
14811        cx: &mut Context<Self>,
14812    ) {
14813        if !self.buffer.read(cx).is_singleton() {
14814            return;
14815        }
14816
14817        let fold_at_level = fold_at.0;
14818        let snapshot = self.buffer.read(cx).snapshot(cx);
14819        let mut to_fold = Vec::new();
14820        let mut stack = vec![(0, snapshot.max_row().0, 1)];
14821
14822        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
14823            while start_row < end_row {
14824                match self
14825                    .snapshot(window, cx)
14826                    .crease_for_buffer_row(MultiBufferRow(start_row))
14827                {
14828                    Some(crease) => {
14829                        let nested_start_row = crease.range().start.row + 1;
14830                        let nested_end_row = crease.range().end.row;
14831
14832                        if current_level < fold_at_level {
14833                            stack.push((nested_start_row, nested_end_row, current_level + 1));
14834                        } else if current_level == fold_at_level {
14835                            to_fold.push(crease);
14836                        }
14837
14838                        start_row = nested_end_row + 1;
14839                    }
14840                    None => start_row += 1,
14841                }
14842            }
14843        }
14844
14845        self.fold_creases(to_fold, true, window, cx);
14846    }
14847
14848    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
14849        if self.buffer.read(cx).is_singleton() {
14850            let mut fold_ranges = Vec::new();
14851            let snapshot = self.buffer.read(cx).snapshot(cx);
14852
14853            for row in 0..snapshot.max_row().0 {
14854                if let Some(foldable_range) = self
14855                    .snapshot(window, cx)
14856                    .crease_for_buffer_row(MultiBufferRow(row))
14857                {
14858                    fold_ranges.push(foldable_range);
14859                }
14860            }
14861
14862            self.fold_creases(fold_ranges, true, window, cx);
14863        } else {
14864            self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
14865                editor
14866                    .update_in(cx, |editor, _, cx| {
14867                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14868                            editor.fold_buffer(buffer_id, cx);
14869                        }
14870                    })
14871                    .ok();
14872            });
14873        }
14874    }
14875
14876    pub fn fold_function_bodies(
14877        &mut self,
14878        _: &actions::FoldFunctionBodies,
14879        window: &mut Window,
14880        cx: &mut Context<Self>,
14881    ) {
14882        let snapshot = self.buffer.read(cx).snapshot(cx);
14883
14884        let ranges = snapshot
14885            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
14886            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
14887            .collect::<Vec<_>>();
14888
14889        let creases = ranges
14890            .into_iter()
14891            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
14892            .collect();
14893
14894        self.fold_creases(creases, true, window, cx);
14895    }
14896
14897    pub fn fold_recursive(
14898        &mut self,
14899        _: &actions::FoldRecursive,
14900        window: &mut Window,
14901        cx: &mut Context<Self>,
14902    ) {
14903        let mut to_fold = Vec::new();
14904        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14905        let selections = self.selections.all_adjusted(cx);
14906
14907        for selection in selections {
14908            let range = selection.range().sorted();
14909            let buffer_start_row = range.start.row;
14910
14911            if range.start.row != range.end.row {
14912                let mut found = false;
14913                for row in range.start.row..=range.end.row {
14914                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14915                        found = true;
14916                        to_fold.push(crease);
14917                    }
14918                }
14919                if found {
14920                    continue;
14921                }
14922            }
14923
14924            for row in (0..=range.start.row).rev() {
14925                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14926                    if crease.range().end.row >= buffer_start_row {
14927                        to_fold.push(crease);
14928                    } else {
14929                        break;
14930                    }
14931                }
14932            }
14933        }
14934
14935        self.fold_creases(to_fold, true, window, cx);
14936    }
14937
14938    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
14939        let buffer_row = fold_at.buffer_row;
14940        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14941
14942        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
14943            let autoscroll = self
14944                .selections
14945                .all::<Point>(cx)
14946                .iter()
14947                .any(|selection| crease.range().overlaps(&selection.range()));
14948
14949            self.fold_creases(vec![crease], autoscroll, window, cx);
14950        }
14951    }
14952
14953    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
14954        if self.is_singleton(cx) {
14955            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14956            let buffer = &display_map.buffer_snapshot;
14957            let selections = self.selections.all::<Point>(cx);
14958            let ranges = selections
14959                .iter()
14960                .map(|s| {
14961                    let range = s.display_range(&display_map).sorted();
14962                    let mut start = range.start.to_point(&display_map);
14963                    let mut end = range.end.to_point(&display_map);
14964                    start.column = 0;
14965                    end.column = buffer.line_len(MultiBufferRow(end.row));
14966                    start..end
14967                })
14968                .collect::<Vec<_>>();
14969
14970            self.unfold_ranges(&ranges, true, true, cx);
14971        } else {
14972            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14973            let buffer_ids = self
14974                .selections
14975                .disjoint_anchor_ranges()
14976                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14977                .collect::<HashSet<_>>();
14978            for buffer_id in buffer_ids {
14979                self.unfold_buffer(buffer_id, cx);
14980            }
14981        }
14982    }
14983
14984    pub fn unfold_recursive(
14985        &mut self,
14986        _: &UnfoldRecursive,
14987        _window: &mut Window,
14988        cx: &mut Context<Self>,
14989    ) {
14990        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14991        let selections = self.selections.all::<Point>(cx);
14992        let ranges = selections
14993            .iter()
14994            .map(|s| {
14995                let mut range = s.display_range(&display_map).sorted();
14996                *range.start.column_mut() = 0;
14997                *range.end.column_mut() = display_map.line_len(range.end.row());
14998                let start = range.start.to_point(&display_map);
14999                let end = range.end.to_point(&display_map);
15000                start..end
15001            })
15002            .collect::<Vec<_>>();
15003
15004        self.unfold_ranges(&ranges, true, true, cx);
15005    }
15006
15007    pub fn unfold_at(
15008        &mut self,
15009        unfold_at: &UnfoldAt,
15010        _window: &mut Window,
15011        cx: &mut Context<Self>,
15012    ) {
15013        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15014
15015        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
15016            ..Point::new(
15017                unfold_at.buffer_row.0,
15018                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
15019            );
15020
15021        let autoscroll = self
15022            .selections
15023            .all::<Point>(cx)
15024            .iter()
15025            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15026
15027        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15028    }
15029
15030    pub fn unfold_all(
15031        &mut self,
15032        _: &actions::UnfoldAll,
15033        _window: &mut Window,
15034        cx: &mut Context<Self>,
15035    ) {
15036        if self.buffer.read(cx).is_singleton() {
15037            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15038            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15039        } else {
15040            self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15041                editor
15042                    .update(cx, |editor, cx| {
15043                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15044                            editor.unfold_buffer(buffer_id, cx);
15045                        }
15046                    })
15047                    .ok();
15048            });
15049        }
15050    }
15051
15052    pub fn fold_selected_ranges(
15053        &mut self,
15054        _: &FoldSelectedRanges,
15055        window: &mut Window,
15056        cx: &mut Context<Self>,
15057    ) {
15058        let selections = self.selections.all_adjusted(cx);
15059        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15060        let ranges = selections
15061            .into_iter()
15062            .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15063            .collect::<Vec<_>>();
15064        self.fold_creases(ranges, true, window, cx);
15065    }
15066
15067    pub fn fold_ranges<T: ToOffset + Clone>(
15068        &mut self,
15069        ranges: Vec<Range<T>>,
15070        auto_scroll: bool,
15071        window: &mut Window,
15072        cx: &mut Context<Self>,
15073    ) {
15074        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15075        let ranges = ranges
15076            .into_iter()
15077            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15078            .collect::<Vec<_>>();
15079        self.fold_creases(ranges, auto_scroll, window, cx);
15080    }
15081
15082    pub fn fold_creases<T: ToOffset + Clone>(
15083        &mut self,
15084        creases: Vec<Crease<T>>,
15085        auto_scroll: bool,
15086        window: &mut Window,
15087        cx: &mut Context<Self>,
15088    ) {
15089        if creases.is_empty() {
15090            return;
15091        }
15092
15093        let mut buffers_affected = HashSet::default();
15094        let multi_buffer = self.buffer().read(cx);
15095        for crease in &creases {
15096            if let Some((_, buffer, _)) =
15097                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15098            {
15099                buffers_affected.insert(buffer.read(cx).remote_id());
15100            };
15101        }
15102
15103        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15104
15105        if auto_scroll {
15106            self.request_autoscroll(Autoscroll::fit(), cx);
15107        }
15108
15109        cx.notify();
15110
15111        if let Some(active_diagnostics) = self.active_diagnostics.take() {
15112            // Clear diagnostics block when folding a range that contains it.
15113            let snapshot = self.snapshot(window, cx);
15114            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
15115                drop(snapshot);
15116                self.active_diagnostics = Some(active_diagnostics);
15117                self.dismiss_diagnostics(cx);
15118            } else {
15119                self.active_diagnostics = Some(active_diagnostics);
15120            }
15121        }
15122
15123        self.scrollbar_marker_state.dirty = true;
15124        self.folds_did_change(cx);
15125    }
15126
15127    /// Removes any folds whose ranges intersect any of the given ranges.
15128    pub fn unfold_ranges<T: ToOffset + Clone>(
15129        &mut self,
15130        ranges: &[Range<T>],
15131        inclusive: bool,
15132        auto_scroll: bool,
15133        cx: &mut Context<Self>,
15134    ) {
15135        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15136            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15137        });
15138        self.folds_did_change(cx);
15139    }
15140
15141    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15142        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15143            return;
15144        }
15145        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15146        self.display_map.update(cx, |display_map, cx| {
15147            display_map.fold_buffers([buffer_id], cx)
15148        });
15149        cx.emit(EditorEvent::BufferFoldToggled {
15150            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15151            folded: true,
15152        });
15153        cx.notify();
15154    }
15155
15156    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15157        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15158            return;
15159        }
15160        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15161        self.display_map.update(cx, |display_map, cx| {
15162            display_map.unfold_buffers([buffer_id], cx);
15163        });
15164        cx.emit(EditorEvent::BufferFoldToggled {
15165            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15166            folded: false,
15167        });
15168        cx.notify();
15169    }
15170
15171    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15172        self.display_map.read(cx).is_buffer_folded(buffer)
15173    }
15174
15175    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15176        self.display_map.read(cx).folded_buffers()
15177    }
15178
15179    pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15180        self.display_map.update(cx, |display_map, cx| {
15181            display_map.disable_header_for_buffer(buffer_id, cx);
15182        });
15183        cx.notify();
15184    }
15185
15186    /// Removes any folds with the given ranges.
15187    pub fn remove_folds_with_type<T: ToOffset + Clone>(
15188        &mut self,
15189        ranges: &[Range<T>],
15190        type_id: TypeId,
15191        auto_scroll: bool,
15192        cx: &mut Context<Self>,
15193    ) {
15194        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15195            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15196        });
15197        self.folds_did_change(cx);
15198    }
15199
15200    fn remove_folds_with<T: ToOffset + Clone>(
15201        &mut self,
15202        ranges: &[Range<T>],
15203        auto_scroll: bool,
15204        cx: &mut Context<Self>,
15205        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15206    ) {
15207        if ranges.is_empty() {
15208            return;
15209        }
15210
15211        let mut buffers_affected = HashSet::default();
15212        let multi_buffer = self.buffer().read(cx);
15213        for range in ranges {
15214            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15215                buffers_affected.insert(buffer.read(cx).remote_id());
15216            };
15217        }
15218
15219        self.display_map.update(cx, update);
15220
15221        if auto_scroll {
15222            self.request_autoscroll(Autoscroll::fit(), cx);
15223        }
15224
15225        cx.notify();
15226        self.scrollbar_marker_state.dirty = true;
15227        self.active_indent_guides_state.dirty = true;
15228    }
15229
15230    pub fn update_fold_widths(
15231        &mut self,
15232        widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15233        cx: &mut Context<Self>,
15234    ) -> bool {
15235        self.display_map
15236            .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15237    }
15238
15239    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15240        self.display_map.read(cx).fold_placeholder.clone()
15241    }
15242
15243    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15244        self.buffer.update(cx, |buffer, cx| {
15245            buffer.set_all_diff_hunks_expanded(cx);
15246        });
15247    }
15248
15249    pub fn expand_all_diff_hunks(
15250        &mut self,
15251        _: &ExpandAllDiffHunks,
15252        _window: &mut Window,
15253        cx: &mut Context<Self>,
15254    ) {
15255        self.buffer.update(cx, |buffer, cx| {
15256            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15257        });
15258    }
15259
15260    pub fn toggle_selected_diff_hunks(
15261        &mut self,
15262        _: &ToggleSelectedDiffHunks,
15263        _window: &mut Window,
15264        cx: &mut Context<Self>,
15265    ) {
15266        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15267        self.toggle_diff_hunks_in_ranges(ranges, cx);
15268    }
15269
15270    pub fn diff_hunks_in_ranges<'a>(
15271        &'a self,
15272        ranges: &'a [Range<Anchor>],
15273        buffer: &'a MultiBufferSnapshot,
15274    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15275        ranges.iter().flat_map(move |range| {
15276            let end_excerpt_id = range.end.excerpt_id;
15277            let range = range.to_point(buffer);
15278            let mut peek_end = range.end;
15279            if range.end.row < buffer.max_row().0 {
15280                peek_end = Point::new(range.end.row + 1, 0);
15281            }
15282            buffer
15283                .diff_hunks_in_range(range.start..peek_end)
15284                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15285        })
15286    }
15287
15288    pub fn has_stageable_diff_hunks_in_ranges(
15289        &self,
15290        ranges: &[Range<Anchor>],
15291        snapshot: &MultiBufferSnapshot,
15292    ) -> bool {
15293        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15294        hunks.any(|hunk| hunk.status().has_secondary_hunk())
15295    }
15296
15297    pub fn toggle_staged_selected_diff_hunks(
15298        &mut self,
15299        _: &::git::ToggleStaged,
15300        _: &mut Window,
15301        cx: &mut Context<Self>,
15302    ) {
15303        let snapshot = self.buffer.read(cx).snapshot(cx);
15304        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15305        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15306        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15307    }
15308
15309    pub fn set_render_diff_hunk_controls(
15310        &mut self,
15311        render_diff_hunk_controls: RenderDiffHunkControlsFn,
15312        cx: &mut Context<Self>,
15313    ) {
15314        self.render_diff_hunk_controls = render_diff_hunk_controls;
15315        cx.notify();
15316    }
15317
15318    pub fn stage_and_next(
15319        &mut self,
15320        _: &::git::StageAndNext,
15321        window: &mut Window,
15322        cx: &mut Context<Self>,
15323    ) {
15324        self.do_stage_or_unstage_and_next(true, window, cx);
15325    }
15326
15327    pub fn unstage_and_next(
15328        &mut self,
15329        _: &::git::UnstageAndNext,
15330        window: &mut Window,
15331        cx: &mut Context<Self>,
15332    ) {
15333        self.do_stage_or_unstage_and_next(false, window, cx);
15334    }
15335
15336    pub fn stage_or_unstage_diff_hunks(
15337        &mut self,
15338        stage: bool,
15339        ranges: Vec<Range<Anchor>>,
15340        cx: &mut Context<Self>,
15341    ) {
15342        let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15343        cx.spawn(async move |this, cx| {
15344            task.await?;
15345            this.update(cx, |this, cx| {
15346                let snapshot = this.buffer.read(cx).snapshot(cx);
15347                let chunk_by = this
15348                    .diff_hunks_in_ranges(&ranges, &snapshot)
15349                    .chunk_by(|hunk| hunk.buffer_id);
15350                for (buffer_id, hunks) in &chunk_by {
15351                    this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15352                }
15353            })
15354        })
15355        .detach_and_log_err(cx);
15356    }
15357
15358    fn save_buffers_for_ranges_if_needed(
15359        &mut self,
15360        ranges: &[Range<Anchor>],
15361        cx: &mut Context<Editor>,
15362    ) -> Task<Result<()>> {
15363        let multibuffer = self.buffer.read(cx);
15364        let snapshot = multibuffer.read(cx);
15365        let buffer_ids: HashSet<_> = ranges
15366            .iter()
15367            .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15368            .collect();
15369        drop(snapshot);
15370
15371        let mut buffers = HashSet::default();
15372        for buffer_id in buffer_ids {
15373            if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15374                let buffer = buffer_entity.read(cx);
15375                if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15376                {
15377                    buffers.insert(buffer_entity);
15378                }
15379            }
15380        }
15381
15382        if let Some(project) = &self.project {
15383            project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15384        } else {
15385            Task::ready(Ok(()))
15386        }
15387    }
15388
15389    fn do_stage_or_unstage_and_next(
15390        &mut self,
15391        stage: bool,
15392        window: &mut Window,
15393        cx: &mut Context<Self>,
15394    ) {
15395        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15396
15397        if ranges.iter().any(|range| range.start != range.end) {
15398            self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15399            return;
15400        }
15401
15402        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15403        let snapshot = self.snapshot(window, cx);
15404        let position = self.selections.newest::<Point>(cx).head();
15405        let mut row = snapshot
15406            .buffer_snapshot
15407            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15408            .find(|hunk| hunk.row_range.start.0 > position.row)
15409            .map(|hunk| hunk.row_range.start);
15410
15411        let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15412        // Outside of the project diff editor, wrap around to the beginning.
15413        if !all_diff_hunks_expanded {
15414            row = row.or_else(|| {
15415                snapshot
15416                    .buffer_snapshot
15417                    .diff_hunks_in_range(Point::zero()..position)
15418                    .find(|hunk| hunk.row_range.end.0 < position.row)
15419                    .map(|hunk| hunk.row_range.start)
15420            });
15421        }
15422
15423        if let Some(row) = row {
15424            let destination = Point::new(row.0, 0);
15425            let autoscroll = Autoscroll::center();
15426
15427            self.unfold_ranges(&[destination..destination], false, false, cx);
15428            self.change_selections(Some(autoscroll), window, cx, |s| {
15429                s.select_ranges([destination..destination]);
15430            });
15431        }
15432    }
15433
15434    fn do_stage_or_unstage(
15435        &self,
15436        stage: bool,
15437        buffer_id: BufferId,
15438        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15439        cx: &mut App,
15440    ) -> Option<()> {
15441        let project = self.project.as_ref()?;
15442        let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15443        let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15444        let buffer_snapshot = buffer.read(cx).snapshot();
15445        let file_exists = buffer_snapshot
15446            .file()
15447            .is_some_and(|file| file.disk_state().exists());
15448        diff.update(cx, |diff, cx| {
15449            diff.stage_or_unstage_hunks(
15450                stage,
15451                &hunks
15452                    .map(|hunk| buffer_diff::DiffHunk {
15453                        buffer_range: hunk.buffer_range,
15454                        diff_base_byte_range: hunk.diff_base_byte_range,
15455                        secondary_status: hunk.secondary_status,
15456                        range: Point::zero()..Point::zero(), // unused
15457                    })
15458                    .collect::<Vec<_>>(),
15459                &buffer_snapshot,
15460                file_exists,
15461                cx,
15462            )
15463        });
15464        None
15465    }
15466
15467    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15468        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15469        self.buffer
15470            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15471    }
15472
15473    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
15474        self.buffer.update(cx, |buffer, cx| {
15475            let ranges = vec![Anchor::min()..Anchor::max()];
15476            if !buffer.all_diff_hunks_expanded()
15477                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
15478            {
15479                buffer.collapse_diff_hunks(ranges, cx);
15480                true
15481            } else {
15482                false
15483            }
15484        })
15485    }
15486
15487    fn toggle_diff_hunks_in_ranges(
15488        &mut self,
15489        ranges: Vec<Range<Anchor>>,
15490        cx: &mut Context<Editor>,
15491    ) {
15492        self.buffer.update(cx, |buffer, cx| {
15493            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
15494            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
15495        })
15496    }
15497
15498    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15499        self.buffer.update(cx, |buffer, cx| {
15500            let snapshot = buffer.snapshot(cx);
15501            let excerpt_id = range.end.excerpt_id;
15502            let point_range = range.to_point(&snapshot);
15503            let expand = !buffer.single_hunk_is_expanded(range, cx);
15504            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15505        })
15506    }
15507
15508    pub(crate) fn apply_all_diff_hunks(
15509        &mut self,
15510        _: &ApplyAllDiffHunks,
15511        window: &mut Window,
15512        cx: &mut Context<Self>,
15513    ) {
15514        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15515
15516        let buffers = self.buffer.read(cx).all_buffers();
15517        for branch_buffer in buffers {
15518            branch_buffer.update(cx, |branch_buffer, cx| {
15519                branch_buffer.merge_into_base(Vec::new(), cx);
15520            });
15521        }
15522
15523        if let Some(project) = self.project.clone() {
15524            self.save(true, project, window, cx).detach_and_log_err(cx);
15525        }
15526    }
15527
15528    pub(crate) fn apply_selected_diff_hunks(
15529        &mut self,
15530        _: &ApplyDiffHunk,
15531        window: &mut Window,
15532        cx: &mut Context<Self>,
15533    ) {
15534        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15535        let snapshot = self.snapshot(window, cx);
15536        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15537        let mut ranges_by_buffer = HashMap::default();
15538        self.transact(window, cx, |editor, _window, cx| {
15539            for hunk in hunks {
15540                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15541                    ranges_by_buffer
15542                        .entry(buffer.clone())
15543                        .or_insert_with(Vec::new)
15544                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15545                }
15546            }
15547
15548            for (buffer, ranges) in ranges_by_buffer {
15549                buffer.update(cx, |buffer, cx| {
15550                    buffer.merge_into_base(ranges, cx);
15551                });
15552            }
15553        });
15554
15555        if let Some(project) = self.project.clone() {
15556            self.save(true, project, window, cx).detach_and_log_err(cx);
15557        }
15558    }
15559
15560    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15561        if hovered != self.gutter_hovered {
15562            self.gutter_hovered = hovered;
15563            cx.notify();
15564        }
15565    }
15566
15567    pub fn insert_blocks(
15568        &mut self,
15569        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15570        autoscroll: Option<Autoscroll>,
15571        cx: &mut Context<Self>,
15572    ) -> Vec<CustomBlockId> {
15573        let blocks = self
15574            .display_map
15575            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15576        if let Some(autoscroll) = autoscroll {
15577            self.request_autoscroll(autoscroll, cx);
15578        }
15579        cx.notify();
15580        blocks
15581    }
15582
15583    pub fn resize_blocks(
15584        &mut self,
15585        heights: HashMap<CustomBlockId, u32>,
15586        autoscroll: Option<Autoscroll>,
15587        cx: &mut Context<Self>,
15588    ) {
15589        self.display_map
15590            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15591        if let Some(autoscroll) = autoscroll {
15592            self.request_autoscroll(autoscroll, cx);
15593        }
15594        cx.notify();
15595    }
15596
15597    pub fn replace_blocks(
15598        &mut self,
15599        renderers: HashMap<CustomBlockId, RenderBlock>,
15600        autoscroll: Option<Autoscroll>,
15601        cx: &mut Context<Self>,
15602    ) {
15603        self.display_map
15604            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15605        if let Some(autoscroll) = autoscroll {
15606            self.request_autoscroll(autoscroll, cx);
15607        }
15608        cx.notify();
15609    }
15610
15611    pub fn remove_blocks(
15612        &mut self,
15613        block_ids: HashSet<CustomBlockId>,
15614        autoscroll: Option<Autoscroll>,
15615        cx: &mut Context<Self>,
15616    ) {
15617        self.display_map.update(cx, |display_map, cx| {
15618            display_map.remove_blocks(block_ids, cx)
15619        });
15620        if let Some(autoscroll) = autoscroll {
15621            self.request_autoscroll(autoscroll, cx);
15622        }
15623        cx.notify();
15624    }
15625
15626    pub fn row_for_block(
15627        &self,
15628        block_id: CustomBlockId,
15629        cx: &mut Context<Self>,
15630    ) -> Option<DisplayRow> {
15631        self.display_map
15632            .update(cx, |map, cx| map.row_for_block(block_id, cx))
15633    }
15634
15635    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15636        self.focused_block = Some(focused_block);
15637    }
15638
15639    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15640        self.focused_block.take()
15641    }
15642
15643    pub fn insert_creases(
15644        &mut self,
15645        creases: impl IntoIterator<Item = Crease<Anchor>>,
15646        cx: &mut Context<Self>,
15647    ) -> Vec<CreaseId> {
15648        self.display_map
15649            .update(cx, |map, cx| map.insert_creases(creases, cx))
15650    }
15651
15652    pub fn remove_creases(
15653        &mut self,
15654        ids: impl IntoIterator<Item = CreaseId>,
15655        cx: &mut Context<Self>,
15656    ) {
15657        self.display_map
15658            .update(cx, |map, cx| map.remove_creases(ids, cx));
15659    }
15660
15661    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15662        self.display_map
15663            .update(cx, |map, cx| map.snapshot(cx))
15664            .longest_row()
15665    }
15666
15667    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15668        self.display_map
15669            .update(cx, |map, cx| map.snapshot(cx))
15670            .max_point()
15671    }
15672
15673    pub fn text(&self, cx: &App) -> String {
15674        self.buffer.read(cx).read(cx).text()
15675    }
15676
15677    pub fn is_empty(&self, cx: &App) -> bool {
15678        self.buffer.read(cx).read(cx).is_empty()
15679    }
15680
15681    pub fn text_option(&self, cx: &App) -> Option<String> {
15682        let text = self.text(cx);
15683        let text = text.trim();
15684
15685        if text.is_empty() {
15686            return None;
15687        }
15688
15689        Some(text.to_string())
15690    }
15691
15692    pub fn set_text(
15693        &mut self,
15694        text: impl Into<Arc<str>>,
15695        window: &mut Window,
15696        cx: &mut Context<Self>,
15697    ) {
15698        self.transact(window, cx, |this, _, cx| {
15699            this.buffer
15700                .read(cx)
15701                .as_singleton()
15702                .expect("you can only call set_text on editors for singleton buffers")
15703                .update(cx, |buffer, cx| buffer.set_text(text, cx));
15704        });
15705    }
15706
15707    pub fn display_text(&self, cx: &mut App) -> String {
15708        self.display_map
15709            .update(cx, |map, cx| map.snapshot(cx))
15710            .text()
15711    }
15712
15713    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15714        let mut wrap_guides = smallvec::smallvec![];
15715
15716        if self.show_wrap_guides == Some(false) {
15717            return wrap_guides;
15718        }
15719
15720        let settings = self.buffer.read(cx).language_settings(cx);
15721        if settings.show_wrap_guides {
15722            match self.soft_wrap_mode(cx) {
15723                SoftWrap::Column(soft_wrap) => {
15724                    wrap_guides.push((soft_wrap as usize, true));
15725                }
15726                SoftWrap::Bounded(soft_wrap) => {
15727                    wrap_guides.push((soft_wrap as usize, true));
15728                }
15729                SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15730            }
15731            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15732        }
15733
15734        wrap_guides
15735    }
15736
15737    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15738        let settings = self.buffer.read(cx).language_settings(cx);
15739        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15740        match mode {
15741            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
15742                SoftWrap::None
15743            }
15744            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
15745            language_settings::SoftWrap::PreferredLineLength => {
15746                SoftWrap::Column(settings.preferred_line_length)
15747            }
15748            language_settings::SoftWrap::Bounded => {
15749                SoftWrap::Bounded(settings.preferred_line_length)
15750            }
15751        }
15752    }
15753
15754    pub fn set_soft_wrap_mode(
15755        &mut self,
15756        mode: language_settings::SoftWrap,
15757
15758        cx: &mut Context<Self>,
15759    ) {
15760        self.soft_wrap_mode_override = Some(mode);
15761        cx.notify();
15762    }
15763
15764    pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
15765        self.hard_wrap = hard_wrap;
15766        cx.notify();
15767    }
15768
15769    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
15770        self.text_style_refinement = Some(style);
15771    }
15772
15773    /// called by the Element so we know what style we were most recently rendered with.
15774    pub(crate) fn set_style(
15775        &mut self,
15776        style: EditorStyle,
15777        window: &mut Window,
15778        cx: &mut Context<Self>,
15779    ) {
15780        let rem_size = window.rem_size();
15781        self.display_map.update(cx, |map, cx| {
15782            map.set_font(
15783                style.text.font(),
15784                style.text.font_size.to_pixels(rem_size),
15785                cx,
15786            )
15787        });
15788        self.style = Some(style);
15789    }
15790
15791    pub fn style(&self) -> Option<&EditorStyle> {
15792        self.style.as_ref()
15793    }
15794
15795    // Called by the element. This method is not designed to be called outside of the editor
15796    // element's layout code because it does not notify when rewrapping is computed synchronously.
15797    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
15798        self.display_map
15799            .update(cx, |map, cx| map.set_wrap_width(width, cx))
15800    }
15801
15802    pub fn set_soft_wrap(&mut self) {
15803        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
15804    }
15805
15806    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
15807        if self.soft_wrap_mode_override.is_some() {
15808            self.soft_wrap_mode_override.take();
15809        } else {
15810            let soft_wrap = match self.soft_wrap_mode(cx) {
15811                SoftWrap::GitDiff => return,
15812                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
15813                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
15814                    language_settings::SoftWrap::None
15815                }
15816            };
15817            self.soft_wrap_mode_override = Some(soft_wrap);
15818        }
15819        cx.notify();
15820    }
15821
15822    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
15823        let Some(workspace) = self.workspace() else {
15824            return;
15825        };
15826        let fs = workspace.read(cx).app_state().fs.clone();
15827        let current_show = TabBarSettings::get_global(cx).show;
15828        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
15829            setting.show = Some(!current_show);
15830        });
15831    }
15832
15833    pub fn toggle_indent_guides(
15834        &mut self,
15835        _: &ToggleIndentGuides,
15836        _: &mut Window,
15837        cx: &mut Context<Self>,
15838    ) {
15839        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
15840            self.buffer
15841                .read(cx)
15842                .language_settings(cx)
15843                .indent_guides
15844                .enabled
15845        });
15846        self.show_indent_guides = Some(!currently_enabled);
15847        cx.notify();
15848    }
15849
15850    fn should_show_indent_guides(&self) -> Option<bool> {
15851        self.show_indent_guides
15852    }
15853
15854    pub fn toggle_line_numbers(
15855        &mut self,
15856        _: &ToggleLineNumbers,
15857        _: &mut Window,
15858        cx: &mut Context<Self>,
15859    ) {
15860        let mut editor_settings = EditorSettings::get_global(cx).clone();
15861        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
15862        EditorSettings::override_global(editor_settings, cx);
15863    }
15864
15865    pub fn line_numbers_enabled(&self, cx: &App) -> bool {
15866        if let Some(show_line_numbers) = self.show_line_numbers {
15867            return show_line_numbers;
15868        }
15869        EditorSettings::get_global(cx).gutter.line_numbers
15870    }
15871
15872    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
15873        self.use_relative_line_numbers
15874            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
15875    }
15876
15877    pub fn toggle_relative_line_numbers(
15878        &mut self,
15879        _: &ToggleRelativeLineNumbers,
15880        _: &mut Window,
15881        cx: &mut Context<Self>,
15882    ) {
15883        let is_relative = self.should_use_relative_line_numbers(cx);
15884        self.set_relative_line_number(Some(!is_relative), cx)
15885    }
15886
15887    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
15888        self.use_relative_line_numbers = is_relative;
15889        cx.notify();
15890    }
15891
15892    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
15893        self.show_gutter = show_gutter;
15894        cx.notify();
15895    }
15896
15897    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
15898        self.show_scrollbars = show_scrollbars;
15899        cx.notify();
15900    }
15901
15902    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
15903        self.show_line_numbers = Some(show_line_numbers);
15904        cx.notify();
15905    }
15906
15907    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
15908        self.show_git_diff_gutter = Some(show_git_diff_gutter);
15909        cx.notify();
15910    }
15911
15912    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
15913        self.show_code_actions = Some(show_code_actions);
15914        cx.notify();
15915    }
15916
15917    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
15918        self.show_runnables = Some(show_runnables);
15919        cx.notify();
15920    }
15921
15922    pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
15923        self.show_breakpoints = Some(show_breakpoints);
15924        cx.notify();
15925    }
15926
15927    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
15928        if self.display_map.read(cx).masked != masked {
15929            self.display_map.update(cx, |map, _| map.masked = masked);
15930        }
15931        cx.notify()
15932    }
15933
15934    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
15935        self.show_wrap_guides = Some(show_wrap_guides);
15936        cx.notify();
15937    }
15938
15939    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
15940        self.show_indent_guides = Some(show_indent_guides);
15941        cx.notify();
15942    }
15943
15944    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
15945        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
15946            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
15947                if let Some(dir) = file.abs_path(cx).parent() {
15948                    return Some(dir.to_owned());
15949                }
15950            }
15951
15952            if let Some(project_path) = buffer.read(cx).project_path(cx) {
15953                return Some(project_path.path.to_path_buf());
15954            }
15955        }
15956
15957        None
15958    }
15959
15960    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
15961        self.active_excerpt(cx)?
15962            .1
15963            .read(cx)
15964            .file()
15965            .and_then(|f| f.as_local())
15966    }
15967
15968    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15969        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15970            let buffer = buffer.read(cx);
15971            if let Some(project_path) = buffer.project_path(cx) {
15972                let project = self.project.as_ref()?.read(cx);
15973                project.absolute_path(&project_path, cx)
15974            } else {
15975                buffer
15976                    .file()
15977                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
15978            }
15979        })
15980    }
15981
15982    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15983        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15984            let project_path = buffer.read(cx).project_path(cx)?;
15985            let project = self.project.as_ref()?.read(cx);
15986            let entry = project.entry_for_path(&project_path, cx)?;
15987            let path = entry.path.to_path_buf();
15988            Some(path)
15989        })
15990    }
15991
15992    pub fn reveal_in_finder(
15993        &mut self,
15994        _: &RevealInFileManager,
15995        _window: &mut Window,
15996        cx: &mut Context<Self>,
15997    ) {
15998        if let Some(target) = self.target_file(cx) {
15999            cx.reveal_path(&target.abs_path(cx));
16000        }
16001    }
16002
16003    pub fn copy_path(
16004        &mut self,
16005        _: &zed_actions::workspace::CopyPath,
16006        _window: &mut Window,
16007        cx: &mut Context<Self>,
16008    ) {
16009        if let Some(path) = self.target_file_abs_path(cx) {
16010            if let Some(path) = path.to_str() {
16011                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16012            }
16013        }
16014    }
16015
16016    pub fn copy_relative_path(
16017        &mut self,
16018        _: &zed_actions::workspace::CopyRelativePath,
16019        _window: &mut Window,
16020        cx: &mut Context<Self>,
16021    ) {
16022        if let Some(path) = self.target_file_path(cx) {
16023            if let Some(path) = path.to_str() {
16024                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16025            }
16026        }
16027    }
16028
16029    pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16030        if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16031            buffer.read(cx).project_path(cx)
16032        } else {
16033            None
16034        }
16035    }
16036
16037    // Returns true if the editor handled a go-to-line request
16038    pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16039        maybe!({
16040            let breakpoint_store = self.breakpoint_store.as_ref()?;
16041
16042            let Some((_, _, active_position)) =
16043                breakpoint_store.read(cx).active_position().cloned()
16044            else {
16045                self.clear_row_highlights::<DebugCurrentRowHighlight>();
16046                return None;
16047            };
16048
16049            let snapshot = self
16050                .project
16051                .as_ref()?
16052                .read(cx)
16053                .buffer_for_id(active_position.buffer_id?, cx)?
16054                .read(cx)
16055                .snapshot();
16056
16057            let mut handled = false;
16058            for (id, ExcerptRange { context, .. }) in self
16059                .buffer
16060                .read(cx)
16061                .excerpts_for_buffer(active_position.buffer_id?, cx)
16062            {
16063                if context.start.cmp(&active_position, &snapshot).is_ge()
16064                    || context.end.cmp(&active_position, &snapshot).is_lt()
16065                {
16066                    continue;
16067                }
16068                let snapshot = self.buffer.read(cx).snapshot(cx);
16069                let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
16070
16071                handled = true;
16072                self.clear_row_highlights::<DebugCurrentRowHighlight>();
16073                self.go_to_line::<DebugCurrentRowHighlight>(
16074                    multibuffer_anchor,
16075                    Some(cx.theme().colors().editor_debugger_active_line_background),
16076                    window,
16077                    cx,
16078                );
16079
16080                cx.notify();
16081            }
16082            handled.then_some(())
16083        })
16084        .is_some()
16085    }
16086
16087    pub fn copy_file_name_without_extension(
16088        &mut self,
16089        _: &CopyFileNameWithoutExtension,
16090        _: &mut Window,
16091        cx: &mut Context<Self>,
16092    ) {
16093        if let Some(file) = self.target_file(cx) {
16094            if let Some(file_stem) = file.path().file_stem() {
16095                if let Some(name) = file_stem.to_str() {
16096                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16097                }
16098            }
16099        }
16100    }
16101
16102    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16103        if let Some(file) = self.target_file(cx) {
16104            if let Some(file_name) = file.path().file_name() {
16105                if let Some(name) = file_name.to_str() {
16106                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16107                }
16108            }
16109        }
16110    }
16111
16112    pub fn toggle_git_blame(
16113        &mut self,
16114        _: &::git::Blame,
16115        window: &mut Window,
16116        cx: &mut Context<Self>,
16117    ) {
16118        self.show_git_blame_gutter = !self.show_git_blame_gutter;
16119
16120        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16121            self.start_git_blame(true, window, cx);
16122        }
16123
16124        cx.notify();
16125    }
16126
16127    pub fn toggle_git_blame_inline(
16128        &mut self,
16129        _: &ToggleGitBlameInline,
16130        window: &mut Window,
16131        cx: &mut Context<Self>,
16132    ) {
16133        self.toggle_git_blame_inline_internal(true, window, cx);
16134        cx.notify();
16135    }
16136
16137    pub fn open_git_blame_commit(
16138        &mut self,
16139        _: &OpenGitBlameCommit,
16140        window: &mut Window,
16141        cx: &mut Context<Self>,
16142    ) {
16143        self.open_git_blame_commit_internal(window, cx);
16144    }
16145
16146    fn open_git_blame_commit_internal(
16147        &mut self,
16148        window: &mut Window,
16149        cx: &mut Context<Self>,
16150    ) -> Option<()> {
16151        let blame = self.blame.as_ref()?;
16152        let snapshot = self.snapshot(window, cx);
16153        let cursor = self.selections.newest::<Point>(cx).head();
16154        let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16155        let blame_entry = blame
16156            .update(cx, |blame, cx| {
16157                blame
16158                    .blame_for_rows(
16159                        &[RowInfo {
16160                            buffer_id: Some(buffer.remote_id()),
16161                            buffer_row: Some(point.row),
16162                            ..Default::default()
16163                        }],
16164                        cx,
16165                    )
16166                    .next()
16167            })
16168            .flatten()?;
16169        let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16170        let repo = blame.read(cx).repository(cx)?;
16171        let workspace = self.workspace()?.downgrade();
16172        renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16173        None
16174    }
16175
16176    pub fn git_blame_inline_enabled(&self) -> bool {
16177        self.git_blame_inline_enabled
16178    }
16179
16180    pub fn toggle_selection_menu(
16181        &mut self,
16182        _: &ToggleSelectionMenu,
16183        _: &mut Window,
16184        cx: &mut Context<Self>,
16185    ) {
16186        self.show_selection_menu = self
16187            .show_selection_menu
16188            .map(|show_selections_menu| !show_selections_menu)
16189            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16190
16191        cx.notify();
16192    }
16193
16194    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16195        self.show_selection_menu
16196            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16197    }
16198
16199    fn start_git_blame(
16200        &mut self,
16201        user_triggered: bool,
16202        window: &mut Window,
16203        cx: &mut Context<Self>,
16204    ) {
16205        if let Some(project) = self.project.as_ref() {
16206            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16207                return;
16208            };
16209
16210            if buffer.read(cx).file().is_none() {
16211                return;
16212            }
16213
16214            let focused = self.focus_handle(cx).contains_focused(window, cx);
16215
16216            let project = project.clone();
16217            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16218            self.blame_subscription =
16219                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16220            self.blame = Some(blame);
16221        }
16222    }
16223
16224    fn toggle_git_blame_inline_internal(
16225        &mut self,
16226        user_triggered: bool,
16227        window: &mut Window,
16228        cx: &mut Context<Self>,
16229    ) {
16230        if self.git_blame_inline_enabled {
16231            self.git_blame_inline_enabled = false;
16232            self.show_git_blame_inline = false;
16233            self.show_git_blame_inline_delay_task.take();
16234        } else {
16235            self.git_blame_inline_enabled = true;
16236            self.start_git_blame_inline(user_triggered, window, cx);
16237        }
16238
16239        cx.notify();
16240    }
16241
16242    fn start_git_blame_inline(
16243        &mut self,
16244        user_triggered: bool,
16245        window: &mut Window,
16246        cx: &mut Context<Self>,
16247    ) {
16248        self.start_git_blame(user_triggered, window, cx);
16249
16250        if ProjectSettings::get_global(cx)
16251            .git
16252            .inline_blame_delay()
16253            .is_some()
16254        {
16255            self.start_inline_blame_timer(window, cx);
16256        } else {
16257            self.show_git_blame_inline = true
16258        }
16259    }
16260
16261    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16262        self.blame.as_ref()
16263    }
16264
16265    pub fn show_git_blame_gutter(&self) -> bool {
16266        self.show_git_blame_gutter
16267    }
16268
16269    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16270        self.show_git_blame_gutter && self.has_blame_entries(cx)
16271    }
16272
16273    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16274        self.show_git_blame_inline
16275            && (self.focus_handle.is_focused(window)
16276                || self
16277                    .git_blame_inline_tooltip
16278                    .as_ref()
16279                    .and_then(|t| t.upgrade())
16280                    .is_some())
16281            && !self.newest_selection_head_on_empty_line(cx)
16282            && self.has_blame_entries(cx)
16283    }
16284
16285    fn has_blame_entries(&self, cx: &App) -> bool {
16286        self.blame()
16287            .map_or(false, |blame| blame.read(cx).has_generated_entries())
16288    }
16289
16290    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16291        let cursor_anchor = self.selections.newest_anchor().head();
16292
16293        let snapshot = self.buffer.read(cx).snapshot(cx);
16294        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16295
16296        snapshot.line_len(buffer_row) == 0
16297    }
16298
16299    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16300        let buffer_and_selection = maybe!({
16301            let selection = self.selections.newest::<Point>(cx);
16302            let selection_range = selection.range();
16303
16304            let multi_buffer = self.buffer().read(cx);
16305            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16306            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16307
16308            let (buffer, range, _) = if selection.reversed {
16309                buffer_ranges.first()
16310            } else {
16311                buffer_ranges.last()
16312            }?;
16313
16314            let selection = text::ToPoint::to_point(&range.start, &buffer).row
16315                ..text::ToPoint::to_point(&range.end, &buffer).row;
16316            Some((
16317                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16318                selection,
16319            ))
16320        });
16321
16322        let Some((buffer, selection)) = buffer_and_selection else {
16323            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16324        };
16325
16326        let Some(project) = self.project.as_ref() else {
16327            return Task::ready(Err(anyhow!("editor does not have project")));
16328        };
16329
16330        project.update(cx, |project, cx| {
16331            project.get_permalink_to_line(&buffer, selection, cx)
16332        })
16333    }
16334
16335    pub fn copy_permalink_to_line(
16336        &mut self,
16337        _: &CopyPermalinkToLine,
16338        window: &mut Window,
16339        cx: &mut Context<Self>,
16340    ) {
16341        let permalink_task = self.get_permalink_to_line(cx);
16342        let workspace = self.workspace();
16343
16344        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16345            Ok(permalink) => {
16346                cx.update(|_, cx| {
16347                    cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16348                })
16349                .ok();
16350            }
16351            Err(err) => {
16352                let message = format!("Failed to copy permalink: {err}");
16353
16354                Err::<(), anyhow::Error>(err).log_err();
16355
16356                if let Some(workspace) = workspace {
16357                    workspace
16358                        .update_in(cx, |workspace, _, cx| {
16359                            struct CopyPermalinkToLine;
16360
16361                            workspace.show_toast(
16362                                Toast::new(
16363                                    NotificationId::unique::<CopyPermalinkToLine>(),
16364                                    message,
16365                                ),
16366                                cx,
16367                            )
16368                        })
16369                        .ok();
16370                }
16371            }
16372        })
16373        .detach();
16374    }
16375
16376    pub fn copy_file_location(
16377        &mut self,
16378        _: &CopyFileLocation,
16379        _: &mut Window,
16380        cx: &mut Context<Self>,
16381    ) {
16382        let selection = self.selections.newest::<Point>(cx).start.row + 1;
16383        if let Some(file) = self.target_file(cx) {
16384            if let Some(path) = file.path().to_str() {
16385                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16386            }
16387        }
16388    }
16389
16390    pub fn open_permalink_to_line(
16391        &mut self,
16392        _: &OpenPermalinkToLine,
16393        window: &mut Window,
16394        cx: &mut Context<Self>,
16395    ) {
16396        let permalink_task = self.get_permalink_to_line(cx);
16397        let workspace = self.workspace();
16398
16399        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16400            Ok(permalink) => {
16401                cx.update(|_, cx| {
16402                    cx.open_url(permalink.as_ref());
16403                })
16404                .ok();
16405            }
16406            Err(err) => {
16407                let message = format!("Failed to open permalink: {err}");
16408
16409                Err::<(), anyhow::Error>(err).log_err();
16410
16411                if let Some(workspace) = workspace {
16412                    workspace
16413                        .update(cx, |workspace, cx| {
16414                            struct OpenPermalinkToLine;
16415
16416                            workspace.show_toast(
16417                                Toast::new(
16418                                    NotificationId::unique::<OpenPermalinkToLine>(),
16419                                    message,
16420                                ),
16421                                cx,
16422                            )
16423                        })
16424                        .ok();
16425                }
16426            }
16427        })
16428        .detach();
16429    }
16430
16431    pub fn insert_uuid_v4(
16432        &mut self,
16433        _: &InsertUuidV4,
16434        window: &mut Window,
16435        cx: &mut Context<Self>,
16436    ) {
16437        self.insert_uuid(UuidVersion::V4, window, cx);
16438    }
16439
16440    pub fn insert_uuid_v7(
16441        &mut self,
16442        _: &InsertUuidV7,
16443        window: &mut Window,
16444        cx: &mut Context<Self>,
16445    ) {
16446        self.insert_uuid(UuidVersion::V7, window, cx);
16447    }
16448
16449    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16450        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16451        self.transact(window, cx, |this, window, cx| {
16452            let edits = this
16453                .selections
16454                .all::<Point>(cx)
16455                .into_iter()
16456                .map(|selection| {
16457                    let uuid = match version {
16458                        UuidVersion::V4 => uuid::Uuid::new_v4(),
16459                        UuidVersion::V7 => uuid::Uuid::now_v7(),
16460                    };
16461
16462                    (selection.range(), uuid.to_string())
16463                });
16464            this.edit(edits, cx);
16465            this.refresh_inline_completion(true, false, window, cx);
16466        });
16467    }
16468
16469    pub fn open_selections_in_multibuffer(
16470        &mut self,
16471        _: &OpenSelectionsInMultibuffer,
16472        window: &mut Window,
16473        cx: &mut Context<Self>,
16474    ) {
16475        let multibuffer = self.buffer.read(cx);
16476
16477        let Some(buffer) = multibuffer.as_singleton() else {
16478            return;
16479        };
16480
16481        let Some(workspace) = self.workspace() else {
16482            return;
16483        };
16484
16485        let locations = self
16486            .selections
16487            .disjoint_anchors()
16488            .iter()
16489            .map(|range| Location {
16490                buffer: buffer.clone(),
16491                range: range.start.text_anchor..range.end.text_anchor,
16492            })
16493            .collect::<Vec<_>>();
16494
16495        let title = multibuffer.title(cx).to_string();
16496
16497        cx.spawn_in(window, async move |_, cx| {
16498            workspace.update_in(cx, |workspace, window, cx| {
16499                Self::open_locations_in_multibuffer(
16500                    workspace,
16501                    locations,
16502                    format!("Selections for '{title}'"),
16503                    false,
16504                    MultibufferSelectionMode::All,
16505                    window,
16506                    cx,
16507                );
16508            })
16509        })
16510        .detach();
16511    }
16512
16513    /// Adds a row highlight for the given range. If a row has multiple highlights, the
16514    /// last highlight added will be used.
16515    ///
16516    /// If the range ends at the beginning of a line, then that line will not be highlighted.
16517    pub fn highlight_rows<T: 'static>(
16518        &mut self,
16519        range: Range<Anchor>,
16520        color: Hsla,
16521        should_autoscroll: bool,
16522        cx: &mut Context<Self>,
16523    ) {
16524        let snapshot = self.buffer().read(cx).snapshot(cx);
16525        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16526        let ix = row_highlights.binary_search_by(|highlight| {
16527            Ordering::Equal
16528                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
16529                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
16530        });
16531
16532        if let Err(mut ix) = ix {
16533            let index = post_inc(&mut self.highlight_order);
16534
16535            // If this range intersects with the preceding highlight, then merge it with
16536            // the preceding highlight. Otherwise insert a new highlight.
16537            let mut merged = false;
16538            if ix > 0 {
16539                let prev_highlight = &mut row_highlights[ix - 1];
16540                if prev_highlight
16541                    .range
16542                    .end
16543                    .cmp(&range.start, &snapshot)
16544                    .is_ge()
16545                {
16546                    ix -= 1;
16547                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
16548                        prev_highlight.range.end = range.end;
16549                    }
16550                    merged = true;
16551                    prev_highlight.index = index;
16552                    prev_highlight.color = color;
16553                    prev_highlight.should_autoscroll = should_autoscroll;
16554                }
16555            }
16556
16557            if !merged {
16558                row_highlights.insert(
16559                    ix,
16560                    RowHighlight {
16561                        range: range.clone(),
16562                        index,
16563                        color,
16564                        should_autoscroll,
16565                    },
16566                );
16567            }
16568
16569            // If any of the following highlights intersect with this one, merge them.
16570            while let Some(next_highlight) = row_highlights.get(ix + 1) {
16571                let highlight = &row_highlights[ix];
16572                if next_highlight
16573                    .range
16574                    .start
16575                    .cmp(&highlight.range.end, &snapshot)
16576                    .is_le()
16577                {
16578                    if next_highlight
16579                        .range
16580                        .end
16581                        .cmp(&highlight.range.end, &snapshot)
16582                        .is_gt()
16583                    {
16584                        row_highlights[ix].range.end = next_highlight.range.end;
16585                    }
16586                    row_highlights.remove(ix + 1);
16587                } else {
16588                    break;
16589                }
16590            }
16591        }
16592    }
16593
16594    /// Remove any highlighted row ranges of the given type that intersect the
16595    /// given ranges.
16596    pub fn remove_highlighted_rows<T: 'static>(
16597        &mut self,
16598        ranges_to_remove: Vec<Range<Anchor>>,
16599        cx: &mut Context<Self>,
16600    ) {
16601        let snapshot = self.buffer().read(cx).snapshot(cx);
16602        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16603        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16604        row_highlights.retain(|highlight| {
16605            while let Some(range_to_remove) = ranges_to_remove.peek() {
16606                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16607                    Ordering::Less | Ordering::Equal => {
16608                        ranges_to_remove.next();
16609                    }
16610                    Ordering::Greater => {
16611                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16612                            Ordering::Less | Ordering::Equal => {
16613                                return false;
16614                            }
16615                            Ordering::Greater => break,
16616                        }
16617                    }
16618                }
16619            }
16620
16621            true
16622        })
16623    }
16624
16625    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16626    pub fn clear_row_highlights<T: 'static>(&mut self) {
16627        self.highlighted_rows.remove(&TypeId::of::<T>());
16628    }
16629
16630    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
16631    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
16632        self.highlighted_rows
16633            .get(&TypeId::of::<T>())
16634            .map_or(&[] as &[_], |vec| vec.as_slice())
16635            .iter()
16636            .map(|highlight| (highlight.range.clone(), highlight.color))
16637    }
16638
16639    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
16640    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
16641    /// Allows to ignore certain kinds of highlights.
16642    pub fn highlighted_display_rows(
16643        &self,
16644        window: &mut Window,
16645        cx: &mut App,
16646    ) -> BTreeMap<DisplayRow, LineHighlight> {
16647        let snapshot = self.snapshot(window, cx);
16648        let mut used_highlight_orders = HashMap::default();
16649        self.highlighted_rows
16650            .iter()
16651            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16652            .fold(
16653                BTreeMap::<DisplayRow, LineHighlight>::new(),
16654                |mut unique_rows, highlight| {
16655                    let start = highlight.range.start.to_display_point(&snapshot);
16656                    let end = highlight.range.end.to_display_point(&snapshot);
16657                    let start_row = start.row().0;
16658                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16659                        && end.column() == 0
16660                    {
16661                        end.row().0.saturating_sub(1)
16662                    } else {
16663                        end.row().0
16664                    };
16665                    for row in start_row..=end_row {
16666                        let used_index =
16667                            used_highlight_orders.entry(row).or_insert(highlight.index);
16668                        if highlight.index >= *used_index {
16669                            *used_index = highlight.index;
16670                            unique_rows.insert(DisplayRow(row), highlight.color.into());
16671                        }
16672                    }
16673                    unique_rows
16674                },
16675            )
16676    }
16677
16678    pub fn highlighted_display_row_for_autoscroll(
16679        &self,
16680        snapshot: &DisplaySnapshot,
16681    ) -> Option<DisplayRow> {
16682        self.highlighted_rows
16683            .values()
16684            .flat_map(|highlighted_rows| highlighted_rows.iter())
16685            .filter_map(|highlight| {
16686                if highlight.should_autoscroll {
16687                    Some(highlight.range.start.to_display_point(snapshot).row())
16688                } else {
16689                    None
16690                }
16691            })
16692            .min()
16693    }
16694
16695    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16696        self.highlight_background::<SearchWithinRange>(
16697            ranges,
16698            |colors| colors.editor_document_highlight_read_background,
16699            cx,
16700        )
16701    }
16702
16703    pub fn set_breadcrumb_header(&mut self, new_header: String) {
16704        self.breadcrumb_header = Some(new_header);
16705    }
16706
16707    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16708        self.clear_background_highlights::<SearchWithinRange>(cx);
16709    }
16710
16711    pub fn highlight_background<T: 'static>(
16712        &mut self,
16713        ranges: &[Range<Anchor>],
16714        color_fetcher: fn(&ThemeColors) -> Hsla,
16715        cx: &mut Context<Self>,
16716    ) {
16717        self.background_highlights
16718            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16719        self.scrollbar_marker_state.dirty = true;
16720        cx.notify();
16721    }
16722
16723    pub fn clear_background_highlights<T: 'static>(
16724        &mut self,
16725        cx: &mut Context<Self>,
16726    ) -> Option<BackgroundHighlight> {
16727        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16728        if !text_highlights.1.is_empty() {
16729            self.scrollbar_marker_state.dirty = true;
16730            cx.notify();
16731        }
16732        Some(text_highlights)
16733    }
16734
16735    pub fn highlight_gutter<T: 'static>(
16736        &mut self,
16737        ranges: &[Range<Anchor>],
16738        color_fetcher: fn(&App) -> Hsla,
16739        cx: &mut Context<Self>,
16740    ) {
16741        self.gutter_highlights
16742            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16743        cx.notify();
16744    }
16745
16746    pub fn clear_gutter_highlights<T: 'static>(
16747        &mut self,
16748        cx: &mut Context<Self>,
16749    ) -> Option<GutterHighlight> {
16750        cx.notify();
16751        self.gutter_highlights.remove(&TypeId::of::<T>())
16752    }
16753
16754    #[cfg(feature = "test-support")]
16755    pub fn all_text_background_highlights(
16756        &self,
16757        window: &mut Window,
16758        cx: &mut Context<Self>,
16759    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16760        let snapshot = self.snapshot(window, cx);
16761        let buffer = &snapshot.buffer_snapshot;
16762        let start = buffer.anchor_before(0);
16763        let end = buffer.anchor_after(buffer.len());
16764        let theme = cx.theme().colors();
16765        self.background_highlights_in_range(start..end, &snapshot, theme)
16766    }
16767
16768    #[cfg(feature = "test-support")]
16769    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
16770        let snapshot = self.buffer().read(cx).snapshot(cx);
16771
16772        let highlights = self
16773            .background_highlights
16774            .get(&TypeId::of::<items::BufferSearchHighlights>());
16775
16776        if let Some((_color, ranges)) = highlights {
16777            ranges
16778                .iter()
16779                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
16780                .collect_vec()
16781        } else {
16782            vec![]
16783        }
16784    }
16785
16786    fn document_highlights_for_position<'a>(
16787        &'a self,
16788        position: Anchor,
16789        buffer: &'a MultiBufferSnapshot,
16790    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
16791        let read_highlights = self
16792            .background_highlights
16793            .get(&TypeId::of::<DocumentHighlightRead>())
16794            .map(|h| &h.1);
16795        let write_highlights = self
16796            .background_highlights
16797            .get(&TypeId::of::<DocumentHighlightWrite>())
16798            .map(|h| &h.1);
16799        let left_position = position.bias_left(buffer);
16800        let right_position = position.bias_right(buffer);
16801        read_highlights
16802            .into_iter()
16803            .chain(write_highlights)
16804            .flat_map(move |ranges| {
16805                let start_ix = match ranges.binary_search_by(|probe| {
16806                    let cmp = probe.end.cmp(&left_position, buffer);
16807                    if cmp.is_ge() {
16808                        Ordering::Greater
16809                    } else {
16810                        Ordering::Less
16811                    }
16812                }) {
16813                    Ok(i) | Err(i) => i,
16814                };
16815
16816                ranges[start_ix..]
16817                    .iter()
16818                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
16819            })
16820    }
16821
16822    pub fn has_background_highlights<T: 'static>(&self) -> bool {
16823        self.background_highlights
16824            .get(&TypeId::of::<T>())
16825            .map_or(false, |(_, highlights)| !highlights.is_empty())
16826    }
16827
16828    pub fn background_highlights_in_range(
16829        &self,
16830        search_range: Range<Anchor>,
16831        display_snapshot: &DisplaySnapshot,
16832        theme: &ThemeColors,
16833    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16834        let mut results = Vec::new();
16835        for (color_fetcher, ranges) in self.background_highlights.values() {
16836            let color = color_fetcher(theme);
16837            let start_ix = match ranges.binary_search_by(|probe| {
16838                let cmp = probe
16839                    .end
16840                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16841                if cmp.is_gt() {
16842                    Ordering::Greater
16843                } else {
16844                    Ordering::Less
16845                }
16846            }) {
16847                Ok(i) | Err(i) => i,
16848            };
16849            for range in &ranges[start_ix..] {
16850                if range
16851                    .start
16852                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16853                    .is_ge()
16854                {
16855                    break;
16856                }
16857
16858                let start = range.start.to_display_point(display_snapshot);
16859                let end = range.end.to_display_point(display_snapshot);
16860                results.push((start..end, color))
16861            }
16862        }
16863        results
16864    }
16865
16866    pub fn background_highlight_row_ranges<T: 'static>(
16867        &self,
16868        search_range: Range<Anchor>,
16869        display_snapshot: &DisplaySnapshot,
16870        count: usize,
16871    ) -> Vec<RangeInclusive<DisplayPoint>> {
16872        let mut results = Vec::new();
16873        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
16874            return vec![];
16875        };
16876
16877        let start_ix = match ranges.binary_search_by(|probe| {
16878            let cmp = probe
16879                .end
16880                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16881            if cmp.is_gt() {
16882                Ordering::Greater
16883            } else {
16884                Ordering::Less
16885            }
16886        }) {
16887            Ok(i) | Err(i) => i,
16888        };
16889        let mut push_region = |start: Option<Point>, end: Option<Point>| {
16890            if let (Some(start_display), Some(end_display)) = (start, end) {
16891                results.push(
16892                    start_display.to_display_point(display_snapshot)
16893                        ..=end_display.to_display_point(display_snapshot),
16894                );
16895            }
16896        };
16897        let mut start_row: Option<Point> = None;
16898        let mut end_row: Option<Point> = None;
16899        if ranges.len() > count {
16900            return Vec::new();
16901        }
16902        for range in &ranges[start_ix..] {
16903            if range
16904                .start
16905                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16906                .is_ge()
16907            {
16908                break;
16909            }
16910            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
16911            if let Some(current_row) = &end_row {
16912                if end.row == current_row.row {
16913                    continue;
16914                }
16915            }
16916            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
16917            if start_row.is_none() {
16918                assert_eq!(end_row, None);
16919                start_row = Some(start);
16920                end_row = Some(end);
16921                continue;
16922            }
16923            if let Some(current_end) = end_row.as_mut() {
16924                if start.row > current_end.row + 1 {
16925                    push_region(start_row, end_row);
16926                    start_row = Some(start);
16927                    end_row = Some(end);
16928                } else {
16929                    // Merge two hunks.
16930                    *current_end = end;
16931                }
16932            } else {
16933                unreachable!();
16934            }
16935        }
16936        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
16937        push_region(start_row, end_row);
16938        results
16939    }
16940
16941    pub fn gutter_highlights_in_range(
16942        &self,
16943        search_range: Range<Anchor>,
16944        display_snapshot: &DisplaySnapshot,
16945        cx: &App,
16946    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16947        let mut results = Vec::new();
16948        for (color_fetcher, ranges) in self.gutter_highlights.values() {
16949            let color = color_fetcher(cx);
16950            let start_ix = match ranges.binary_search_by(|probe| {
16951                let cmp = probe
16952                    .end
16953                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16954                if cmp.is_gt() {
16955                    Ordering::Greater
16956                } else {
16957                    Ordering::Less
16958                }
16959            }) {
16960                Ok(i) | Err(i) => i,
16961            };
16962            for range in &ranges[start_ix..] {
16963                if range
16964                    .start
16965                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16966                    .is_ge()
16967                {
16968                    break;
16969                }
16970
16971                let start = range.start.to_display_point(display_snapshot);
16972                let end = range.end.to_display_point(display_snapshot);
16973                results.push((start..end, color))
16974            }
16975        }
16976        results
16977    }
16978
16979    /// Get the text ranges corresponding to the redaction query
16980    pub fn redacted_ranges(
16981        &self,
16982        search_range: Range<Anchor>,
16983        display_snapshot: &DisplaySnapshot,
16984        cx: &App,
16985    ) -> Vec<Range<DisplayPoint>> {
16986        display_snapshot
16987            .buffer_snapshot
16988            .redacted_ranges(search_range, |file| {
16989                if let Some(file) = file {
16990                    file.is_private()
16991                        && EditorSettings::get(
16992                            Some(SettingsLocation {
16993                                worktree_id: file.worktree_id(cx),
16994                                path: file.path().as_ref(),
16995                            }),
16996                            cx,
16997                        )
16998                        .redact_private_values
16999                } else {
17000                    false
17001                }
17002            })
17003            .map(|range| {
17004                range.start.to_display_point(display_snapshot)
17005                    ..range.end.to_display_point(display_snapshot)
17006            })
17007            .collect()
17008    }
17009
17010    pub fn highlight_text<T: 'static>(
17011        &mut self,
17012        ranges: Vec<Range<Anchor>>,
17013        style: HighlightStyle,
17014        cx: &mut Context<Self>,
17015    ) {
17016        self.display_map.update(cx, |map, _| {
17017            map.highlight_text(TypeId::of::<T>(), ranges, style)
17018        });
17019        cx.notify();
17020    }
17021
17022    pub(crate) fn highlight_inlays<T: 'static>(
17023        &mut self,
17024        highlights: Vec<InlayHighlight>,
17025        style: HighlightStyle,
17026        cx: &mut Context<Self>,
17027    ) {
17028        self.display_map.update(cx, |map, _| {
17029            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17030        });
17031        cx.notify();
17032    }
17033
17034    pub fn text_highlights<'a, T: 'static>(
17035        &'a self,
17036        cx: &'a App,
17037    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17038        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17039    }
17040
17041    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17042        let cleared = self
17043            .display_map
17044            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17045        if cleared {
17046            cx.notify();
17047        }
17048    }
17049
17050    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17051        (self.read_only(cx) || self.blink_manager.read(cx).visible())
17052            && self.focus_handle.is_focused(window)
17053    }
17054
17055    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17056        self.show_cursor_when_unfocused = is_enabled;
17057        cx.notify();
17058    }
17059
17060    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17061        cx.notify();
17062    }
17063
17064    fn on_buffer_event(
17065        &mut self,
17066        multibuffer: &Entity<MultiBuffer>,
17067        event: &multi_buffer::Event,
17068        window: &mut Window,
17069        cx: &mut Context<Self>,
17070    ) {
17071        match event {
17072            multi_buffer::Event::Edited {
17073                singleton_buffer_edited,
17074                edited_buffer: buffer_edited,
17075            } => {
17076                self.scrollbar_marker_state.dirty = true;
17077                self.active_indent_guides_state.dirty = true;
17078                self.refresh_active_diagnostics(cx);
17079                self.refresh_code_actions(window, cx);
17080                if self.has_active_inline_completion() {
17081                    self.update_visible_inline_completion(window, cx);
17082                }
17083                if let Some(buffer) = buffer_edited {
17084                    let buffer_id = buffer.read(cx).remote_id();
17085                    if !self.registered_buffers.contains_key(&buffer_id) {
17086                        if let Some(project) = self.project.as_ref() {
17087                            project.update(cx, |project, cx| {
17088                                self.registered_buffers.insert(
17089                                    buffer_id,
17090                                    project.register_buffer_with_language_servers(&buffer, cx),
17091                                );
17092                            })
17093                        }
17094                    }
17095                }
17096                cx.emit(EditorEvent::BufferEdited);
17097                cx.emit(SearchEvent::MatchesInvalidated);
17098                if *singleton_buffer_edited {
17099                    if let Some(project) = &self.project {
17100                        #[allow(clippy::mutable_key_type)]
17101                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17102                            multibuffer
17103                                .all_buffers()
17104                                .into_iter()
17105                                .filter_map(|buffer| {
17106                                    buffer.update(cx, |buffer, cx| {
17107                                        let language = buffer.language()?;
17108                                        let should_discard = project.update(cx, |project, cx| {
17109                                            project.is_local()
17110                                                && !project.has_language_servers_for(buffer, cx)
17111                                        });
17112                                        should_discard.not().then_some(language.clone())
17113                                    })
17114                                })
17115                                .collect::<HashSet<_>>()
17116                        });
17117                        if !languages_affected.is_empty() {
17118                            self.refresh_inlay_hints(
17119                                InlayHintRefreshReason::BufferEdited(languages_affected),
17120                                cx,
17121                            );
17122                        }
17123                    }
17124                }
17125
17126                let Some(project) = &self.project else { return };
17127                let (telemetry, is_via_ssh) = {
17128                    let project = project.read(cx);
17129                    let telemetry = project.client().telemetry().clone();
17130                    let is_via_ssh = project.is_via_ssh();
17131                    (telemetry, is_via_ssh)
17132                };
17133                refresh_linked_ranges(self, window, cx);
17134                telemetry.log_edit_event("editor", is_via_ssh);
17135            }
17136            multi_buffer::Event::ExcerptsAdded {
17137                buffer,
17138                predecessor,
17139                excerpts,
17140            } => {
17141                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17142                let buffer_id = buffer.read(cx).remote_id();
17143                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17144                    if let Some(project) = &self.project {
17145                        get_uncommitted_diff_for_buffer(
17146                            project,
17147                            [buffer.clone()],
17148                            self.buffer.clone(),
17149                            cx,
17150                        )
17151                        .detach();
17152                    }
17153                }
17154                cx.emit(EditorEvent::ExcerptsAdded {
17155                    buffer: buffer.clone(),
17156                    predecessor: *predecessor,
17157                    excerpts: excerpts.clone(),
17158                });
17159                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17160            }
17161            multi_buffer::Event::ExcerptsRemoved { ids } => {
17162                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17163                let buffer = self.buffer.read(cx);
17164                self.registered_buffers
17165                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17166                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17167                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
17168            }
17169            multi_buffer::Event::ExcerptsEdited {
17170                excerpt_ids,
17171                buffer_ids,
17172            } => {
17173                self.display_map.update(cx, |map, cx| {
17174                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
17175                });
17176                cx.emit(EditorEvent::ExcerptsEdited {
17177                    ids: excerpt_ids.clone(),
17178                })
17179            }
17180            multi_buffer::Event::ExcerptsExpanded { ids } => {
17181                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17182                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17183            }
17184            multi_buffer::Event::Reparsed(buffer_id) => {
17185                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17186                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17187
17188                cx.emit(EditorEvent::Reparsed(*buffer_id));
17189            }
17190            multi_buffer::Event::DiffHunksToggled => {
17191                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17192            }
17193            multi_buffer::Event::LanguageChanged(buffer_id) => {
17194                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17195                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17196                cx.emit(EditorEvent::Reparsed(*buffer_id));
17197                cx.notify();
17198            }
17199            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17200            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17201            multi_buffer::Event::FileHandleChanged
17202            | multi_buffer::Event::Reloaded
17203            | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17204            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17205            multi_buffer::Event::DiagnosticsUpdated => {
17206                self.refresh_active_diagnostics(cx);
17207                self.refresh_inline_diagnostics(true, window, cx);
17208                self.scrollbar_marker_state.dirty = true;
17209                cx.notify();
17210            }
17211            _ => {}
17212        };
17213    }
17214
17215    fn on_display_map_changed(
17216        &mut self,
17217        _: Entity<DisplayMap>,
17218        _: &mut Window,
17219        cx: &mut Context<Self>,
17220    ) {
17221        cx.notify();
17222    }
17223
17224    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17225        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17226        self.update_edit_prediction_settings(cx);
17227        self.refresh_inline_completion(true, false, window, cx);
17228        self.refresh_inlay_hints(
17229            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17230                self.selections.newest_anchor().head(),
17231                &self.buffer.read(cx).snapshot(cx),
17232                cx,
17233            )),
17234            cx,
17235        );
17236
17237        let old_cursor_shape = self.cursor_shape;
17238
17239        {
17240            let editor_settings = EditorSettings::get_global(cx);
17241            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17242            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17243            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17244            self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17245        }
17246
17247        if old_cursor_shape != self.cursor_shape {
17248            cx.emit(EditorEvent::CursorShapeChanged);
17249        }
17250
17251        let project_settings = ProjectSettings::get_global(cx);
17252        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17253
17254        if self.mode.is_full() {
17255            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17256            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17257            if self.show_inline_diagnostics != show_inline_diagnostics {
17258                self.show_inline_diagnostics = show_inline_diagnostics;
17259                self.refresh_inline_diagnostics(false, window, cx);
17260            }
17261
17262            if self.git_blame_inline_enabled != inline_blame_enabled {
17263                self.toggle_git_blame_inline_internal(false, window, cx);
17264            }
17265        }
17266
17267        cx.notify();
17268    }
17269
17270    pub fn set_searchable(&mut self, searchable: bool) {
17271        self.searchable = searchable;
17272    }
17273
17274    pub fn searchable(&self) -> bool {
17275        self.searchable
17276    }
17277
17278    fn open_proposed_changes_editor(
17279        &mut self,
17280        _: &OpenProposedChangesEditor,
17281        window: &mut Window,
17282        cx: &mut Context<Self>,
17283    ) {
17284        let Some(workspace) = self.workspace() else {
17285            cx.propagate();
17286            return;
17287        };
17288
17289        let selections = self.selections.all::<usize>(cx);
17290        let multi_buffer = self.buffer.read(cx);
17291        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17292        let mut new_selections_by_buffer = HashMap::default();
17293        for selection in selections {
17294            for (buffer, range, _) in
17295                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17296            {
17297                let mut range = range.to_point(buffer);
17298                range.start.column = 0;
17299                range.end.column = buffer.line_len(range.end.row);
17300                new_selections_by_buffer
17301                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17302                    .or_insert(Vec::new())
17303                    .push(range)
17304            }
17305        }
17306
17307        let proposed_changes_buffers = new_selections_by_buffer
17308            .into_iter()
17309            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17310            .collect::<Vec<_>>();
17311        let proposed_changes_editor = cx.new(|cx| {
17312            ProposedChangesEditor::new(
17313                "Proposed changes",
17314                proposed_changes_buffers,
17315                self.project.clone(),
17316                window,
17317                cx,
17318            )
17319        });
17320
17321        window.defer(cx, move |window, cx| {
17322            workspace.update(cx, |workspace, cx| {
17323                workspace.active_pane().update(cx, |pane, cx| {
17324                    pane.add_item(
17325                        Box::new(proposed_changes_editor),
17326                        true,
17327                        true,
17328                        None,
17329                        window,
17330                        cx,
17331                    );
17332                });
17333            });
17334        });
17335    }
17336
17337    pub fn open_excerpts_in_split(
17338        &mut self,
17339        _: &OpenExcerptsSplit,
17340        window: &mut Window,
17341        cx: &mut Context<Self>,
17342    ) {
17343        self.open_excerpts_common(None, true, window, cx)
17344    }
17345
17346    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
17347        self.open_excerpts_common(None, false, window, cx)
17348    }
17349
17350    fn open_excerpts_common(
17351        &mut self,
17352        jump_data: Option<JumpData>,
17353        split: bool,
17354        window: &mut Window,
17355        cx: &mut Context<Self>,
17356    ) {
17357        let Some(workspace) = self.workspace() else {
17358            cx.propagate();
17359            return;
17360        };
17361
17362        if self.buffer.read(cx).is_singleton() {
17363            cx.propagate();
17364            return;
17365        }
17366
17367        let mut new_selections_by_buffer = HashMap::default();
17368        match &jump_data {
17369            Some(JumpData::MultiBufferPoint {
17370                excerpt_id,
17371                position,
17372                anchor,
17373                line_offset_from_top,
17374            }) => {
17375                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
17376                if let Some(buffer) = multi_buffer_snapshot
17377                    .buffer_id_for_excerpt(*excerpt_id)
17378                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
17379                {
17380                    let buffer_snapshot = buffer.read(cx).snapshot();
17381                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
17382                        language::ToPoint::to_point(anchor, &buffer_snapshot)
17383                    } else {
17384                        buffer_snapshot.clip_point(*position, Bias::Left)
17385                    };
17386                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
17387                    new_selections_by_buffer.insert(
17388                        buffer,
17389                        (
17390                            vec![jump_to_offset..jump_to_offset],
17391                            Some(*line_offset_from_top),
17392                        ),
17393                    );
17394                }
17395            }
17396            Some(JumpData::MultiBufferRow {
17397                row,
17398                line_offset_from_top,
17399            }) => {
17400                let point = MultiBufferPoint::new(row.0, 0);
17401                if let Some((buffer, buffer_point, _)) =
17402                    self.buffer.read(cx).point_to_buffer_point(point, cx)
17403                {
17404                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
17405                    new_selections_by_buffer
17406                        .entry(buffer)
17407                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
17408                        .0
17409                        .push(buffer_offset..buffer_offset)
17410                }
17411            }
17412            None => {
17413                let selections = self.selections.all::<usize>(cx);
17414                let multi_buffer = self.buffer.read(cx);
17415                for selection in selections {
17416                    for (snapshot, range, _, anchor) in multi_buffer
17417                        .snapshot(cx)
17418                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
17419                    {
17420                        if let Some(anchor) = anchor {
17421                            // selection is in a deleted hunk
17422                            let Some(buffer_id) = anchor.buffer_id else {
17423                                continue;
17424                            };
17425                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
17426                                continue;
17427                            };
17428                            let offset = text::ToOffset::to_offset(
17429                                &anchor.text_anchor,
17430                                &buffer_handle.read(cx).snapshot(),
17431                            );
17432                            let range = offset..offset;
17433                            new_selections_by_buffer
17434                                .entry(buffer_handle)
17435                                .or_insert((Vec::new(), None))
17436                                .0
17437                                .push(range)
17438                        } else {
17439                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
17440                            else {
17441                                continue;
17442                            };
17443                            new_selections_by_buffer
17444                                .entry(buffer_handle)
17445                                .or_insert((Vec::new(), None))
17446                                .0
17447                                .push(range)
17448                        }
17449                    }
17450                }
17451            }
17452        }
17453
17454        new_selections_by_buffer
17455            .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
17456
17457        if new_selections_by_buffer.is_empty() {
17458            return;
17459        }
17460
17461        // We defer the pane interaction because we ourselves are a workspace item
17462        // and activating a new item causes the pane to call a method on us reentrantly,
17463        // which panics if we're on the stack.
17464        window.defer(cx, move |window, cx| {
17465            workspace.update(cx, |workspace, cx| {
17466                let pane = if split {
17467                    workspace.adjacent_pane(window, cx)
17468                } else {
17469                    workspace.active_pane().clone()
17470                };
17471
17472                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
17473                    let editor = buffer
17474                        .read(cx)
17475                        .file()
17476                        .is_none()
17477                        .then(|| {
17478                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
17479                            // so `workspace.open_project_item` will never find them, always opening a new editor.
17480                            // Instead, we try to activate the existing editor in the pane first.
17481                            let (editor, pane_item_index) =
17482                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
17483                                    let editor = item.downcast::<Editor>()?;
17484                                    let singleton_buffer =
17485                                        editor.read(cx).buffer().read(cx).as_singleton()?;
17486                                    if singleton_buffer == buffer {
17487                                        Some((editor, i))
17488                                    } else {
17489                                        None
17490                                    }
17491                                })?;
17492                            pane.update(cx, |pane, cx| {
17493                                pane.activate_item(pane_item_index, true, true, window, cx)
17494                            });
17495                            Some(editor)
17496                        })
17497                        .flatten()
17498                        .unwrap_or_else(|| {
17499                            workspace.open_project_item::<Self>(
17500                                pane.clone(),
17501                                buffer,
17502                                true,
17503                                true,
17504                                window,
17505                                cx,
17506                            )
17507                        });
17508
17509                    editor.update(cx, |editor, cx| {
17510                        let autoscroll = match scroll_offset {
17511                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
17512                            None => Autoscroll::newest(),
17513                        };
17514                        let nav_history = editor.nav_history.take();
17515                        editor.change_selections(Some(autoscroll), window, cx, |s| {
17516                            s.select_ranges(ranges);
17517                        });
17518                        editor.nav_history = nav_history;
17519                    });
17520                }
17521            })
17522        });
17523    }
17524
17525    // For now, don't allow opening excerpts in buffers that aren't backed by
17526    // regular project files.
17527    fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
17528        file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
17529    }
17530
17531    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
17532        let snapshot = self.buffer.read(cx).read(cx);
17533        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
17534        Some(
17535            ranges
17536                .iter()
17537                .map(move |range| {
17538                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
17539                })
17540                .collect(),
17541        )
17542    }
17543
17544    fn selection_replacement_ranges(
17545        &self,
17546        range: Range<OffsetUtf16>,
17547        cx: &mut App,
17548    ) -> Vec<Range<OffsetUtf16>> {
17549        let selections = self.selections.all::<OffsetUtf16>(cx);
17550        let newest_selection = selections
17551            .iter()
17552            .max_by_key(|selection| selection.id)
17553            .unwrap();
17554        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
17555        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
17556        let snapshot = self.buffer.read(cx).read(cx);
17557        selections
17558            .into_iter()
17559            .map(|mut selection| {
17560                selection.start.0 =
17561                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
17562                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
17563                snapshot.clip_offset_utf16(selection.start, Bias::Left)
17564                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
17565            })
17566            .collect()
17567    }
17568
17569    fn report_editor_event(
17570        &self,
17571        event_type: &'static str,
17572        file_extension: Option<String>,
17573        cx: &App,
17574    ) {
17575        if cfg!(any(test, feature = "test-support")) {
17576            return;
17577        }
17578
17579        let Some(project) = &self.project else { return };
17580
17581        // If None, we are in a file without an extension
17582        let file = self
17583            .buffer
17584            .read(cx)
17585            .as_singleton()
17586            .and_then(|b| b.read(cx).file());
17587        let file_extension = file_extension.or(file
17588            .as_ref()
17589            .and_then(|file| Path::new(file.file_name(cx)).extension())
17590            .and_then(|e| e.to_str())
17591            .map(|a| a.to_string()));
17592
17593        let vim_mode = cx
17594            .global::<SettingsStore>()
17595            .raw_user_settings()
17596            .get("vim_mode")
17597            == Some(&serde_json::Value::Bool(true));
17598
17599        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
17600        let copilot_enabled = edit_predictions_provider
17601            == language::language_settings::EditPredictionProvider::Copilot;
17602        let copilot_enabled_for_language = self
17603            .buffer
17604            .read(cx)
17605            .language_settings(cx)
17606            .show_edit_predictions;
17607
17608        let project = project.read(cx);
17609        telemetry::event!(
17610            event_type,
17611            file_extension,
17612            vim_mode,
17613            copilot_enabled,
17614            copilot_enabled_for_language,
17615            edit_predictions_provider,
17616            is_via_ssh = project.is_via_ssh(),
17617        );
17618    }
17619
17620    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
17621    /// with each line being an array of {text, highlight} objects.
17622    fn copy_highlight_json(
17623        &mut self,
17624        _: &CopyHighlightJson,
17625        window: &mut Window,
17626        cx: &mut Context<Self>,
17627    ) {
17628        #[derive(Serialize)]
17629        struct Chunk<'a> {
17630            text: String,
17631            highlight: Option<&'a str>,
17632        }
17633
17634        let snapshot = self.buffer.read(cx).snapshot(cx);
17635        let range = self
17636            .selected_text_range(false, window, cx)
17637            .and_then(|selection| {
17638                if selection.range.is_empty() {
17639                    None
17640                } else {
17641                    Some(selection.range)
17642                }
17643            })
17644            .unwrap_or_else(|| 0..snapshot.len());
17645
17646        let chunks = snapshot.chunks(range, true);
17647        let mut lines = Vec::new();
17648        let mut line: VecDeque<Chunk> = VecDeque::new();
17649
17650        let Some(style) = self.style.as_ref() else {
17651            return;
17652        };
17653
17654        for chunk in chunks {
17655            let highlight = chunk
17656                .syntax_highlight_id
17657                .and_then(|id| id.name(&style.syntax));
17658            let mut chunk_lines = chunk.text.split('\n').peekable();
17659            while let Some(text) = chunk_lines.next() {
17660                let mut merged_with_last_token = false;
17661                if let Some(last_token) = line.back_mut() {
17662                    if last_token.highlight == highlight {
17663                        last_token.text.push_str(text);
17664                        merged_with_last_token = true;
17665                    }
17666                }
17667
17668                if !merged_with_last_token {
17669                    line.push_back(Chunk {
17670                        text: text.into(),
17671                        highlight,
17672                    });
17673                }
17674
17675                if chunk_lines.peek().is_some() {
17676                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
17677                        line.pop_front();
17678                    }
17679                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
17680                        line.pop_back();
17681                    }
17682
17683                    lines.push(mem::take(&mut line));
17684                }
17685            }
17686        }
17687
17688        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17689            return;
17690        };
17691        cx.write_to_clipboard(ClipboardItem::new_string(lines));
17692    }
17693
17694    pub fn open_context_menu(
17695        &mut self,
17696        _: &OpenContextMenu,
17697        window: &mut Window,
17698        cx: &mut Context<Self>,
17699    ) {
17700        self.request_autoscroll(Autoscroll::newest(), cx);
17701        let position = self.selections.newest_display(cx).start;
17702        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17703    }
17704
17705    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17706        &self.inlay_hint_cache
17707    }
17708
17709    pub fn replay_insert_event(
17710        &mut self,
17711        text: &str,
17712        relative_utf16_range: Option<Range<isize>>,
17713        window: &mut Window,
17714        cx: &mut Context<Self>,
17715    ) {
17716        if !self.input_enabled {
17717            cx.emit(EditorEvent::InputIgnored { text: text.into() });
17718            return;
17719        }
17720        if let Some(relative_utf16_range) = relative_utf16_range {
17721            let selections = self.selections.all::<OffsetUtf16>(cx);
17722            self.change_selections(None, window, cx, |s| {
17723                let new_ranges = selections.into_iter().map(|range| {
17724                    let start = OffsetUtf16(
17725                        range
17726                            .head()
17727                            .0
17728                            .saturating_add_signed(relative_utf16_range.start),
17729                    );
17730                    let end = OffsetUtf16(
17731                        range
17732                            .head()
17733                            .0
17734                            .saturating_add_signed(relative_utf16_range.end),
17735                    );
17736                    start..end
17737                });
17738                s.select_ranges(new_ranges);
17739            });
17740        }
17741
17742        self.handle_input(text, window, cx);
17743    }
17744
17745    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
17746        let Some(provider) = self.semantics_provider.as_ref() else {
17747            return false;
17748        };
17749
17750        let mut supports = false;
17751        self.buffer().update(cx, |this, cx| {
17752            this.for_each_buffer(|buffer| {
17753                supports |= provider.supports_inlay_hints(buffer, cx);
17754            });
17755        });
17756
17757        supports
17758    }
17759
17760    pub fn is_focused(&self, window: &Window) -> bool {
17761        self.focus_handle.is_focused(window)
17762    }
17763
17764    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17765        cx.emit(EditorEvent::Focused);
17766
17767        if let Some(descendant) = self
17768            .last_focused_descendant
17769            .take()
17770            .and_then(|descendant| descendant.upgrade())
17771        {
17772            window.focus(&descendant);
17773        } else {
17774            if let Some(blame) = self.blame.as_ref() {
17775                blame.update(cx, GitBlame::focus)
17776            }
17777
17778            self.blink_manager.update(cx, BlinkManager::enable);
17779            self.show_cursor_names(window, cx);
17780            self.buffer.update(cx, |buffer, cx| {
17781                buffer.finalize_last_transaction(cx);
17782                if self.leader_peer_id.is_none() {
17783                    buffer.set_active_selections(
17784                        &self.selections.disjoint_anchors(),
17785                        self.selections.line_mode,
17786                        self.cursor_shape,
17787                        cx,
17788                    );
17789                }
17790            });
17791        }
17792    }
17793
17794    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17795        cx.emit(EditorEvent::FocusedIn)
17796    }
17797
17798    fn handle_focus_out(
17799        &mut self,
17800        event: FocusOutEvent,
17801        _window: &mut Window,
17802        cx: &mut Context<Self>,
17803    ) {
17804        if event.blurred != self.focus_handle {
17805            self.last_focused_descendant = Some(event.blurred);
17806        }
17807        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
17808    }
17809
17810    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17811        self.blink_manager.update(cx, BlinkManager::disable);
17812        self.buffer
17813            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
17814
17815        if let Some(blame) = self.blame.as_ref() {
17816            blame.update(cx, GitBlame::blur)
17817        }
17818        if !self.hover_state.focused(window, cx) {
17819            hide_hover(self, cx);
17820        }
17821        if !self
17822            .context_menu
17823            .borrow()
17824            .as_ref()
17825            .is_some_and(|context_menu| context_menu.focused(window, cx))
17826        {
17827            self.hide_context_menu(window, cx);
17828        }
17829        self.discard_inline_completion(false, cx);
17830        cx.emit(EditorEvent::Blurred);
17831        cx.notify();
17832    }
17833
17834    pub fn register_action<A: Action>(
17835        &mut self,
17836        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
17837    ) -> Subscription {
17838        let id = self.next_editor_action_id.post_inc();
17839        let listener = Arc::new(listener);
17840        self.editor_actions.borrow_mut().insert(
17841            id,
17842            Box::new(move |window, _| {
17843                let listener = listener.clone();
17844                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
17845                    let action = action.downcast_ref().unwrap();
17846                    if phase == DispatchPhase::Bubble {
17847                        listener(action, window, cx)
17848                    }
17849                })
17850            }),
17851        );
17852
17853        let editor_actions = self.editor_actions.clone();
17854        Subscription::new(move || {
17855            editor_actions.borrow_mut().remove(&id);
17856        })
17857    }
17858
17859    pub fn file_header_size(&self) -> u32 {
17860        FILE_HEADER_HEIGHT
17861    }
17862
17863    pub fn restore(
17864        &mut self,
17865        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
17866        window: &mut Window,
17867        cx: &mut Context<Self>,
17868    ) {
17869        let workspace = self.workspace();
17870        let project = self.project.as_ref();
17871        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
17872            let mut tasks = Vec::new();
17873            for (buffer_id, changes) in revert_changes {
17874                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
17875                    buffer.update(cx, |buffer, cx| {
17876                        buffer.edit(
17877                            changes
17878                                .into_iter()
17879                                .map(|(range, text)| (range, text.to_string())),
17880                            None,
17881                            cx,
17882                        );
17883                    });
17884
17885                    if let Some(project) =
17886                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
17887                    {
17888                        project.update(cx, |project, cx| {
17889                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
17890                        })
17891                    }
17892                }
17893            }
17894            tasks
17895        });
17896        cx.spawn_in(window, async move |_, cx| {
17897            for (buffer, task) in save_tasks {
17898                let result = task.await;
17899                if result.is_err() {
17900                    let Some(path) = buffer
17901                        .read_with(cx, |buffer, cx| buffer.project_path(cx))
17902                        .ok()
17903                    else {
17904                        continue;
17905                    };
17906                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
17907                        let Some(task) = cx
17908                            .update_window_entity(&workspace, |workspace, window, cx| {
17909                                workspace
17910                                    .open_path_preview(path, None, false, false, false, window, cx)
17911                            })
17912                            .ok()
17913                        else {
17914                            continue;
17915                        };
17916                        task.await.log_err();
17917                    }
17918                }
17919            }
17920        })
17921        .detach();
17922        self.change_selections(None, window, cx, |selections| selections.refresh());
17923    }
17924
17925    pub fn to_pixel_point(
17926        &self,
17927        source: multi_buffer::Anchor,
17928        editor_snapshot: &EditorSnapshot,
17929        window: &mut Window,
17930    ) -> Option<gpui::Point<Pixels>> {
17931        let source_point = source.to_display_point(editor_snapshot);
17932        self.display_to_pixel_point(source_point, editor_snapshot, window)
17933    }
17934
17935    pub fn display_to_pixel_point(
17936        &self,
17937        source: DisplayPoint,
17938        editor_snapshot: &EditorSnapshot,
17939        window: &mut Window,
17940    ) -> Option<gpui::Point<Pixels>> {
17941        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
17942        let text_layout_details = self.text_layout_details(window);
17943        let scroll_top = text_layout_details
17944            .scroll_anchor
17945            .scroll_position(editor_snapshot)
17946            .y;
17947
17948        if source.row().as_f32() < scroll_top.floor() {
17949            return None;
17950        }
17951        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
17952        let source_y = line_height * (source.row().as_f32() - scroll_top);
17953        Some(gpui::Point::new(source_x, source_y))
17954    }
17955
17956    pub fn has_visible_completions_menu(&self) -> bool {
17957        !self.edit_prediction_preview_is_active()
17958            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
17959                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
17960            })
17961    }
17962
17963    pub fn register_addon<T: Addon>(&mut self, instance: T) {
17964        self.addons
17965            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
17966    }
17967
17968    pub fn unregister_addon<T: Addon>(&mut self) {
17969        self.addons.remove(&std::any::TypeId::of::<T>());
17970    }
17971
17972    pub fn addon<T: Addon>(&self) -> Option<&T> {
17973        let type_id = std::any::TypeId::of::<T>();
17974        self.addons
17975            .get(&type_id)
17976            .and_then(|item| item.to_any().downcast_ref::<T>())
17977    }
17978
17979    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
17980        let text_layout_details = self.text_layout_details(window);
17981        let style = &text_layout_details.editor_style;
17982        let font_id = window.text_system().resolve_font(&style.text.font());
17983        let font_size = style.text.font_size.to_pixels(window.rem_size());
17984        let line_height = style.text.line_height_in_pixels(window.rem_size());
17985        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
17986
17987        gpui::Size::new(em_width, line_height)
17988    }
17989
17990    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
17991        self.load_diff_task.clone()
17992    }
17993
17994    fn read_metadata_from_db(
17995        &mut self,
17996        item_id: u64,
17997        workspace_id: WorkspaceId,
17998        window: &mut Window,
17999        cx: &mut Context<Editor>,
18000    ) {
18001        if self.is_singleton(cx)
18002            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18003        {
18004            let buffer_snapshot = OnceCell::new();
18005
18006            if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18007                if !folds.is_empty() {
18008                    let snapshot =
18009                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18010                    self.fold_ranges(
18011                        folds
18012                            .into_iter()
18013                            .map(|(start, end)| {
18014                                snapshot.clip_offset(start, Bias::Left)
18015                                    ..snapshot.clip_offset(end, Bias::Right)
18016                            })
18017                            .collect(),
18018                        false,
18019                        window,
18020                        cx,
18021                    );
18022                }
18023            }
18024
18025            if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18026                if !selections.is_empty() {
18027                    let snapshot =
18028                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18029                    self.change_selections(None, window, cx, |s| {
18030                        s.select_ranges(selections.into_iter().map(|(start, end)| {
18031                            snapshot.clip_offset(start, Bias::Left)
18032                                ..snapshot.clip_offset(end, Bias::Right)
18033                        }));
18034                    });
18035                }
18036            };
18037        }
18038
18039        self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18040    }
18041}
18042
18043// Consider user intent and default settings
18044fn choose_completion_range(
18045    completion: &Completion,
18046    intent: CompletionIntent,
18047    buffer: &Entity<Buffer>,
18048    cx: &mut Context<Editor>,
18049) -> Range<usize> {
18050    fn should_replace(
18051        completion: &Completion,
18052        insert_range: &Range<text::Anchor>,
18053        intent: CompletionIntent,
18054        completion_mode_setting: LspInsertMode,
18055        buffer: &Buffer,
18056    ) -> bool {
18057        // specific actions take precedence over settings
18058        match intent {
18059            CompletionIntent::CompleteWithInsert => return false,
18060            CompletionIntent::CompleteWithReplace => return true,
18061            CompletionIntent::Complete | CompletionIntent::Compose => {}
18062        }
18063
18064        match completion_mode_setting {
18065            LspInsertMode::Insert => false,
18066            LspInsertMode::Replace => true,
18067            LspInsertMode::ReplaceSubsequence => {
18068                let mut text_to_replace = buffer.chars_for_range(
18069                    buffer.anchor_before(completion.replace_range.start)
18070                        ..buffer.anchor_after(completion.replace_range.end),
18071                );
18072                let mut completion_text = completion.new_text.chars();
18073
18074                // is `text_to_replace` a subsequence of `completion_text`
18075                text_to_replace
18076                    .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18077            }
18078            LspInsertMode::ReplaceSuffix => {
18079                let range_after_cursor = insert_range.end..completion.replace_range.end;
18080
18081                let text_after_cursor = buffer
18082                    .text_for_range(
18083                        buffer.anchor_before(range_after_cursor.start)
18084                            ..buffer.anchor_after(range_after_cursor.end),
18085                    )
18086                    .collect::<String>();
18087                completion.new_text.ends_with(&text_after_cursor)
18088            }
18089        }
18090    }
18091
18092    let buffer = buffer.read(cx);
18093
18094    if let CompletionSource::Lsp {
18095        insert_range: Some(insert_range),
18096        ..
18097    } = &completion.source
18098    {
18099        let completion_mode_setting =
18100            language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18101                .completions
18102                .lsp_insert_mode;
18103
18104        if !should_replace(
18105            completion,
18106            &insert_range,
18107            intent,
18108            completion_mode_setting,
18109            buffer,
18110        ) {
18111            return insert_range.to_offset(buffer);
18112        }
18113    }
18114
18115    completion.replace_range.to_offset(buffer)
18116}
18117
18118fn insert_extra_newline_brackets(
18119    buffer: &MultiBufferSnapshot,
18120    range: Range<usize>,
18121    language: &language::LanguageScope,
18122) -> bool {
18123    let leading_whitespace_len = buffer
18124        .reversed_chars_at(range.start)
18125        .take_while(|c| c.is_whitespace() && *c != '\n')
18126        .map(|c| c.len_utf8())
18127        .sum::<usize>();
18128    let trailing_whitespace_len = buffer
18129        .chars_at(range.end)
18130        .take_while(|c| c.is_whitespace() && *c != '\n')
18131        .map(|c| c.len_utf8())
18132        .sum::<usize>();
18133    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18134
18135    language.brackets().any(|(pair, enabled)| {
18136        let pair_start = pair.start.trim_end();
18137        let pair_end = pair.end.trim_start();
18138
18139        enabled
18140            && pair.newline
18141            && buffer.contains_str_at(range.end, pair_end)
18142            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18143    })
18144}
18145
18146fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18147    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18148        [(buffer, range, _)] => (*buffer, range.clone()),
18149        _ => return false,
18150    };
18151    let pair = {
18152        let mut result: Option<BracketMatch> = None;
18153
18154        for pair in buffer
18155            .all_bracket_ranges(range.clone())
18156            .filter(move |pair| {
18157                pair.open_range.start <= range.start && pair.close_range.end >= range.end
18158            })
18159        {
18160            let len = pair.close_range.end - pair.open_range.start;
18161
18162            if let Some(existing) = &result {
18163                let existing_len = existing.close_range.end - existing.open_range.start;
18164                if len > existing_len {
18165                    continue;
18166                }
18167            }
18168
18169            result = Some(pair);
18170        }
18171
18172        result
18173    };
18174    let Some(pair) = pair else {
18175        return false;
18176    };
18177    pair.newline_only
18178        && buffer
18179            .chars_for_range(pair.open_range.end..range.start)
18180            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18181            .all(|c| c.is_whitespace() && c != '\n')
18182}
18183
18184fn get_uncommitted_diff_for_buffer(
18185    project: &Entity<Project>,
18186    buffers: impl IntoIterator<Item = Entity<Buffer>>,
18187    buffer: Entity<MultiBuffer>,
18188    cx: &mut App,
18189) -> Task<()> {
18190    let mut tasks = Vec::new();
18191    project.update(cx, |project, cx| {
18192        for buffer in buffers {
18193            if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18194                tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18195            }
18196        }
18197    });
18198    cx.spawn(async move |cx| {
18199        let diffs = future::join_all(tasks).await;
18200        buffer
18201            .update(cx, |buffer, cx| {
18202                for diff in diffs.into_iter().flatten() {
18203                    buffer.add_diff(diff, cx);
18204                }
18205            })
18206            .ok();
18207    })
18208}
18209
18210fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18211    let tab_size = tab_size.get() as usize;
18212    let mut width = offset;
18213
18214    for ch in text.chars() {
18215        width += if ch == '\t' {
18216            tab_size - (width % tab_size)
18217        } else {
18218            1
18219        };
18220    }
18221
18222    width - offset
18223}
18224
18225#[cfg(test)]
18226mod tests {
18227    use super::*;
18228
18229    #[test]
18230    fn test_string_size_with_expanded_tabs() {
18231        let nz = |val| NonZeroU32::new(val).unwrap();
18232        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18233        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18234        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18235        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18236        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18237        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18238        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18239        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18240    }
18241}
18242
18243/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18244struct WordBreakingTokenizer<'a> {
18245    input: &'a str,
18246}
18247
18248impl<'a> WordBreakingTokenizer<'a> {
18249    fn new(input: &'a str) -> Self {
18250        Self { input }
18251    }
18252}
18253
18254fn is_char_ideographic(ch: char) -> bool {
18255    use unicode_script::Script::*;
18256    use unicode_script::UnicodeScript;
18257    matches!(ch.script(), Han | Tangut | Yi)
18258}
18259
18260fn is_grapheme_ideographic(text: &str) -> bool {
18261    text.chars().any(is_char_ideographic)
18262}
18263
18264fn is_grapheme_whitespace(text: &str) -> bool {
18265    text.chars().any(|x| x.is_whitespace())
18266}
18267
18268fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18269    text.chars().next().map_or(false, |ch| {
18270        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18271    })
18272}
18273
18274#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18275enum WordBreakToken<'a> {
18276    Word { token: &'a str, grapheme_len: usize },
18277    InlineWhitespace { token: &'a str, grapheme_len: usize },
18278    Newline,
18279}
18280
18281impl<'a> Iterator for WordBreakingTokenizer<'a> {
18282    /// Yields a span, the count of graphemes in the token, and whether it was
18283    /// whitespace. Note that it also breaks at word boundaries.
18284    type Item = WordBreakToken<'a>;
18285
18286    fn next(&mut self) -> Option<Self::Item> {
18287        use unicode_segmentation::UnicodeSegmentation;
18288        if self.input.is_empty() {
18289            return None;
18290        }
18291
18292        let mut iter = self.input.graphemes(true).peekable();
18293        let mut offset = 0;
18294        let mut grapheme_len = 0;
18295        if let Some(first_grapheme) = iter.next() {
18296            let is_newline = first_grapheme == "\n";
18297            let is_whitespace = is_grapheme_whitespace(first_grapheme);
18298            offset += first_grapheme.len();
18299            grapheme_len += 1;
18300            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
18301                if let Some(grapheme) = iter.peek().copied() {
18302                    if should_stay_with_preceding_ideograph(grapheme) {
18303                        offset += grapheme.len();
18304                        grapheme_len += 1;
18305                    }
18306                }
18307            } else {
18308                let mut words = self.input[offset..].split_word_bound_indices().peekable();
18309                let mut next_word_bound = words.peek().copied();
18310                if next_word_bound.map_or(false, |(i, _)| i == 0) {
18311                    next_word_bound = words.next();
18312                }
18313                while let Some(grapheme) = iter.peek().copied() {
18314                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
18315                        break;
18316                    };
18317                    if is_grapheme_whitespace(grapheme) != is_whitespace
18318                        || (grapheme == "\n") != is_newline
18319                    {
18320                        break;
18321                    };
18322                    offset += grapheme.len();
18323                    grapheme_len += 1;
18324                    iter.next();
18325                }
18326            }
18327            let token = &self.input[..offset];
18328            self.input = &self.input[offset..];
18329            if token == "\n" {
18330                Some(WordBreakToken::Newline)
18331            } else if is_whitespace {
18332                Some(WordBreakToken::InlineWhitespace {
18333                    token,
18334                    grapheme_len,
18335                })
18336            } else {
18337                Some(WordBreakToken::Word {
18338                    token,
18339                    grapheme_len,
18340                })
18341            }
18342        } else {
18343            None
18344        }
18345    }
18346}
18347
18348#[test]
18349fn test_word_breaking_tokenizer() {
18350    let tests: &[(&str, &[WordBreakToken<'static>])] = &[
18351        ("", &[]),
18352        ("  ", &[whitespace("  ", 2)]),
18353        ("Ʒ", &[word("Ʒ", 1)]),
18354        ("Ǽ", &[word("Ǽ", 1)]),
18355        ("", &[word("", 1)]),
18356        ("⋑⋑", &[word("⋑⋑", 2)]),
18357        (
18358            "原理,进而",
18359            &[word("", 1), word("理,", 2), word("", 1), word("", 1)],
18360        ),
18361        (
18362            "hello world",
18363            &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
18364        ),
18365        (
18366            "hello, world",
18367            &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
18368        ),
18369        (
18370            "  hello world",
18371            &[
18372                whitespace("  ", 2),
18373                word("hello", 5),
18374                whitespace(" ", 1),
18375                word("world", 5),
18376            ],
18377        ),
18378        (
18379            "这是什么 \n 钢笔",
18380            &[
18381                word("", 1),
18382                word("", 1),
18383                word("", 1),
18384                word("", 1),
18385                whitespace(" ", 1),
18386                newline(),
18387                whitespace(" ", 1),
18388                word("", 1),
18389                word("", 1),
18390            ],
18391        ),
18392        (" mutton", &[whitespace("", 1), word("mutton", 6)]),
18393    ];
18394
18395    fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18396        WordBreakToken::Word {
18397            token,
18398            grapheme_len,
18399        }
18400    }
18401
18402    fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18403        WordBreakToken::InlineWhitespace {
18404            token,
18405            grapheme_len,
18406        }
18407    }
18408
18409    fn newline() -> WordBreakToken<'static> {
18410        WordBreakToken::Newline
18411    }
18412
18413    for (input, result) in tests {
18414        assert_eq!(
18415            WordBreakingTokenizer::new(input)
18416                .collect::<Vec<_>>()
18417                .as_slice(),
18418            *result,
18419        );
18420    }
18421}
18422
18423fn wrap_with_prefix(
18424    line_prefix: String,
18425    unwrapped_text: String,
18426    wrap_column: usize,
18427    tab_size: NonZeroU32,
18428    preserve_existing_whitespace: bool,
18429) -> String {
18430    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
18431    let mut wrapped_text = String::new();
18432    let mut current_line = line_prefix.clone();
18433
18434    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
18435    let mut current_line_len = line_prefix_len;
18436    let mut in_whitespace = false;
18437    for token in tokenizer {
18438        let have_preceding_whitespace = in_whitespace;
18439        match token {
18440            WordBreakToken::Word {
18441                token,
18442                grapheme_len,
18443            } => {
18444                in_whitespace = false;
18445                if current_line_len + grapheme_len > wrap_column
18446                    && current_line_len != line_prefix_len
18447                {
18448                    wrapped_text.push_str(current_line.trim_end());
18449                    wrapped_text.push('\n');
18450                    current_line.truncate(line_prefix.len());
18451                    current_line_len = line_prefix_len;
18452                }
18453                current_line.push_str(token);
18454                current_line_len += grapheme_len;
18455            }
18456            WordBreakToken::InlineWhitespace {
18457                mut token,
18458                mut grapheme_len,
18459            } => {
18460                in_whitespace = true;
18461                if have_preceding_whitespace && !preserve_existing_whitespace {
18462                    continue;
18463                }
18464                if !preserve_existing_whitespace {
18465                    token = " ";
18466                    grapheme_len = 1;
18467                }
18468                if current_line_len + grapheme_len > wrap_column {
18469                    wrapped_text.push_str(current_line.trim_end());
18470                    wrapped_text.push('\n');
18471                    current_line.truncate(line_prefix.len());
18472                    current_line_len = line_prefix_len;
18473                } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
18474                    current_line.push_str(token);
18475                    current_line_len += grapheme_len;
18476                }
18477            }
18478            WordBreakToken::Newline => {
18479                in_whitespace = true;
18480                if preserve_existing_whitespace {
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                } else if have_preceding_whitespace {
18486                    continue;
18487                } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
18488                {
18489                    wrapped_text.push_str(current_line.trim_end());
18490                    wrapped_text.push('\n');
18491                    current_line.truncate(line_prefix.len());
18492                    current_line_len = line_prefix_len;
18493                } else if current_line_len != line_prefix_len {
18494                    current_line.push(' ');
18495                    current_line_len += 1;
18496                }
18497            }
18498        }
18499    }
18500
18501    if !current_line.is_empty() {
18502        wrapped_text.push_str(&current_line);
18503    }
18504    wrapped_text
18505}
18506
18507#[test]
18508fn test_wrap_with_prefix() {
18509    assert_eq!(
18510        wrap_with_prefix(
18511            "# ".to_string(),
18512            "abcdefg".to_string(),
18513            4,
18514            NonZeroU32::new(4).unwrap(),
18515            false,
18516        ),
18517        "# abcdefg"
18518    );
18519    assert_eq!(
18520        wrap_with_prefix(
18521            "".to_string(),
18522            "\thello world".to_string(),
18523            8,
18524            NonZeroU32::new(4).unwrap(),
18525            false,
18526        ),
18527        "hello\nworld"
18528    );
18529    assert_eq!(
18530        wrap_with_prefix(
18531            "// ".to_string(),
18532            "xx \nyy zz aa bb cc".to_string(),
18533            12,
18534            NonZeroU32::new(4).unwrap(),
18535            false,
18536        ),
18537        "// xx yy zz\n// aa bb cc"
18538    );
18539    assert_eq!(
18540        wrap_with_prefix(
18541            String::new(),
18542            "这是什么 \n 钢笔".to_string(),
18543            3,
18544            NonZeroU32::new(4).unwrap(),
18545            false,
18546        ),
18547        "这是什\n么 钢\n"
18548    );
18549}
18550
18551pub trait CollaborationHub {
18552    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
18553    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
18554    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
18555}
18556
18557impl CollaborationHub for Entity<Project> {
18558    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
18559        self.read(cx).collaborators()
18560    }
18561
18562    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
18563        self.read(cx).user_store().read(cx).participant_indices()
18564    }
18565
18566    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
18567        let this = self.read(cx);
18568        let user_ids = this.collaborators().values().map(|c| c.user_id);
18569        this.user_store().read_with(cx, |user_store, cx| {
18570            user_store.participant_names(user_ids, cx)
18571        })
18572    }
18573}
18574
18575pub trait SemanticsProvider {
18576    fn hover(
18577        &self,
18578        buffer: &Entity<Buffer>,
18579        position: text::Anchor,
18580        cx: &mut App,
18581    ) -> Option<Task<Vec<project::Hover>>>;
18582
18583    fn inlay_hints(
18584        &self,
18585        buffer_handle: Entity<Buffer>,
18586        range: Range<text::Anchor>,
18587        cx: &mut App,
18588    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
18589
18590    fn resolve_inlay_hint(
18591        &self,
18592        hint: InlayHint,
18593        buffer_handle: Entity<Buffer>,
18594        server_id: LanguageServerId,
18595        cx: &mut App,
18596    ) -> Option<Task<anyhow::Result<InlayHint>>>;
18597
18598    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
18599
18600    fn document_highlights(
18601        &self,
18602        buffer: &Entity<Buffer>,
18603        position: text::Anchor,
18604        cx: &mut App,
18605    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
18606
18607    fn definitions(
18608        &self,
18609        buffer: &Entity<Buffer>,
18610        position: text::Anchor,
18611        kind: GotoDefinitionKind,
18612        cx: &mut App,
18613    ) -> Option<Task<Result<Vec<LocationLink>>>>;
18614
18615    fn range_for_rename(
18616        &self,
18617        buffer: &Entity<Buffer>,
18618        position: text::Anchor,
18619        cx: &mut App,
18620    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
18621
18622    fn perform_rename(
18623        &self,
18624        buffer: &Entity<Buffer>,
18625        position: text::Anchor,
18626        new_name: String,
18627        cx: &mut App,
18628    ) -> Option<Task<Result<ProjectTransaction>>>;
18629}
18630
18631pub trait CompletionProvider {
18632    fn completions(
18633        &self,
18634        excerpt_id: ExcerptId,
18635        buffer: &Entity<Buffer>,
18636        buffer_position: text::Anchor,
18637        trigger: CompletionContext,
18638        window: &mut Window,
18639        cx: &mut Context<Editor>,
18640    ) -> Task<Result<Option<Vec<Completion>>>>;
18641
18642    fn resolve_completions(
18643        &self,
18644        buffer: Entity<Buffer>,
18645        completion_indices: Vec<usize>,
18646        completions: Rc<RefCell<Box<[Completion]>>>,
18647        cx: &mut Context<Editor>,
18648    ) -> Task<Result<bool>>;
18649
18650    fn apply_additional_edits_for_completion(
18651        &self,
18652        _buffer: Entity<Buffer>,
18653        _completions: Rc<RefCell<Box<[Completion]>>>,
18654        _completion_index: usize,
18655        _push_to_history: bool,
18656        _cx: &mut Context<Editor>,
18657    ) -> Task<Result<Option<language::Transaction>>> {
18658        Task::ready(Ok(None))
18659    }
18660
18661    fn is_completion_trigger(
18662        &self,
18663        buffer: &Entity<Buffer>,
18664        position: language::Anchor,
18665        text: &str,
18666        trigger_in_words: bool,
18667        cx: &mut Context<Editor>,
18668    ) -> bool;
18669
18670    fn sort_completions(&self) -> bool {
18671        true
18672    }
18673
18674    fn filter_completions(&self) -> bool {
18675        true
18676    }
18677}
18678
18679pub trait CodeActionProvider {
18680    fn id(&self) -> Arc<str>;
18681
18682    fn code_actions(
18683        &self,
18684        buffer: &Entity<Buffer>,
18685        range: Range<text::Anchor>,
18686        window: &mut Window,
18687        cx: &mut App,
18688    ) -> Task<Result<Vec<CodeAction>>>;
18689
18690    fn apply_code_action(
18691        &self,
18692        buffer_handle: Entity<Buffer>,
18693        action: CodeAction,
18694        excerpt_id: ExcerptId,
18695        push_to_history: bool,
18696        window: &mut Window,
18697        cx: &mut App,
18698    ) -> Task<Result<ProjectTransaction>>;
18699}
18700
18701impl CodeActionProvider for Entity<Project> {
18702    fn id(&self) -> Arc<str> {
18703        "project".into()
18704    }
18705
18706    fn code_actions(
18707        &self,
18708        buffer: &Entity<Buffer>,
18709        range: Range<text::Anchor>,
18710        _window: &mut Window,
18711        cx: &mut App,
18712    ) -> Task<Result<Vec<CodeAction>>> {
18713        self.update(cx, |project, cx| {
18714            let code_lens = project.code_lens(buffer, range.clone(), cx);
18715            let code_actions = project.code_actions(buffer, range, None, cx);
18716            cx.background_spawn(async move {
18717                let (code_lens, code_actions) = join(code_lens, code_actions).await;
18718                Ok(code_lens
18719                    .context("code lens fetch")?
18720                    .into_iter()
18721                    .chain(code_actions.context("code action fetch")?)
18722                    .collect())
18723            })
18724        })
18725    }
18726
18727    fn apply_code_action(
18728        &self,
18729        buffer_handle: Entity<Buffer>,
18730        action: CodeAction,
18731        _excerpt_id: ExcerptId,
18732        push_to_history: bool,
18733        _window: &mut Window,
18734        cx: &mut App,
18735    ) -> Task<Result<ProjectTransaction>> {
18736        self.update(cx, |project, cx| {
18737            project.apply_code_action(buffer_handle, action, push_to_history, cx)
18738        })
18739    }
18740}
18741
18742fn snippet_completions(
18743    project: &Project,
18744    buffer: &Entity<Buffer>,
18745    buffer_position: text::Anchor,
18746    cx: &mut App,
18747) -> Task<Result<Vec<Completion>>> {
18748    let language = buffer.read(cx).language_at(buffer_position);
18749    let language_name = language.as_ref().map(|language| language.lsp_id());
18750    let snippet_store = project.snippets().read(cx);
18751    let snippets = snippet_store.snippets_for(language_name, cx);
18752
18753    if snippets.is_empty() {
18754        return Task::ready(Ok(vec![]));
18755    }
18756    let snapshot = buffer.read(cx).text_snapshot();
18757    let chars: String = snapshot
18758        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
18759        .collect();
18760
18761    let scope = language.map(|language| language.default_scope());
18762    let executor = cx.background_executor().clone();
18763
18764    cx.background_spawn(async move {
18765        let classifier = CharClassifier::new(scope).for_completion(true);
18766        let mut last_word = chars
18767            .chars()
18768            .take_while(|c| classifier.is_word(*c))
18769            .collect::<String>();
18770        last_word = last_word.chars().rev().collect();
18771
18772        if last_word.is_empty() {
18773            return Ok(vec![]);
18774        }
18775
18776        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
18777        let to_lsp = |point: &text::Anchor| {
18778            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
18779            point_to_lsp(end)
18780        };
18781        let lsp_end = to_lsp(&buffer_position);
18782
18783        let candidates = snippets
18784            .iter()
18785            .enumerate()
18786            .flat_map(|(ix, snippet)| {
18787                snippet
18788                    .prefix
18789                    .iter()
18790                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
18791            })
18792            .collect::<Vec<StringMatchCandidate>>();
18793
18794        let mut matches = fuzzy::match_strings(
18795            &candidates,
18796            &last_word,
18797            last_word.chars().any(|c| c.is_uppercase()),
18798            100,
18799            &Default::default(),
18800            executor,
18801        )
18802        .await;
18803
18804        // Remove all candidates where the query's start does not match the start of any word in the candidate
18805        if let Some(query_start) = last_word.chars().next() {
18806            matches.retain(|string_match| {
18807                split_words(&string_match.string).any(|word| {
18808                    // Check that the first codepoint of the word as lowercase matches the first
18809                    // codepoint of the query as lowercase
18810                    word.chars()
18811                        .flat_map(|codepoint| codepoint.to_lowercase())
18812                        .zip(query_start.to_lowercase())
18813                        .all(|(word_cp, query_cp)| word_cp == query_cp)
18814                })
18815            });
18816        }
18817
18818        let matched_strings = matches
18819            .into_iter()
18820            .map(|m| m.string)
18821            .collect::<HashSet<_>>();
18822
18823        let result: Vec<Completion> = snippets
18824            .into_iter()
18825            .filter_map(|snippet| {
18826                let matching_prefix = snippet
18827                    .prefix
18828                    .iter()
18829                    .find(|prefix| matched_strings.contains(*prefix))?;
18830                let start = as_offset - last_word.len();
18831                let start = snapshot.anchor_before(start);
18832                let range = start..buffer_position;
18833                let lsp_start = to_lsp(&start);
18834                let lsp_range = lsp::Range {
18835                    start: lsp_start,
18836                    end: lsp_end,
18837                };
18838                Some(Completion {
18839                    replace_range: range,
18840                    new_text: snippet.body.clone(),
18841                    source: CompletionSource::Lsp {
18842                        insert_range: None,
18843                        server_id: LanguageServerId(usize::MAX),
18844                        resolved: true,
18845                        lsp_completion: Box::new(lsp::CompletionItem {
18846                            label: snippet.prefix.first().unwrap().clone(),
18847                            kind: Some(CompletionItemKind::SNIPPET),
18848                            label_details: snippet.description.as_ref().map(|description| {
18849                                lsp::CompletionItemLabelDetails {
18850                                    detail: Some(description.clone()),
18851                                    description: None,
18852                                }
18853                            }),
18854                            insert_text_format: Some(InsertTextFormat::SNIPPET),
18855                            text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
18856                                lsp::InsertReplaceEdit {
18857                                    new_text: snippet.body.clone(),
18858                                    insert: lsp_range,
18859                                    replace: lsp_range,
18860                                },
18861                            )),
18862                            filter_text: Some(snippet.body.clone()),
18863                            sort_text: Some(char::MAX.to_string()),
18864                            ..lsp::CompletionItem::default()
18865                        }),
18866                        lsp_defaults: None,
18867                    },
18868                    label: CodeLabel {
18869                        text: matching_prefix.clone(),
18870                        runs: Vec::new(),
18871                        filter_range: 0..matching_prefix.len(),
18872                    },
18873                    icon_path: None,
18874                    documentation: snippet
18875                        .description
18876                        .clone()
18877                        .map(|description| CompletionDocumentation::SingleLine(description.into())),
18878                    insert_text_mode: None,
18879                    confirm: None,
18880                })
18881            })
18882            .collect();
18883
18884        Ok(result)
18885    })
18886}
18887
18888impl CompletionProvider for Entity<Project> {
18889    fn completions(
18890        &self,
18891        _excerpt_id: ExcerptId,
18892        buffer: &Entity<Buffer>,
18893        buffer_position: text::Anchor,
18894        options: CompletionContext,
18895        _window: &mut Window,
18896        cx: &mut Context<Editor>,
18897    ) -> Task<Result<Option<Vec<Completion>>>> {
18898        self.update(cx, |project, cx| {
18899            let snippets = snippet_completions(project, buffer, buffer_position, cx);
18900            let project_completions = project.completions(buffer, buffer_position, options, cx);
18901            cx.background_spawn(async move {
18902                let snippets_completions = snippets.await?;
18903                match project_completions.await? {
18904                    Some(mut completions) => {
18905                        completions.extend(snippets_completions);
18906                        Ok(Some(completions))
18907                    }
18908                    None => {
18909                        if snippets_completions.is_empty() {
18910                            Ok(None)
18911                        } else {
18912                            Ok(Some(snippets_completions))
18913                        }
18914                    }
18915                }
18916            })
18917        })
18918    }
18919
18920    fn resolve_completions(
18921        &self,
18922        buffer: Entity<Buffer>,
18923        completion_indices: Vec<usize>,
18924        completions: Rc<RefCell<Box<[Completion]>>>,
18925        cx: &mut Context<Editor>,
18926    ) -> Task<Result<bool>> {
18927        self.update(cx, |project, cx| {
18928            project.lsp_store().update(cx, |lsp_store, cx| {
18929                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
18930            })
18931        })
18932    }
18933
18934    fn apply_additional_edits_for_completion(
18935        &self,
18936        buffer: Entity<Buffer>,
18937        completions: Rc<RefCell<Box<[Completion]>>>,
18938        completion_index: usize,
18939        push_to_history: bool,
18940        cx: &mut Context<Editor>,
18941    ) -> Task<Result<Option<language::Transaction>>> {
18942        self.update(cx, |project, cx| {
18943            project.lsp_store().update(cx, |lsp_store, cx| {
18944                lsp_store.apply_additional_edits_for_completion(
18945                    buffer,
18946                    completions,
18947                    completion_index,
18948                    push_to_history,
18949                    cx,
18950                )
18951            })
18952        })
18953    }
18954
18955    fn is_completion_trigger(
18956        &self,
18957        buffer: &Entity<Buffer>,
18958        position: language::Anchor,
18959        text: &str,
18960        trigger_in_words: bool,
18961        cx: &mut Context<Editor>,
18962    ) -> bool {
18963        let mut chars = text.chars();
18964        let char = if let Some(char) = chars.next() {
18965            char
18966        } else {
18967            return false;
18968        };
18969        if chars.next().is_some() {
18970            return false;
18971        }
18972
18973        let buffer = buffer.read(cx);
18974        let snapshot = buffer.snapshot();
18975        if !snapshot.settings_at(position, cx).show_completions_on_input {
18976            return false;
18977        }
18978        let classifier = snapshot.char_classifier_at(position).for_completion(true);
18979        if trigger_in_words && classifier.is_word(char) {
18980            return true;
18981        }
18982
18983        buffer.completion_triggers().contains(text)
18984    }
18985}
18986
18987impl SemanticsProvider for Entity<Project> {
18988    fn hover(
18989        &self,
18990        buffer: &Entity<Buffer>,
18991        position: text::Anchor,
18992        cx: &mut App,
18993    ) -> Option<Task<Vec<project::Hover>>> {
18994        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
18995    }
18996
18997    fn document_highlights(
18998        &self,
18999        buffer: &Entity<Buffer>,
19000        position: text::Anchor,
19001        cx: &mut App,
19002    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19003        Some(self.update(cx, |project, cx| {
19004            project.document_highlights(buffer, position, cx)
19005        }))
19006    }
19007
19008    fn definitions(
19009        &self,
19010        buffer: &Entity<Buffer>,
19011        position: text::Anchor,
19012        kind: GotoDefinitionKind,
19013        cx: &mut App,
19014    ) -> Option<Task<Result<Vec<LocationLink>>>> {
19015        Some(self.update(cx, |project, cx| match kind {
19016            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19017            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19018            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19019            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19020        }))
19021    }
19022
19023    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19024        // TODO: make this work for remote projects
19025        self.update(cx, |this, cx| {
19026            buffer.update(cx, |buffer, cx| {
19027                this.any_language_server_supports_inlay_hints(buffer, cx)
19028            })
19029        })
19030    }
19031
19032    fn inlay_hints(
19033        &self,
19034        buffer_handle: Entity<Buffer>,
19035        range: Range<text::Anchor>,
19036        cx: &mut App,
19037    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19038        Some(self.update(cx, |project, cx| {
19039            project.inlay_hints(buffer_handle, range, cx)
19040        }))
19041    }
19042
19043    fn resolve_inlay_hint(
19044        &self,
19045        hint: InlayHint,
19046        buffer_handle: Entity<Buffer>,
19047        server_id: LanguageServerId,
19048        cx: &mut App,
19049    ) -> Option<Task<anyhow::Result<InlayHint>>> {
19050        Some(self.update(cx, |project, cx| {
19051            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19052        }))
19053    }
19054
19055    fn range_for_rename(
19056        &self,
19057        buffer: &Entity<Buffer>,
19058        position: text::Anchor,
19059        cx: &mut App,
19060    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19061        Some(self.update(cx, |project, cx| {
19062            let buffer = buffer.clone();
19063            let task = project.prepare_rename(buffer.clone(), position, cx);
19064            cx.spawn(async move |_, cx| {
19065                Ok(match task.await? {
19066                    PrepareRenameResponse::Success(range) => Some(range),
19067                    PrepareRenameResponse::InvalidPosition => None,
19068                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19069                        // Fallback on using TreeSitter info to determine identifier range
19070                        buffer.update(cx, |buffer, _| {
19071                            let snapshot = buffer.snapshot();
19072                            let (range, kind) = snapshot.surrounding_word(position);
19073                            if kind != Some(CharKind::Word) {
19074                                return None;
19075                            }
19076                            Some(
19077                                snapshot.anchor_before(range.start)
19078                                    ..snapshot.anchor_after(range.end),
19079                            )
19080                        })?
19081                    }
19082                })
19083            })
19084        }))
19085    }
19086
19087    fn perform_rename(
19088        &self,
19089        buffer: &Entity<Buffer>,
19090        position: text::Anchor,
19091        new_name: String,
19092        cx: &mut App,
19093    ) -> Option<Task<Result<ProjectTransaction>>> {
19094        Some(self.update(cx, |project, cx| {
19095            project.perform_rename(buffer.clone(), position, new_name, cx)
19096        }))
19097    }
19098}
19099
19100fn inlay_hint_settings(
19101    location: Anchor,
19102    snapshot: &MultiBufferSnapshot,
19103    cx: &mut Context<Editor>,
19104) -> InlayHintSettings {
19105    let file = snapshot.file_at(location);
19106    let language = snapshot.language_at(location).map(|l| l.name());
19107    language_settings(language, file, cx).inlay_hints
19108}
19109
19110fn consume_contiguous_rows(
19111    contiguous_row_selections: &mut Vec<Selection<Point>>,
19112    selection: &Selection<Point>,
19113    display_map: &DisplaySnapshot,
19114    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19115) -> (MultiBufferRow, MultiBufferRow) {
19116    contiguous_row_selections.push(selection.clone());
19117    let start_row = MultiBufferRow(selection.start.row);
19118    let mut end_row = ending_row(selection, display_map);
19119
19120    while let Some(next_selection) = selections.peek() {
19121        if next_selection.start.row <= end_row.0 {
19122            end_row = ending_row(next_selection, display_map);
19123            contiguous_row_selections.push(selections.next().unwrap().clone());
19124        } else {
19125            break;
19126        }
19127    }
19128    (start_row, end_row)
19129}
19130
19131fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19132    if next_selection.end.column > 0 || next_selection.is_empty() {
19133        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19134    } else {
19135        MultiBufferRow(next_selection.end.row)
19136    }
19137}
19138
19139impl EditorSnapshot {
19140    pub fn remote_selections_in_range<'a>(
19141        &'a self,
19142        range: &'a Range<Anchor>,
19143        collaboration_hub: &dyn CollaborationHub,
19144        cx: &'a App,
19145    ) -> impl 'a + Iterator<Item = RemoteSelection> {
19146        let participant_names = collaboration_hub.user_names(cx);
19147        let participant_indices = collaboration_hub.user_participant_indices(cx);
19148        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19149        let collaborators_by_replica_id = collaborators_by_peer_id
19150            .iter()
19151            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19152            .collect::<HashMap<_, _>>();
19153        self.buffer_snapshot
19154            .selections_in_range(range, false)
19155            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19156                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19157                let participant_index = participant_indices.get(&collaborator.user_id).copied();
19158                let user_name = participant_names.get(&collaborator.user_id).cloned();
19159                Some(RemoteSelection {
19160                    replica_id,
19161                    selection,
19162                    cursor_shape,
19163                    line_mode,
19164                    participant_index,
19165                    peer_id: collaborator.peer_id,
19166                    user_name,
19167                })
19168            })
19169    }
19170
19171    pub fn hunks_for_ranges(
19172        &self,
19173        ranges: impl IntoIterator<Item = Range<Point>>,
19174    ) -> Vec<MultiBufferDiffHunk> {
19175        let mut hunks = Vec::new();
19176        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19177            HashMap::default();
19178        for query_range in ranges {
19179            let query_rows =
19180                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19181            for hunk in self.buffer_snapshot.diff_hunks_in_range(
19182                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19183            ) {
19184                // Include deleted hunks that are adjacent to the query range, because
19185                // otherwise they would be missed.
19186                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19187                if hunk.status().is_deleted() {
19188                    intersects_range |= hunk.row_range.start == query_rows.end;
19189                    intersects_range |= hunk.row_range.end == query_rows.start;
19190                }
19191                if intersects_range {
19192                    if !processed_buffer_rows
19193                        .entry(hunk.buffer_id)
19194                        .or_default()
19195                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19196                    {
19197                        continue;
19198                    }
19199                    hunks.push(hunk);
19200                }
19201            }
19202        }
19203
19204        hunks
19205    }
19206
19207    fn display_diff_hunks_for_rows<'a>(
19208        &'a self,
19209        display_rows: Range<DisplayRow>,
19210        folded_buffers: &'a HashSet<BufferId>,
19211    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19212        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19213        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19214
19215        self.buffer_snapshot
19216            .diff_hunks_in_range(buffer_start..buffer_end)
19217            .filter_map(|hunk| {
19218                if folded_buffers.contains(&hunk.buffer_id) {
19219                    return None;
19220                }
19221
19222                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
19223                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
19224
19225                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
19226                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
19227
19228                let display_hunk = if hunk_display_start.column() != 0 {
19229                    DisplayDiffHunk::Folded {
19230                        display_row: hunk_display_start.row(),
19231                    }
19232                } else {
19233                    let mut end_row = hunk_display_end.row();
19234                    if hunk_display_end.column() > 0 {
19235                        end_row.0 += 1;
19236                    }
19237                    let is_created_file = hunk.is_created_file();
19238                    DisplayDiffHunk::Unfolded {
19239                        status: hunk.status(),
19240                        diff_base_byte_range: hunk.diff_base_byte_range,
19241                        display_row_range: hunk_display_start.row()..end_row,
19242                        multi_buffer_range: Anchor::range_in_buffer(
19243                            hunk.excerpt_id,
19244                            hunk.buffer_id,
19245                            hunk.buffer_range,
19246                        ),
19247                        is_created_file,
19248                    }
19249                };
19250
19251                Some(display_hunk)
19252            })
19253    }
19254
19255    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
19256        self.display_snapshot.buffer_snapshot.language_at(position)
19257    }
19258
19259    pub fn is_focused(&self) -> bool {
19260        self.is_focused
19261    }
19262
19263    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
19264        self.placeholder_text.as_ref()
19265    }
19266
19267    pub fn scroll_position(&self) -> gpui::Point<f32> {
19268        self.scroll_anchor.scroll_position(&self.display_snapshot)
19269    }
19270
19271    fn gutter_dimensions(
19272        &self,
19273        font_id: FontId,
19274        font_size: Pixels,
19275        max_line_number_width: Pixels,
19276        cx: &App,
19277    ) -> Option<GutterDimensions> {
19278        if !self.show_gutter {
19279            return None;
19280        }
19281
19282        let descent = cx.text_system().descent(font_id, font_size);
19283        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
19284        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
19285
19286        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
19287            matches!(
19288                ProjectSettings::get_global(cx).git.git_gutter,
19289                Some(GitGutterSetting::TrackedFiles)
19290            )
19291        });
19292        let gutter_settings = EditorSettings::get_global(cx).gutter;
19293        let show_line_numbers = self
19294            .show_line_numbers
19295            .unwrap_or(gutter_settings.line_numbers);
19296        let line_gutter_width = if show_line_numbers {
19297            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
19298            let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
19299            max_line_number_width.max(min_width_for_number_on_gutter)
19300        } else {
19301            0.0.into()
19302        };
19303
19304        let show_code_actions = self
19305            .show_code_actions
19306            .unwrap_or(gutter_settings.code_actions);
19307
19308        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
19309        let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
19310
19311        let git_blame_entries_width =
19312            self.git_blame_gutter_max_author_length
19313                .map(|max_author_length| {
19314                    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
19315                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
19316
19317                    /// The number of characters to dedicate to gaps and margins.
19318                    const SPACING_WIDTH: usize = 4;
19319
19320                    let max_char_count = max_author_length.min(renderer.max_author_length())
19321                        + ::git::SHORT_SHA_LENGTH
19322                        + MAX_RELATIVE_TIMESTAMP.len()
19323                        + SPACING_WIDTH;
19324
19325                    em_advance * max_char_count
19326                });
19327
19328        let is_singleton = self.buffer_snapshot.is_singleton();
19329
19330        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
19331        left_padding += if !is_singleton {
19332            em_width * 4.0
19333        } else if show_code_actions || show_runnables || show_breakpoints {
19334            em_width * 3.0
19335        } else if show_git_gutter && show_line_numbers {
19336            em_width * 2.0
19337        } else if show_git_gutter || show_line_numbers {
19338            em_width
19339        } else {
19340            px(0.)
19341        };
19342
19343        let shows_folds = is_singleton && gutter_settings.folds;
19344
19345        let right_padding = if shows_folds && show_line_numbers {
19346            em_width * 4.0
19347        } else if shows_folds || (!is_singleton && show_line_numbers) {
19348            em_width * 3.0
19349        } else if show_line_numbers {
19350            em_width
19351        } else {
19352            px(0.)
19353        };
19354
19355        Some(GutterDimensions {
19356            left_padding,
19357            right_padding,
19358            width: line_gutter_width + left_padding + right_padding,
19359            margin: -descent,
19360            git_blame_entries_width,
19361        })
19362    }
19363
19364    pub fn render_crease_toggle(
19365        &self,
19366        buffer_row: MultiBufferRow,
19367        row_contains_cursor: bool,
19368        editor: Entity<Editor>,
19369        window: &mut Window,
19370        cx: &mut App,
19371    ) -> Option<AnyElement> {
19372        let folded = self.is_line_folded(buffer_row);
19373        let mut is_foldable = false;
19374
19375        if let Some(crease) = self
19376            .crease_snapshot
19377            .query_row(buffer_row, &self.buffer_snapshot)
19378        {
19379            is_foldable = true;
19380            match crease {
19381                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
19382                    if let Some(render_toggle) = render_toggle {
19383                        let toggle_callback =
19384                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
19385                                if folded {
19386                                    editor.update(cx, |editor, cx| {
19387                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
19388                                    });
19389                                } else {
19390                                    editor.update(cx, |editor, cx| {
19391                                        editor.unfold_at(
19392                                            &crate::UnfoldAt { buffer_row },
19393                                            window,
19394                                            cx,
19395                                        )
19396                                    });
19397                                }
19398                            });
19399                        return Some((render_toggle)(
19400                            buffer_row,
19401                            folded,
19402                            toggle_callback,
19403                            window,
19404                            cx,
19405                        ));
19406                    }
19407                }
19408            }
19409        }
19410
19411        is_foldable |= self.starts_indent(buffer_row);
19412
19413        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
19414            Some(
19415                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
19416                    .toggle_state(folded)
19417                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
19418                        if folded {
19419                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
19420                        } else {
19421                            this.fold_at(&FoldAt { buffer_row }, window, cx);
19422                        }
19423                    }))
19424                    .into_any_element(),
19425            )
19426        } else {
19427            None
19428        }
19429    }
19430
19431    pub fn render_crease_trailer(
19432        &self,
19433        buffer_row: MultiBufferRow,
19434        window: &mut Window,
19435        cx: &mut App,
19436    ) -> Option<AnyElement> {
19437        let folded = self.is_line_folded(buffer_row);
19438        if let Crease::Inline { render_trailer, .. } = self
19439            .crease_snapshot
19440            .query_row(buffer_row, &self.buffer_snapshot)?
19441        {
19442            let render_trailer = render_trailer.as_ref()?;
19443            Some(render_trailer(buffer_row, folded, window, cx))
19444        } else {
19445            None
19446        }
19447    }
19448}
19449
19450impl Deref for EditorSnapshot {
19451    type Target = DisplaySnapshot;
19452
19453    fn deref(&self) -> &Self::Target {
19454        &self.display_snapshot
19455    }
19456}
19457
19458#[derive(Clone, Debug, PartialEq, Eq)]
19459pub enum EditorEvent {
19460    InputIgnored {
19461        text: Arc<str>,
19462    },
19463    InputHandled {
19464        utf16_range_to_replace: Option<Range<isize>>,
19465        text: Arc<str>,
19466    },
19467    ExcerptsAdded {
19468        buffer: Entity<Buffer>,
19469        predecessor: ExcerptId,
19470        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
19471    },
19472    ExcerptsRemoved {
19473        ids: Vec<ExcerptId>,
19474    },
19475    BufferFoldToggled {
19476        ids: Vec<ExcerptId>,
19477        folded: bool,
19478    },
19479    ExcerptsEdited {
19480        ids: Vec<ExcerptId>,
19481    },
19482    ExcerptsExpanded {
19483        ids: Vec<ExcerptId>,
19484    },
19485    BufferEdited,
19486    Edited {
19487        transaction_id: clock::Lamport,
19488    },
19489    Reparsed(BufferId),
19490    Focused,
19491    FocusedIn,
19492    Blurred,
19493    DirtyChanged,
19494    Saved,
19495    TitleChanged,
19496    DiffBaseChanged,
19497    SelectionsChanged {
19498        local: bool,
19499    },
19500    ScrollPositionChanged {
19501        local: bool,
19502        autoscroll: bool,
19503    },
19504    Closed,
19505    TransactionUndone {
19506        transaction_id: clock::Lamport,
19507    },
19508    TransactionBegun {
19509        transaction_id: clock::Lamport,
19510    },
19511    Reloaded,
19512    CursorShapeChanged,
19513    PushedToNavHistory {
19514        anchor: Anchor,
19515        is_deactivate: bool,
19516    },
19517}
19518
19519impl EventEmitter<EditorEvent> for Editor {}
19520
19521impl Focusable for Editor {
19522    fn focus_handle(&self, _cx: &App) -> FocusHandle {
19523        self.focus_handle.clone()
19524    }
19525}
19526
19527impl Render for Editor {
19528    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19529        let settings = ThemeSettings::get_global(cx);
19530
19531        let mut text_style = match self.mode {
19532            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
19533                color: cx.theme().colors().editor_foreground,
19534                font_family: settings.ui_font.family.clone(),
19535                font_features: settings.ui_font.features.clone(),
19536                font_fallbacks: settings.ui_font.fallbacks.clone(),
19537                font_size: rems(0.875).into(),
19538                font_weight: settings.ui_font.weight,
19539                line_height: relative(settings.buffer_line_height.value()),
19540                ..Default::default()
19541            },
19542            EditorMode::Full { .. } => TextStyle {
19543                color: cx.theme().colors().editor_foreground,
19544                font_family: settings.buffer_font.family.clone(),
19545                font_features: settings.buffer_font.features.clone(),
19546                font_fallbacks: settings.buffer_font.fallbacks.clone(),
19547                font_size: settings.buffer_font_size(cx).into(),
19548                font_weight: settings.buffer_font.weight,
19549                line_height: relative(settings.buffer_line_height.value()),
19550                ..Default::default()
19551            },
19552        };
19553        if let Some(text_style_refinement) = &self.text_style_refinement {
19554            text_style.refine(text_style_refinement)
19555        }
19556
19557        let background = match self.mode {
19558            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
19559            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
19560            EditorMode::Full { .. } => cx.theme().colors().editor_background,
19561        };
19562
19563        EditorElement::new(
19564            &cx.entity(),
19565            EditorStyle {
19566                background,
19567                local_player: cx.theme().players().local(),
19568                text: text_style,
19569                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
19570                syntax: cx.theme().syntax().clone(),
19571                status: cx.theme().status().clone(),
19572                inlay_hints_style: make_inlay_hints_style(cx),
19573                inline_completion_styles: make_suggestion_styles(cx),
19574                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
19575            },
19576        )
19577    }
19578}
19579
19580impl EntityInputHandler for Editor {
19581    fn text_for_range(
19582        &mut self,
19583        range_utf16: Range<usize>,
19584        adjusted_range: &mut Option<Range<usize>>,
19585        _: &mut Window,
19586        cx: &mut Context<Self>,
19587    ) -> Option<String> {
19588        let snapshot = self.buffer.read(cx).read(cx);
19589        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
19590        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
19591        if (start.0..end.0) != range_utf16 {
19592            adjusted_range.replace(start.0..end.0);
19593        }
19594        Some(snapshot.text_for_range(start..end).collect())
19595    }
19596
19597    fn selected_text_range(
19598        &mut self,
19599        ignore_disabled_input: bool,
19600        _: &mut Window,
19601        cx: &mut Context<Self>,
19602    ) -> Option<UTF16Selection> {
19603        // Prevent the IME menu from appearing when holding down an alphabetic key
19604        // while input is disabled.
19605        if !ignore_disabled_input && !self.input_enabled {
19606            return None;
19607        }
19608
19609        let selection = self.selections.newest::<OffsetUtf16>(cx);
19610        let range = selection.range();
19611
19612        Some(UTF16Selection {
19613            range: range.start.0..range.end.0,
19614            reversed: selection.reversed,
19615        })
19616    }
19617
19618    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
19619        let snapshot = self.buffer.read(cx).read(cx);
19620        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
19621        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
19622    }
19623
19624    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
19625        self.clear_highlights::<InputComposition>(cx);
19626        self.ime_transaction.take();
19627    }
19628
19629    fn replace_text_in_range(
19630        &mut self,
19631        range_utf16: Option<Range<usize>>,
19632        text: &str,
19633        window: &mut Window,
19634        cx: &mut Context<Self>,
19635    ) {
19636        if !self.input_enabled {
19637            cx.emit(EditorEvent::InputIgnored { text: text.into() });
19638            return;
19639        }
19640
19641        self.transact(window, cx, |this, window, cx| {
19642            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
19643                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19644                Some(this.selection_replacement_ranges(range_utf16, cx))
19645            } else {
19646                this.marked_text_ranges(cx)
19647            };
19648
19649            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
19650                let newest_selection_id = this.selections.newest_anchor().id;
19651                this.selections
19652                    .all::<OffsetUtf16>(cx)
19653                    .iter()
19654                    .zip(ranges_to_replace.iter())
19655                    .find_map(|(selection, range)| {
19656                        if selection.id == newest_selection_id {
19657                            Some(
19658                                (range.start.0 as isize - selection.head().0 as isize)
19659                                    ..(range.end.0 as isize - selection.head().0 as isize),
19660                            )
19661                        } else {
19662                            None
19663                        }
19664                    })
19665            });
19666
19667            cx.emit(EditorEvent::InputHandled {
19668                utf16_range_to_replace: range_to_replace,
19669                text: text.into(),
19670            });
19671
19672            if let Some(new_selected_ranges) = new_selected_ranges {
19673                this.change_selections(None, window, cx, |selections| {
19674                    selections.select_ranges(new_selected_ranges)
19675                });
19676                this.backspace(&Default::default(), window, cx);
19677            }
19678
19679            this.handle_input(text, window, cx);
19680        });
19681
19682        if let Some(transaction) = self.ime_transaction {
19683            self.buffer.update(cx, |buffer, cx| {
19684                buffer.group_until_transaction(transaction, cx);
19685            });
19686        }
19687
19688        self.unmark_text(window, cx);
19689    }
19690
19691    fn replace_and_mark_text_in_range(
19692        &mut self,
19693        range_utf16: Option<Range<usize>>,
19694        text: &str,
19695        new_selected_range_utf16: Option<Range<usize>>,
19696        window: &mut Window,
19697        cx: &mut Context<Self>,
19698    ) {
19699        if !self.input_enabled {
19700            return;
19701        }
19702
19703        let transaction = self.transact(window, cx, |this, window, cx| {
19704            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
19705                let snapshot = this.buffer.read(cx).read(cx);
19706                if let Some(relative_range_utf16) = range_utf16.as_ref() {
19707                    for marked_range in &mut marked_ranges {
19708                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
19709                        marked_range.start.0 += relative_range_utf16.start;
19710                        marked_range.start =
19711                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
19712                        marked_range.end =
19713                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
19714                    }
19715                }
19716                Some(marked_ranges)
19717            } else if let Some(range_utf16) = range_utf16 {
19718                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19719                Some(this.selection_replacement_ranges(range_utf16, cx))
19720            } else {
19721                None
19722            };
19723
19724            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
19725                let newest_selection_id = this.selections.newest_anchor().id;
19726                this.selections
19727                    .all::<OffsetUtf16>(cx)
19728                    .iter()
19729                    .zip(ranges_to_replace.iter())
19730                    .find_map(|(selection, range)| {
19731                        if selection.id == newest_selection_id {
19732                            Some(
19733                                (range.start.0 as isize - selection.head().0 as isize)
19734                                    ..(range.end.0 as isize - selection.head().0 as isize),
19735                            )
19736                        } else {
19737                            None
19738                        }
19739                    })
19740            });
19741
19742            cx.emit(EditorEvent::InputHandled {
19743                utf16_range_to_replace: range_to_replace,
19744                text: text.into(),
19745            });
19746
19747            if let Some(ranges) = ranges_to_replace {
19748                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
19749            }
19750
19751            let marked_ranges = {
19752                let snapshot = this.buffer.read(cx).read(cx);
19753                this.selections
19754                    .disjoint_anchors()
19755                    .iter()
19756                    .map(|selection| {
19757                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
19758                    })
19759                    .collect::<Vec<_>>()
19760            };
19761
19762            if text.is_empty() {
19763                this.unmark_text(window, cx);
19764            } else {
19765                this.highlight_text::<InputComposition>(
19766                    marked_ranges.clone(),
19767                    HighlightStyle {
19768                        underline: Some(UnderlineStyle {
19769                            thickness: px(1.),
19770                            color: None,
19771                            wavy: false,
19772                        }),
19773                        ..Default::default()
19774                    },
19775                    cx,
19776                );
19777            }
19778
19779            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
19780            let use_autoclose = this.use_autoclose;
19781            let use_auto_surround = this.use_auto_surround;
19782            this.set_use_autoclose(false);
19783            this.set_use_auto_surround(false);
19784            this.handle_input(text, window, cx);
19785            this.set_use_autoclose(use_autoclose);
19786            this.set_use_auto_surround(use_auto_surround);
19787
19788            if let Some(new_selected_range) = new_selected_range_utf16 {
19789                let snapshot = this.buffer.read(cx).read(cx);
19790                let new_selected_ranges = marked_ranges
19791                    .into_iter()
19792                    .map(|marked_range| {
19793                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
19794                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
19795                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
19796                        snapshot.clip_offset_utf16(new_start, Bias::Left)
19797                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
19798                    })
19799                    .collect::<Vec<_>>();
19800
19801                drop(snapshot);
19802                this.change_selections(None, window, cx, |selections| {
19803                    selections.select_ranges(new_selected_ranges)
19804                });
19805            }
19806        });
19807
19808        self.ime_transaction = self.ime_transaction.or(transaction);
19809        if let Some(transaction) = self.ime_transaction {
19810            self.buffer.update(cx, |buffer, cx| {
19811                buffer.group_until_transaction(transaction, cx);
19812            });
19813        }
19814
19815        if self.text_highlights::<InputComposition>(cx).is_none() {
19816            self.ime_transaction.take();
19817        }
19818    }
19819
19820    fn bounds_for_range(
19821        &mut self,
19822        range_utf16: Range<usize>,
19823        element_bounds: gpui::Bounds<Pixels>,
19824        window: &mut Window,
19825        cx: &mut Context<Self>,
19826    ) -> Option<gpui::Bounds<Pixels>> {
19827        let text_layout_details = self.text_layout_details(window);
19828        let gpui::Size {
19829            width: em_width,
19830            height: line_height,
19831        } = self.character_size(window);
19832
19833        let snapshot = self.snapshot(window, cx);
19834        let scroll_position = snapshot.scroll_position();
19835        let scroll_left = scroll_position.x * em_width;
19836
19837        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
19838        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
19839            + self.gutter_dimensions.width
19840            + self.gutter_dimensions.margin;
19841        let y = line_height * (start.row().as_f32() - scroll_position.y);
19842
19843        Some(Bounds {
19844            origin: element_bounds.origin + point(x, y),
19845            size: size(em_width, line_height),
19846        })
19847    }
19848
19849    fn character_index_for_point(
19850        &mut self,
19851        point: gpui::Point<Pixels>,
19852        _window: &mut Window,
19853        _cx: &mut Context<Self>,
19854    ) -> Option<usize> {
19855        let position_map = self.last_position_map.as_ref()?;
19856        if !position_map.text_hitbox.contains(&point) {
19857            return None;
19858        }
19859        let display_point = position_map.point_for_position(point).previous_valid;
19860        let anchor = position_map
19861            .snapshot
19862            .display_point_to_anchor(display_point, Bias::Left);
19863        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
19864        Some(utf16_offset.0)
19865    }
19866}
19867
19868trait SelectionExt {
19869    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
19870    fn spanned_rows(
19871        &self,
19872        include_end_if_at_line_start: bool,
19873        map: &DisplaySnapshot,
19874    ) -> Range<MultiBufferRow>;
19875}
19876
19877impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
19878    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
19879        let start = self
19880            .start
19881            .to_point(&map.buffer_snapshot)
19882            .to_display_point(map);
19883        let end = self
19884            .end
19885            .to_point(&map.buffer_snapshot)
19886            .to_display_point(map);
19887        if self.reversed {
19888            end..start
19889        } else {
19890            start..end
19891        }
19892    }
19893
19894    fn spanned_rows(
19895        &self,
19896        include_end_if_at_line_start: bool,
19897        map: &DisplaySnapshot,
19898    ) -> Range<MultiBufferRow> {
19899        let start = self.start.to_point(&map.buffer_snapshot);
19900        let mut end = self.end.to_point(&map.buffer_snapshot);
19901        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
19902            end.row -= 1;
19903        }
19904
19905        let buffer_start = map.prev_line_boundary(start).0;
19906        let buffer_end = map.next_line_boundary(end).0;
19907        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
19908    }
19909}
19910
19911impl<T: InvalidationRegion> InvalidationStack<T> {
19912    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
19913    where
19914        S: Clone + ToOffset,
19915    {
19916        while let Some(region) = self.last() {
19917            let all_selections_inside_invalidation_ranges =
19918                if selections.len() == region.ranges().len() {
19919                    selections
19920                        .iter()
19921                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
19922                        .all(|(selection, invalidation_range)| {
19923                            let head = selection.head().to_offset(buffer);
19924                            invalidation_range.start <= head && invalidation_range.end >= head
19925                        })
19926                } else {
19927                    false
19928                };
19929
19930            if all_selections_inside_invalidation_ranges {
19931                break;
19932            } else {
19933                self.pop();
19934            }
19935        }
19936    }
19937}
19938
19939impl<T> Default for InvalidationStack<T> {
19940    fn default() -> Self {
19941        Self(Default::default())
19942    }
19943}
19944
19945impl<T> Deref for InvalidationStack<T> {
19946    type Target = Vec<T>;
19947
19948    fn deref(&self) -> &Self::Target {
19949        &self.0
19950    }
19951}
19952
19953impl<T> DerefMut for InvalidationStack<T> {
19954    fn deref_mut(&mut self) -> &mut Self::Target {
19955        &mut self.0
19956    }
19957}
19958
19959impl InvalidationRegion for SnippetState {
19960    fn ranges(&self) -> &[Range<Anchor>] {
19961        &self.ranges[self.active_index]
19962    }
19963}
19964
19965pub fn diagnostic_block_renderer(
19966    diagnostic: Diagnostic,
19967    max_message_rows: Option<u8>,
19968    allow_closing: bool,
19969) -> RenderBlock {
19970    let (text_without_backticks, code_ranges) =
19971        highlight_diagnostic_message(&diagnostic, max_message_rows);
19972
19973    Arc::new(move |cx: &mut BlockContext| {
19974        let group_id: SharedString = cx.block_id.to_string().into();
19975
19976        let mut text_style = cx.window.text_style().clone();
19977        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
19978        let theme_settings = ThemeSettings::get_global(cx);
19979        text_style.font_family = theme_settings.buffer_font.family.clone();
19980        text_style.font_style = theme_settings.buffer_font.style;
19981        text_style.font_features = theme_settings.buffer_font.features.clone();
19982        text_style.font_weight = theme_settings.buffer_font.weight;
19983
19984        let multi_line_diagnostic = diagnostic.message.contains('\n');
19985
19986        let buttons = |diagnostic: &Diagnostic| {
19987            if multi_line_diagnostic {
19988                v_flex()
19989            } else {
19990                h_flex()
19991            }
19992            .when(allow_closing, |div| {
19993                div.children(diagnostic.is_primary.then(|| {
19994                    IconButton::new("close-block", IconName::XCircle)
19995                        .icon_color(Color::Muted)
19996                        .size(ButtonSize::Compact)
19997                        .style(ButtonStyle::Transparent)
19998                        .visible_on_hover(group_id.clone())
19999                        .on_click(move |_click, window, cx| {
20000                            window.dispatch_action(Box::new(Cancel), cx)
20001                        })
20002                        .tooltip(|window, cx| {
20003                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
20004                        })
20005                }))
20006            })
20007            .child(
20008                IconButton::new("copy-block", IconName::Copy)
20009                    .icon_color(Color::Muted)
20010                    .size(ButtonSize::Compact)
20011                    .style(ButtonStyle::Transparent)
20012                    .visible_on_hover(group_id.clone())
20013                    .on_click({
20014                        let message = diagnostic.message.clone();
20015                        move |_click, _, cx| {
20016                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
20017                        }
20018                    })
20019                    .tooltip(Tooltip::text("Copy diagnostic message")),
20020            )
20021        };
20022
20023        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
20024            AvailableSpace::min_size(),
20025            cx.window,
20026            cx.app,
20027        );
20028
20029        h_flex()
20030            .id(cx.block_id)
20031            .group(group_id.clone())
20032            .relative()
20033            .size_full()
20034            .block_mouse_down()
20035            .pl(cx.gutter_dimensions.width)
20036            .w(cx.max_width - cx.gutter_dimensions.full_width())
20037            .child(
20038                div()
20039                    .flex()
20040                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
20041                    .flex_shrink(),
20042            )
20043            .child(buttons(&diagnostic))
20044            .child(div().flex().flex_shrink_0().child(
20045                StyledText::new(text_without_backticks.clone()).with_default_highlights(
20046                    &text_style,
20047                    code_ranges.iter().map(|range| {
20048                        (
20049                            range.clone(),
20050                            HighlightStyle {
20051                                font_weight: Some(FontWeight::BOLD),
20052                                ..Default::default()
20053                            },
20054                        )
20055                    }),
20056                ),
20057            ))
20058            .into_any_element()
20059    })
20060}
20061
20062fn inline_completion_edit_text(
20063    current_snapshot: &BufferSnapshot,
20064    edits: &[(Range<Anchor>, String)],
20065    edit_preview: &EditPreview,
20066    include_deletions: bool,
20067    cx: &App,
20068) -> HighlightedText {
20069    let edits = edits
20070        .iter()
20071        .map(|(anchor, text)| {
20072            (
20073                anchor.start.text_anchor..anchor.end.text_anchor,
20074                text.clone(),
20075            )
20076        })
20077        .collect::<Vec<_>>();
20078
20079    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20080}
20081
20082pub fn highlight_diagnostic_message(
20083    diagnostic: &Diagnostic,
20084    mut max_message_rows: Option<u8>,
20085) -> (SharedString, Vec<Range<usize>>) {
20086    let mut text_without_backticks = String::new();
20087    let mut code_ranges = Vec::new();
20088
20089    if let Some(source) = &diagnostic.source {
20090        text_without_backticks.push_str(source);
20091        code_ranges.push(0..source.len());
20092        text_without_backticks.push_str(": ");
20093    }
20094
20095    let mut prev_offset = 0;
20096    let mut in_code_block = false;
20097    let has_row_limit = max_message_rows.is_some();
20098    let mut newline_indices = diagnostic
20099        .message
20100        .match_indices('\n')
20101        .filter(|_| has_row_limit)
20102        .map(|(ix, _)| ix)
20103        .fuse()
20104        .peekable();
20105
20106    for (quote_ix, _) in diagnostic
20107        .message
20108        .match_indices('`')
20109        .chain([(diagnostic.message.len(), "")])
20110    {
20111        let mut first_newline_ix = None;
20112        let mut last_newline_ix = None;
20113        while let Some(newline_ix) = newline_indices.peek() {
20114            if *newline_ix < quote_ix {
20115                if first_newline_ix.is_none() {
20116                    first_newline_ix = Some(*newline_ix);
20117                }
20118                last_newline_ix = Some(*newline_ix);
20119
20120                if let Some(rows_left) = &mut max_message_rows {
20121                    if *rows_left == 0 {
20122                        break;
20123                    } else {
20124                        *rows_left -= 1;
20125                    }
20126                }
20127                let _ = newline_indices.next();
20128            } else {
20129                break;
20130            }
20131        }
20132        let prev_len = text_without_backticks.len();
20133        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
20134        text_without_backticks.push_str(new_text);
20135        if in_code_block {
20136            code_ranges.push(prev_len..text_without_backticks.len());
20137        }
20138        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
20139        in_code_block = !in_code_block;
20140        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
20141            text_without_backticks.push_str("...");
20142            break;
20143        }
20144    }
20145
20146    (text_without_backticks.into(), code_ranges)
20147}
20148
20149fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20150    match severity {
20151        DiagnosticSeverity::ERROR => colors.error,
20152        DiagnosticSeverity::WARNING => colors.warning,
20153        DiagnosticSeverity::INFORMATION => colors.info,
20154        DiagnosticSeverity::HINT => colors.info,
20155        _ => colors.ignored,
20156    }
20157}
20158
20159pub fn styled_runs_for_code_label<'a>(
20160    label: &'a CodeLabel,
20161    syntax_theme: &'a theme::SyntaxTheme,
20162) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20163    let fade_out = HighlightStyle {
20164        fade_out: Some(0.35),
20165        ..Default::default()
20166    };
20167
20168    let mut prev_end = label.filter_range.end;
20169    label
20170        .runs
20171        .iter()
20172        .enumerate()
20173        .flat_map(move |(ix, (range, highlight_id))| {
20174            let style = if let Some(style) = highlight_id.style(syntax_theme) {
20175                style
20176            } else {
20177                return Default::default();
20178            };
20179            let mut muted_style = style;
20180            muted_style.highlight(fade_out);
20181
20182            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20183            if range.start >= label.filter_range.end {
20184                if range.start > prev_end {
20185                    runs.push((prev_end..range.start, fade_out));
20186                }
20187                runs.push((range.clone(), muted_style));
20188            } else if range.end <= label.filter_range.end {
20189                runs.push((range.clone(), style));
20190            } else {
20191                runs.push((range.start..label.filter_range.end, style));
20192                runs.push((label.filter_range.end..range.end, muted_style));
20193            }
20194            prev_end = cmp::max(prev_end, range.end);
20195
20196            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20197                runs.push((prev_end..label.text.len(), fade_out));
20198            }
20199
20200            runs
20201        })
20202}
20203
20204pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20205    let mut prev_index = 0;
20206    let mut prev_codepoint: Option<char> = None;
20207    text.char_indices()
20208        .chain([(text.len(), '\0')])
20209        .filter_map(move |(index, codepoint)| {
20210            let prev_codepoint = prev_codepoint.replace(codepoint)?;
20211            let is_boundary = index == text.len()
20212                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20213                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20214            if is_boundary {
20215                let chunk = &text[prev_index..index];
20216                prev_index = index;
20217                Some(chunk)
20218            } else {
20219                None
20220            }
20221        })
20222}
20223
20224pub trait RangeToAnchorExt: Sized {
20225    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20226
20227    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20228        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20229        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20230    }
20231}
20232
20233impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20234    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20235        let start_offset = self.start.to_offset(snapshot);
20236        let end_offset = self.end.to_offset(snapshot);
20237        if start_offset == end_offset {
20238            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20239        } else {
20240            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20241        }
20242    }
20243}
20244
20245pub trait RowExt {
20246    fn as_f32(&self) -> f32;
20247
20248    fn next_row(&self) -> Self;
20249
20250    fn previous_row(&self) -> Self;
20251
20252    fn minus(&self, other: Self) -> u32;
20253}
20254
20255impl RowExt for DisplayRow {
20256    fn as_f32(&self) -> f32 {
20257        self.0 as f32
20258    }
20259
20260    fn next_row(&self) -> Self {
20261        Self(self.0 + 1)
20262    }
20263
20264    fn previous_row(&self) -> Self {
20265        Self(self.0.saturating_sub(1))
20266    }
20267
20268    fn minus(&self, other: Self) -> u32 {
20269        self.0 - other.0
20270    }
20271}
20272
20273impl RowExt for MultiBufferRow {
20274    fn as_f32(&self) -> f32 {
20275        self.0 as f32
20276    }
20277
20278    fn next_row(&self) -> Self {
20279        Self(self.0 + 1)
20280    }
20281
20282    fn previous_row(&self) -> Self {
20283        Self(self.0.saturating_sub(1))
20284    }
20285
20286    fn minus(&self, other: Self) -> u32 {
20287        self.0 - other.0
20288    }
20289}
20290
20291trait RowRangeExt {
20292    type Row;
20293
20294    fn len(&self) -> usize;
20295
20296    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20297}
20298
20299impl RowRangeExt for Range<MultiBufferRow> {
20300    type Row = MultiBufferRow;
20301
20302    fn len(&self) -> usize {
20303        (self.end.0 - self.start.0) as usize
20304    }
20305
20306    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20307        (self.start.0..self.end.0).map(MultiBufferRow)
20308    }
20309}
20310
20311impl RowRangeExt for Range<DisplayRow> {
20312    type Row = DisplayRow;
20313
20314    fn len(&self) -> usize {
20315        (self.end.0 - self.start.0) as usize
20316    }
20317
20318    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20319        (self.start.0..self.end.0).map(DisplayRow)
20320    }
20321}
20322
20323/// If select range has more than one line, we
20324/// just point the cursor to range.start.
20325fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20326    if range.start.row == range.end.row {
20327        range
20328    } else {
20329        range.start..range.start
20330    }
20331}
20332pub struct KillRing(ClipboardItem);
20333impl Global for KillRing {}
20334
20335const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20336
20337enum BreakpointPromptEditAction {
20338    Log,
20339    Condition,
20340    HitCondition,
20341}
20342
20343struct BreakpointPromptEditor {
20344    pub(crate) prompt: Entity<Editor>,
20345    editor: WeakEntity<Editor>,
20346    breakpoint_anchor: Anchor,
20347    breakpoint: Breakpoint,
20348    edit_action: BreakpointPromptEditAction,
20349    block_ids: HashSet<CustomBlockId>,
20350    gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20351    _subscriptions: Vec<Subscription>,
20352}
20353
20354impl BreakpointPromptEditor {
20355    const MAX_LINES: u8 = 4;
20356
20357    fn new(
20358        editor: WeakEntity<Editor>,
20359        breakpoint_anchor: Anchor,
20360        breakpoint: Breakpoint,
20361        edit_action: BreakpointPromptEditAction,
20362        window: &mut Window,
20363        cx: &mut Context<Self>,
20364    ) -> Self {
20365        let base_text = match edit_action {
20366            BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20367            BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20368            BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20369        }
20370        .map(|msg| msg.to_string())
20371        .unwrap_or_default();
20372
20373        let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20374        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20375
20376        let prompt = cx.new(|cx| {
20377            let mut prompt = Editor::new(
20378                EditorMode::AutoHeight {
20379                    max_lines: Self::MAX_LINES as usize,
20380                },
20381                buffer,
20382                None,
20383                window,
20384                cx,
20385            );
20386            prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20387            prompt.set_show_cursor_when_unfocused(false, cx);
20388            prompt.set_placeholder_text(
20389                match edit_action {
20390                    BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20391                    BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20392                    BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20393                },
20394                cx,
20395            );
20396
20397            prompt
20398        });
20399
20400        Self {
20401            prompt,
20402            editor,
20403            breakpoint_anchor,
20404            breakpoint,
20405            edit_action,
20406            gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20407            block_ids: Default::default(),
20408            _subscriptions: vec![],
20409        }
20410    }
20411
20412    pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20413        self.block_ids.extend(block_ids)
20414    }
20415
20416    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20417        if let Some(editor) = self.editor.upgrade() {
20418            let message = self
20419                .prompt
20420                .read(cx)
20421                .buffer
20422                .read(cx)
20423                .as_singleton()
20424                .expect("A multi buffer in breakpoint prompt isn't possible")
20425                .read(cx)
20426                .as_rope()
20427                .to_string();
20428
20429            editor.update(cx, |editor, cx| {
20430                editor.edit_breakpoint_at_anchor(
20431                    self.breakpoint_anchor,
20432                    self.breakpoint.clone(),
20433                    match self.edit_action {
20434                        BreakpointPromptEditAction::Log => {
20435                            BreakpointEditAction::EditLogMessage(message.into())
20436                        }
20437                        BreakpointPromptEditAction::Condition => {
20438                            BreakpointEditAction::EditCondition(message.into())
20439                        }
20440                        BreakpointPromptEditAction::HitCondition => {
20441                            BreakpointEditAction::EditHitCondition(message.into())
20442                        }
20443                    },
20444                    cx,
20445                );
20446
20447                editor.remove_blocks(self.block_ids.clone(), None, cx);
20448                cx.focus_self(window);
20449            });
20450        }
20451    }
20452
20453    fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
20454        self.editor
20455            .update(cx, |editor, cx| {
20456                editor.remove_blocks(self.block_ids.clone(), None, cx);
20457                window.focus(&editor.focus_handle);
20458            })
20459            .log_err();
20460    }
20461
20462    fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
20463        let settings = ThemeSettings::get_global(cx);
20464        let text_style = TextStyle {
20465            color: if self.prompt.read(cx).read_only(cx) {
20466                cx.theme().colors().text_disabled
20467            } else {
20468                cx.theme().colors().text
20469            },
20470            font_family: settings.buffer_font.family.clone(),
20471            font_fallbacks: settings.buffer_font.fallbacks.clone(),
20472            font_size: settings.buffer_font_size(cx).into(),
20473            font_weight: settings.buffer_font.weight,
20474            line_height: relative(settings.buffer_line_height.value()),
20475            ..Default::default()
20476        };
20477        EditorElement::new(
20478            &self.prompt,
20479            EditorStyle {
20480                background: cx.theme().colors().editor_background,
20481                local_player: cx.theme().players().local(),
20482                text: text_style,
20483                ..Default::default()
20484            },
20485        )
20486    }
20487}
20488
20489impl Render for BreakpointPromptEditor {
20490    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20491        let gutter_dimensions = *self.gutter_dimensions.lock();
20492        h_flex()
20493            .key_context("Editor")
20494            .bg(cx.theme().colors().editor_background)
20495            .border_y_1()
20496            .border_color(cx.theme().status().info_border)
20497            .size_full()
20498            .py(window.line_height() / 2.5)
20499            .on_action(cx.listener(Self::confirm))
20500            .on_action(cx.listener(Self::cancel))
20501            .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
20502            .child(div().flex_1().child(self.render_prompt_editor(cx)))
20503    }
20504}
20505
20506impl Focusable for BreakpointPromptEditor {
20507    fn focus_handle(&self, cx: &App) -> FocusHandle {
20508        self.prompt.focus_handle(cx)
20509    }
20510}
20511
20512fn all_edits_insertions_or_deletions(
20513    edits: &Vec<(Range<Anchor>, String)>,
20514    snapshot: &MultiBufferSnapshot,
20515) -> bool {
20516    let mut all_insertions = true;
20517    let mut all_deletions = true;
20518
20519    for (range, new_text) in edits.iter() {
20520        let range_is_empty = range.to_offset(&snapshot).is_empty();
20521        let text_is_empty = new_text.is_empty();
20522
20523        if range_is_empty != text_is_empty {
20524            if range_is_empty {
20525                all_deletions = false;
20526            } else {
20527                all_insertions = false;
20528            }
20529        } else {
20530            return false;
20531        }
20532
20533        if !all_insertions && !all_deletions {
20534            return false;
20535        }
20536    }
20537    all_insertions || all_deletions
20538}
20539
20540struct MissingEditPredictionKeybindingTooltip;
20541
20542impl Render for MissingEditPredictionKeybindingTooltip {
20543    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20544        ui::tooltip_container(window, cx, |container, _, cx| {
20545            container
20546                .flex_shrink_0()
20547                .max_w_80()
20548                .min_h(rems_from_px(124.))
20549                .justify_between()
20550                .child(
20551                    v_flex()
20552                        .flex_1()
20553                        .text_ui_sm(cx)
20554                        .child(Label::new("Conflict with Accept Keybinding"))
20555                        .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
20556                )
20557                .child(
20558                    h_flex()
20559                        .pb_1()
20560                        .gap_1()
20561                        .items_end()
20562                        .w_full()
20563                        .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
20564                            window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
20565                        }))
20566                        .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
20567                            cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
20568                        })),
20569                )
20570        })
20571    }
20572}
20573
20574#[derive(Debug, Clone, Copy, PartialEq)]
20575pub struct LineHighlight {
20576    pub background: Background,
20577    pub border: Option<gpui::Hsla>,
20578}
20579
20580impl From<Hsla> for LineHighlight {
20581    fn from(hsla: Hsla) -> Self {
20582        Self {
20583            background: hsla.into(),
20584            border: None,
20585        }
20586    }
20587}
20588
20589impl From<Background> for LineHighlight {
20590    fn from(background: Background) -> Self {
20591        Self {
20592            background,
20593            border: None,
20594        }
20595    }
20596}
20597
20598fn render_diff_hunk_controls(
20599    row: u32,
20600    status: &DiffHunkStatus,
20601    hunk_range: Range<Anchor>,
20602    is_created_file: bool,
20603    line_height: Pixels,
20604    editor: &Entity<Editor>,
20605    _window: &mut Window,
20606    cx: &mut App,
20607) -> AnyElement {
20608    h_flex()
20609        .h(line_height)
20610        .mr_1()
20611        .gap_1()
20612        .px_0p5()
20613        .pb_1()
20614        .border_x_1()
20615        .border_b_1()
20616        .border_color(cx.theme().colors().border_variant)
20617        .rounded_b_lg()
20618        .bg(cx.theme().colors().editor_background)
20619        .gap_1()
20620        .occlude()
20621        .shadow_md()
20622        .child(if status.has_secondary_hunk() {
20623            Button::new(("stage", row as u64), "Stage")
20624                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20625                .tooltip({
20626                    let focus_handle = editor.focus_handle(cx);
20627                    move |window, cx| {
20628                        Tooltip::for_action_in(
20629                            "Stage Hunk",
20630                            &::git::ToggleStaged,
20631                            &focus_handle,
20632                            window,
20633                            cx,
20634                        )
20635                    }
20636                })
20637                .on_click({
20638                    let editor = editor.clone();
20639                    move |_event, _window, cx| {
20640                        editor.update(cx, |editor, cx| {
20641                            editor.stage_or_unstage_diff_hunks(
20642                                true,
20643                                vec![hunk_range.start..hunk_range.start],
20644                                cx,
20645                            );
20646                        });
20647                    }
20648                })
20649        } else {
20650            Button::new(("unstage", row as u64), "Unstage")
20651                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20652                .tooltip({
20653                    let focus_handle = editor.focus_handle(cx);
20654                    move |window, cx| {
20655                        Tooltip::for_action_in(
20656                            "Unstage Hunk",
20657                            &::git::ToggleStaged,
20658                            &focus_handle,
20659                            window,
20660                            cx,
20661                        )
20662                    }
20663                })
20664                .on_click({
20665                    let editor = editor.clone();
20666                    move |_event, _window, cx| {
20667                        editor.update(cx, |editor, cx| {
20668                            editor.stage_or_unstage_diff_hunks(
20669                                false,
20670                                vec![hunk_range.start..hunk_range.start],
20671                                cx,
20672                            );
20673                        });
20674                    }
20675                })
20676        })
20677        .child(
20678            Button::new(("restore", row as u64), "Restore")
20679                .tooltip({
20680                    let focus_handle = editor.focus_handle(cx);
20681                    move |window, cx| {
20682                        Tooltip::for_action_in(
20683                            "Restore Hunk",
20684                            &::git::Restore,
20685                            &focus_handle,
20686                            window,
20687                            cx,
20688                        )
20689                    }
20690                })
20691                .on_click({
20692                    let editor = editor.clone();
20693                    move |_event, window, cx| {
20694                        editor.update(cx, |editor, cx| {
20695                            let snapshot = editor.snapshot(window, cx);
20696                            let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
20697                            editor.restore_hunks_in_ranges(vec![point..point], window, cx);
20698                        });
20699                    }
20700                })
20701                .disabled(is_created_file),
20702        )
20703        .when(
20704            !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
20705            |el| {
20706                el.child(
20707                    IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
20708                        .shape(IconButtonShape::Square)
20709                        .icon_size(IconSize::Small)
20710                        // .disabled(!has_multiple_hunks)
20711                        .tooltip({
20712                            let focus_handle = editor.focus_handle(cx);
20713                            move |window, cx| {
20714                                Tooltip::for_action_in(
20715                                    "Next Hunk",
20716                                    &GoToHunk,
20717                                    &focus_handle,
20718                                    window,
20719                                    cx,
20720                                )
20721                            }
20722                        })
20723                        .on_click({
20724                            let editor = editor.clone();
20725                            move |_event, window, cx| {
20726                                editor.update(cx, |editor, cx| {
20727                                    let snapshot = editor.snapshot(window, cx);
20728                                    let position =
20729                                        hunk_range.end.to_point(&snapshot.buffer_snapshot);
20730                                    editor.go_to_hunk_before_or_after_position(
20731                                        &snapshot,
20732                                        position,
20733                                        Direction::Next,
20734                                        window,
20735                                        cx,
20736                                    );
20737                                    editor.expand_selected_diff_hunks(cx);
20738                                });
20739                            }
20740                        }),
20741                )
20742                .child(
20743                    IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
20744                        .shape(IconButtonShape::Square)
20745                        .icon_size(IconSize::Small)
20746                        // .disabled(!has_multiple_hunks)
20747                        .tooltip({
20748                            let focus_handle = editor.focus_handle(cx);
20749                            move |window, cx| {
20750                                Tooltip::for_action_in(
20751                                    "Previous Hunk",
20752                                    &GoToPreviousHunk,
20753                                    &focus_handle,
20754                                    window,
20755                                    cx,
20756                                )
20757                            }
20758                        })
20759                        .on_click({
20760                            let editor = editor.clone();
20761                            move |_event, window, cx| {
20762                                editor.update(cx, |editor, cx| {
20763                                    let snapshot = editor.snapshot(window, cx);
20764                                    let point =
20765                                        hunk_range.start.to_point(&snapshot.buffer_snapshot);
20766                                    editor.go_to_hunk_before_or_after_position(
20767                                        &snapshot,
20768                                        point,
20769                                        Direction::Prev,
20770                                        window,
20771                                        cx,
20772                                    );
20773                                    editor.expand_selected_diff_hunks(cx);
20774                                });
20775                            }
20776                        }),
20777                )
20778            },
20779        )
20780        .into_any_element()
20781}