editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blink_manager;
   17mod clangd_ext;
   18mod code_context_menus;
   19pub mod commit_tooltip;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod indent_guides;
   29mod inlay_hint_cache;
   30pub mod items;
   31mod jsx_tag_auto_close;
   32mod linked_editing_ranges;
   33mod lsp_ext;
   34mod mouse_context_menu;
   35pub mod movement;
   36mod persistence;
   37mod proposed_changes_editor;
   38mod rust_analyzer_ext;
   39pub mod scroll;
   40mod selections_collection;
   41pub mod tasks;
   42
   43#[cfg(test)]
   44mod editor_tests;
   45#[cfg(test)]
   46mod inline_completion_tests;
   47mod signature_help;
   48#[cfg(any(test, feature = "test-support"))]
   49pub mod test;
   50
   51pub(crate) use actions::*;
   52pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   53use aho_corasick::AhoCorasick;
   54use anyhow::{anyhow, Context as _, Result};
   55use blink_manager::BlinkManager;
   56use buffer_diff::DiffHunkStatus;
   57use client::{Collaborator, ParticipantIndex};
   58use clock::ReplicaId;
   59use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   60use convert_case::{Case, Casing};
   61use display_map::*;
   62pub use display_map::{DisplayPoint, FoldPlaceholder};
   63pub use editor_settings::{
   64    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   65};
   66pub use editor_settings_controls::*;
   67use element::{layout_line, AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
   68pub use element::{
   69    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   70};
   71use feature_flags::{Debugger, FeatureFlagAppExt};
   72use futures::{
   73    future::{self, join, Shared},
   74    FutureExt,
   75};
   76use fuzzy::StringMatchCandidate;
   77
   78use ::git::Restore;
   79use code_context_menus::{
   80    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   81    CompletionsMenu, ContextMenuOrigin,
   82};
   83use git::blame::GitBlame;
   84use gpui::{
   85    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
   86    AnimationExt, AnyElement, App, AppContext, AsyncWindowContext, AvailableSpace, Background,
   87    Bounds, ClickEvent, ClipboardEntry, ClipboardItem, Context, DispatchPhase, Edges, Entity,
   88    EntityInputHandler, EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight,
   89    Global, HighlightStyle, Hsla, KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad,
   90    ParentElement, Pixels, Render, SharedString, Size, Stateful, Styled, StyledText, Subscription,
   91    Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
   92    WeakEntity, WeakFocusHandle, Window,
   93};
   94use highlight_matching_bracket::refresh_matching_bracket_highlights;
   95use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
   96use hover_popover::{hide_hover, HoverState};
   97use indent_guides::ActiveIndentGuidesState;
   98use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   99pub use inline_completion::Direction;
  100use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
  101pub use items::MAX_TAB_TITLE_LEN;
  102use itertools::Itertools;
  103use language::{
  104    language_settings::{
  105        self, all_language_settings, language_settings, InlayHintSettings, RewrapBehavior,
  106        WordsCompletionMode,
  107    },
  108    point_from_lsp, text_diff_with_options, AutoindentMode, BracketMatch, BracketPair, Buffer,
  109    Capability, CharKind, CodeLabel, CursorShape, Diagnostic, DiffOptions, EditPredictionsMode,
  110    EditPreview, HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point,
  111    Selection, SelectionGoal, TextObject, TransactionId, TreeSitterOptions, WordsQuery,
  112};
  113use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  114use linked_editing_ranges::refresh_linked_ranges;
  115use mouse_context_menu::MouseContextMenu;
  116use persistence::DB;
  117use project::{
  118    debugger::breakpoint_store::{BreakpointEditAction, BreakpointStore, BreakpointStoreEvent},
  119    ProjectPath,
  120};
  121
  122pub use proposed_changes_editor::{
  123    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  124};
  125use smallvec::smallvec;
  126use std::iter::Peekable;
  127use task::{ResolvedTask, TaskTemplate, TaskVariables};
  128
  129pub use lsp::CompletionContext;
  130use lsp::{
  131    CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
  132    InsertTextFormat, LanguageServerId, LanguageServerName,
  133};
  134
  135use language::BufferSnapshot;
  136use movement::TextLayoutDetails;
  137pub use multi_buffer::{
  138    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  139    ToOffset, ToPoint,
  140};
  141use multi_buffer::{
  142    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  143    MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
  144};
  145use parking_lot::Mutex;
  146use project::{
  147    debugger::breakpoint_store::{Breakpoint, BreakpointKind},
  148    lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  149    project_settings::{GitGutterSetting, ProjectSettings},
  150    CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
  151    Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
  152    TaskSourceKind,
  153};
  154use rand::prelude::*;
  155use rpc::{proto::*, ErrorExt};
  156use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  157use selections_collection::{
  158    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  159};
  160use serde::{Deserialize, Serialize};
  161use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  162use smallvec::SmallVec;
  163use snippet::Snippet;
  164use std::sync::Arc;
  165use std::{
  166    any::TypeId,
  167    borrow::Cow,
  168    cell::RefCell,
  169    cmp::{self, Ordering, Reverse},
  170    mem,
  171    num::NonZeroU32,
  172    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  173    path::{Path, PathBuf},
  174    rc::Rc,
  175    time::{Duration, Instant},
  176};
  177pub use sum_tree::Bias;
  178use sum_tree::TreeMap;
  179use text::{BufferId, OffsetUtf16, Rope};
  180use theme::{
  181    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  182    ThemeColors, ThemeSettings,
  183};
  184use ui::{
  185    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
  186    Tooltip,
  187};
  188use util::{maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  189use workspace::{
  190    item::{ItemHandle, PreviewTabsSettings},
  191    ItemId, RestoreOnStartupBehavior,
  192};
  193use workspace::{
  194    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  195    WorkspaceSettings,
  196};
  197use workspace::{
  198    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  199};
  200use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  201
  202use crate::hover_links::{find_url, find_url_from_range};
  203use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  204
  205pub const FILE_HEADER_HEIGHT: u32 = 2;
  206pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  207pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  208const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  209const MAX_LINE_LEN: usize = 1024;
  210const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  211const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  212pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  213#[doc(hidden)]
  214pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  215
  216pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
  217pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
  218pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  219
  220pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  221pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  222pub(crate) const MIN_LINE_NUMBER_DIGITS: u32 = 4;
  223
  224const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  225    alt: true,
  226    shift: true,
  227    control: false,
  228    platform: false,
  229    function: false,
  230};
  231
  232#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  233pub enum InlayId {
  234    InlineCompletion(usize),
  235    Hint(usize),
  236}
  237
  238impl InlayId {
  239    fn id(&self) -> usize {
  240        match self {
  241            Self::InlineCompletion(id) => *id,
  242            Self::Hint(id) => *id,
  243        }
  244    }
  245}
  246
  247pub enum DebugCurrentRowHighlight {}
  248enum DocumentHighlightRead {}
  249enum DocumentHighlightWrite {}
  250enum InputComposition {}
  251enum SelectedTextHighlight {}
  252
  253#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  254pub enum Navigated {
  255    Yes,
  256    No,
  257}
  258
  259impl Navigated {
  260    pub fn from_bool(yes: bool) -> Navigated {
  261        if yes {
  262            Navigated::Yes
  263        } else {
  264            Navigated::No
  265        }
  266    }
  267}
  268
  269#[derive(Debug, Clone, PartialEq, Eq)]
  270enum DisplayDiffHunk {
  271    Folded {
  272        display_row: DisplayRow,
  273    },
  274    Unfolded {
  275        is_created_file: bool,
  276        diff_base_byte_range: Range<usize>,
  277        display_row_range: Range<DisplayRow>,
  278        multi_buffer_range: Range<Anchor>,
  279        status: DiffHunkStatus,
  280    },
  281}
  282
  283pub fn init_settings(cx: &mut App) {
  284    EditorSettings::register(cx);
  285}
  286
  287pub fn init(cx: &mut App) {
  288    init_settings(cx);
  289
  290    workspace::register_project_item::<Editor>(cx);
  291    workspace::FollowableViewRegistry::register::<Editor>(cx);
  292    workspace::register_serializable_item::<Editor>(cx);
  293
  294    cx.observe_new(
  295        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  296            workspace.register_action(Editor::new_file);
  297            workspace.register_action(Editor::new_file_vertical);
  298            workspace.register_action(Editor::new_file_horizontal);
  299            workspace.register_action(Editor::cancel_language_server_work);
  300        },
  301    )
  302    .detach();
  303
  304    cx.on_action(move |_: &workspace::NewFile, cx| {
  305        let app_state = workspace::AppState::global(cx);
  306        if let Some(app_state) = app_state.upgrade() {
  307            workspace::open_new(
  308                Default::default(),
  309                app_state,
  310                cx,
  311                |workspace, window, cx| {
  312                    Editor::new_file(workspace, &Default::default(), window, cx)
  313                },
  314            )
  315            .detach();
  316        }
  317    });
  318    cx.on_action(move |_: &workspace::NewWindow, cx| {
  319        let app_state = workspace::AppState::global(cx);
  320        if let Some(app_state) = app_state.upgrade() {
  321            workspace::open_new(
  322                Default::default(),
  323                app_state,
  324                cx,
  325                |workspace, window, cx| {
  326                    cx.activate(true);
  327                    Editor::new_file(workspace, &Default::default(), window, cx)
  328                },
  329            )
  330            .detach();
  331        }
  332    });
  333}
  334
  335pub struct SearchWithinRange;
  336
  337trait InvalidationRegion {
  338    fn ranges(&self) -> &[Range<Anchor>];
  339}
  340
  341#[derive(Clone, Debug, PartialEq)]
  342pub enum SelectPhase {
  343    Begin {
  344        position: DisplayPoint,
  345        add: bool,
  346        click_count: usize,
  347    },
  348    BeginColumnar {
  349        position: DisplayPoint,
  350        reset: bool,
  351        goal_column: u32,
  352    },
  353    Extend {
  354        position: DisplayPoint,
  355        click_count: usize,
  356    },
  357    Update {
  358        position: DisplayPoint,
  359        goal_column: u32,
  360        scroll_delta: gpui::Point<f32>,
  361    },
  362    End,
  363}
  364
  365#[derive(Clone, Debug)]
  366pub enum SelectMode {
  367    Character,
  368    Word(Range<Anchor>),
  369    Line(Range<Anchor>),
  370    All,
  371}
  372
  373#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  374pub enum EditorMode {
  375    SingleLine { auto_width: bool },
  376    AutoHeight { max_lines: usize },
  377    Full,
  378}
  379
  380#[derive(Copy, Clone, Debug)]
  381pub enum SoftWrap {
  382    /// Prefer not to wrap at all.
  383    ///
  384    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  385    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  386    GitDiff,
  387    /// Prefer a single line generally, unless an overly long line is encountered.
  388    None,
  389    /// Soft wrap lines that exceed the editor width.
  390    EditorWidth,
  391    /// Soft wrap lines at the preferred line length.
  392    Column(u32),
  393    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  394    Bounded(u32),
  395}
  396
  397#[derive(Clone)]
  398pub struct EditorStyle {
  399    pub background: Hsla,
  400    pub local_player: PlayerColor,
  401    pub text: TextStyle,
  402    pub scrollbar_width: Pixels,
  403    pub syntax: Arc<SyntaxTheme>,
  404    pub status: StatusColors,
  405    pub inlay_hints_style: HighlightStyle,
  406    pub inline_completion_styles: InlineCompletionStyles,
  407    pub unnecessary_code_fade: f32,
  408}
  409
  410impl Default for EditorStyle {
  411    fn default() -> Self {
  412        Self {
  413            background: Hsla::default(),
  414            local_player: PlayerColor::default(),
  415            text: TextStyle::default(),
  416            scrollbar_width: Pixels::default(),
  417            syntax: Default::default(),
  418            // HACK: Status colors don't have a real default.
  419            // We should look into removing the status colors from the editor
  420            // style and retrieve them directly from the theme.
  421            status: StatusColors::dark(),
  422            inlay_hints_style: HighlightStyle::default(),
  423            inline_completion_styles: InlineCompletionStyles {
  424                insertion: HighlightStyle::default(),
  425                whitespace: HighlightStyle::default(),
  426            },
  427            unnecessary_code_fade: Default::default(),
  428        }
  429    }
  430}
  431
  432pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  433    let show_background = language_settings::language_settings(None, None, cx)
  434        .inlay_hints
  435        .show_background;
  436
  437    HighlightStyle {
  438        color: Some(cx.theme().status().hint),
  439        background_color: show_background.then(|| cx.theme().status().hint_background),
  440        ..HighlightStyle::default()
  441    }
  442}
  443
  444pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  445    InlineCompletionStyles {
  446        insertion: HighlightStyle {
  447            color: Some(cx.theme().status().predictive),
  448            ..HighlightStyle::default()
  449        },
  450        whitespace: HighlightStyle {
  451            background_color: Some(cx.theme().status().created_background),
  452            ..HighlightStyle::default()
  453        },
  454    }
  455}
  456
  457type CompletionId = usize;
  458
  459pub(crate) enum EditDisplayMode {
  460    TabAccept,
  461    DiffPopover,
  462    Inline,
  463}
  464
  465enum InlineCompletion {
  466    Edit {
  467        edits: Vec<(Range<Anchor>, String)>,
  468        edit_preview: Option<EditPreview>,
  469        display_mode: EditDisplayMode,
  470        snapshot: BufferSnapshot,
  471    },
  472    Move {
  473        target: Anchor,
  474        snapshot: BufferSnapshot,
  475    },
  476}
  477
  478struct InlineCompletionState {
  479    inlay_ids: Vec<InlayId>,
  480    completion: InlineCompletion,
  481    completion_id: Option<SharedString>,
  482    invalidation_range: Range<Anchor>,
  483}
  484
  485enum EditPredictionSettings {
  486    Disabled,
  487    Enabled {
  488        show_in_menu: bool,
  489        preview_requires_modifier: bool,
  490    },
  491}
  492
  493enum InlineCompletionHighlight {}
  494
  495#[derive(Debug, Clone)]
  496struct InlineDiagnostic {
  497    message: SharedString,
  498    group_id: usize,
  499    is_primary: bool,
  500    start: Point,
  501    severity: DiagnosticSeverity,
  502}
  503
  504pub enum MenuInlineCompletionsPolicy {
  505    Never,
  506    ByProvider,
  507}
  508
  509pub enum EditPredictionPreview {
  510    /// Modifier is not pressed
  511    Inactive { released_too_fast: bool },
  512    /// Modifier pressed
  513    Active {
  514        since: Instant,
  515        previous_scroll_position: Option<ScrollAnchor>,
  516    },
  517}
  518
  519impl EditPredictionPreview {
  520    pub fn released_too_fast(&self) -> bool {
  521        match self {
  522            EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
  523            EditPredictionPreview::Active { .. } => false,
  524        }
  525    }
  526
  527    pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
  528        if let EditPredictionPreview::Active {
  529            previous_scroll_position,
  530            ..
  531        } = self
  532        {
  533            *previous_scroll_position = scroll_position;
  534        }
  535    }
  536}
  537
  538#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  539struct EditorActionId(usize);
  540
  541impl EditorActionId {
  542    pub fn post_inc(&mut self) -> Self {
  543        let answer = self.0;
  544
  545        *self = Self(answer + 1);
  546
  547        Self(answer)
  548    }
  549}
  550
  551// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  552// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  553
  554type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  555type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  556
  557#[derive(Default)]
  558struct ScrollbarMarkerState {
  559    scrollbar_size: Size<Pixels>,
  560    dirty: bool,
  561    markers: Arc<[PaintQuad]>,
  562    pending_refresh: Option<Task<Result<()>>>,
  563}
  564
  565impl ScrollbarMarkerState {
  566    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  567        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  568    }
  569}
  570
  571#[derive(Clone, Debug)]
  572struct RunnableTasks {
  573    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  574    offset: multi_buffer::Anchor,
  575    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  576    column: u32,
  577    // Values of all named captures, including those starting with '_'
  578    extra_variables: HashMap<String, String>,
  579    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  580    context_range: Range<BufferOffset>,
  581}
  582
  583impl RunnableTasks {
  584    fn resolve<'a>(
  585        &'a self,
  586        cx: &'a task::TaskContext,
  587    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  588        self.templates.iter().filter_map(|(kind, template)| {
  589            template
  590                .resolve_task(&kind.to_id_base(), cx)
  591                .map(|task| (kind.clone(), task))
  592        })
  593    }
  594}
  595
  596#[derive(Clone)]
  597struct ResolvedTasks {
  598    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  599    position: Anchor,
  600}
  601
  602#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  603struct BufferOffset(usize);
  604
  605// Addons allow storing per-editor state in other crates (e.g. Vim)
  606pub trait Addon: 'static {
  607    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  608
  609    fn render_buffer_header_controls(
  610        &self,
  611        _: &ExcerptInfo,
  612        _: &Window,
  613        _: &App,
  614    ) -> Option<AnyElement> {
  615        None
  616    }
  617
  618    fn to_any(&self) -> &dyn std::any::Any;
  619}
  620
  621/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  622///
  623/// See the [module level documentation](self) for more information.
  624pub struct Editor {
  625    focus_handle: FocusHandle,
  626    last_focused_descendant: Option<WeakFocusHandle>,
  627    /// The text buffer being edited
  628    buffer: Entity<MultiBuffer>,
  629    /// Map of how text in the buffer should be displayed.
  630    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  631    pub display_map: Entity<DisplayMap>,
  632    pub selections: SelectionsCollection,
  633    pub scroll_manager: ScrollManager,
  634    /// When inline assist editors are linked, they all render cursors because
  635    /// typing enters text into each of them, even the ones that aren't focused.
  636    pub(crate) show_cursor_when_unfocused: bool,
  637    columnar_selection_tail: Option<Anchor>,
  638    add_selections_state: Option<AddSelectionsState>,
  639    select_next_state: Option<SelectNextState>,
  640    select_prev_state: Option<SelectNextState>,
  641    selection_history: SelectionHistory,
  642    autoclose_regions: Vec<AutocloseRegion>,
  643    snippet_stack: InvalidationStack<SnippetState>,
  644    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  645    ime_transaction: Option<TransactionId>,
  646    active_diagnostics: Option<ActiveDiagnosticGroup>,
  647    show_inline_diagnostics: bool,
  648    inline_diagnostics_update: Task<()>,
  649    inline_diagnostics_enabled: bool,
  650    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  651    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  652    hard_wrap: Option<usize>,
  653
  654    // TODO: make this a access method
  655    pub project: Option<Entity<Project>>,
  656    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  657    completion_provider: Option<Box<dyn CompletionProvider>>,
  658    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  659    blink_manager: Entity<BlinkManager>,
  660    show_cursor_names: bool,
  661    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  662    pub show_local_selections: bool,
  663    mode: EditorMode,
  664    show_breadcrumbs: bool,
  665    show_gutter: bool,
  666    show_scrollbars: bool,
  667    show_line_numbers: Option<bool>,
  668    use_relative_line_numbers: Option<bool>,
  669    show_git_diff_gutter: Option<bool>,
  670    show_code_actions: Option<bool>,
  671    show_runnables: Option<bool>,
  672    show_breakpoints: Option<bool>,
  673    show_wrap_guides: Option<bool>,
  674    show_indent_guides: Option<bool>,
  675    placeholder_text: Option<Arc<str>>,
  676    highlight_order: usize,
  677    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  678    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  679    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  680    scrollbar_marker_state: ScrollbarMarkerState,
  681    active_indent_guides_state: ActiveIndentGuidesState,
  682    nav_history: Option<ItemNavHistory>,
  683    context_menu: RefCell<Option<CodeContextMenu>>,
  684    mouse_context_menu: Option<MouseContextMenu>,
  685    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  686    signature_help_state: SignatureHelpState,
  687    auto_signature_help: Option<bool>,
  688    find_all_references_task_sources: Vec<Anchor>,
  689    next_completion_id: CompletionId,
  690    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  691    code_actions_task: Option<Task<Result<()>>>,
  692    selection_highlight_task: Option<Task<()>>,
  693    document_highlights_task: Option<Task<()>>,
  694    linked_editing_range_task: Option<Task<Option<()>>>,
  695    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  696    pending_rename: Option<RenameState>,
  697    searchable: bool,
  698    cursor_shape: CursorShape,
  699    current_line_highlight: Option<CurrentLineHighlight>,
  700    collapse_matches: bool,
  701    autoindent_mode: Option<AutoindentMode>,
  702    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  703    input_enabled: bool,
  704    use_modal_editing: bool,
  705    read_only: bool,
  706    leader_peer_id: Option<PeerId>,
  707    remote_id: Option<ViewId>,
  708    hover_state: HoverState,
  709    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  710    gutter_hovered: bool,
  711    hovered_link_state: Option<HoveredLinkState>,
  712    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  713    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  714    active_inline_completion: Option<InlineCompletionState>,
  715    /// Used to prevent flickering as the user types while the menu is open
  716    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  717    edit_prediction_settings: EditPredictionSettings,
  718    inline_completions_hidden_for_vim_mode: bool,
  719    show_inline_completions_override: Option<bool>,
  720    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  721    edit_prediction_preview: EditPredictionPreview,
  722    edit_prediction_indent_conflict: bool,
  723    edit_prediction_requires_modifier_in_indent_conflict: bool,
  724    inlay_hint_cache: InlayHintCache,
  725    next_inlay_id: usize,
  726    _subscriptions: Vec<Subscription>,
  727    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  728    gutter_dimensions: GutterDimensions,
  729    style: Option<EditorStyle>,
  730    text_style_refinement: Option<TextStyleRefinement>,
  731    next_editor_action_id: EditorActionId,
  732    editor_actions:
  733        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  734    use_autoclose: bool,
  735    use_auto_surround: bool,
  736    auto_replace_emoji_shortcode: bool,
  737    jsx_tag_auto_close_enabled_in_any_buffer: bool,
  738    show_git_blame_gutter: bool,
  739    show_git_blame_inline: bool,
  740    show_git_blame_inline_delay_task: Option<Task<()>>,
  741    git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
  742    git_blame_inline_enabled: bool,
  743    serialize_dirty_buffers: bool,
  744    show_selection_menu: Option<bool>,
  745    blame: Option<Entity<GitBlame>>,
  746    blame_subscription: Option<Subscription>,
  747    custom_context_menu: Option<
  748        Box<
  749            dyn 'static
  750                + Fn(
  751                    &mut Self,
  752                    DisplayPoint,
  753                    &mut Window,
  754                    &mut Context<Self>,
  755                ) -> Option<Entity<ui::ContextMenu>>,
  756        >,
  757    >,
  758    last_bounds: Option<Bounds<Pixels>>,
  759    last_position_map: Option<Rc<PositionMap>>,
  760    expect_bounds_change: Option<Bounds<Pixels>>,
  761    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  762    tasks_update_task: Option<Task<()>>,
  763    pub breakpoint_store: Option<Entity<BreakpointStore>>,
  764    /// Allow's a user to create a breakpoint by selecting this indicator
  765    /// It should be None while a user is not hovering over the gutter
  766    /// Otherwise it represents the point that the breakpoint will be shown
  767    pub gutter_breakpoint_indicator: Option<DisplayPoint>,
  768    in_project_search: bool,
  769    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  770    breadcrumb_header: Option<String>,
  771    focused_block: Option<FocusedBlock>,
  772    next_scroll_position: NextScrollCursorCenterTopBottom,
  773    addons: HashMap<TypeId, Box<dyn Addon>>,
  774    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  775    load_diff_task: Option<Shared<Task<()>>>,
  776    selection_mark_mode: bool,
  777    toggle_fold_multiple_buffers: Task<()>,
  778    _scroll_cursor_center_top_bottom_task: Task<()>,
  779    serialize_selections: Task<()>,
  780}
  781
  782#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  783enum NextScrollCursorCenterTopBottom {
  784    #[default]
  785    Center,
  786    Top,
  787    Bottom,
  788}
  789
  790impl NextScrollCursorCenterTopBottom {
  791    fn next(&self) -> Self {
  792        match self {
  793            Self::Center => Self::Top,
  794            Self::Top => Self::Bottom,
  795            Self::Bottom => Self::Center,
  796        }
  797    }
  798}
  799
  800#[derive(Clone)]
  801pub struct EditorSnapshot {
  802    pub mode: EditorMode,
  803    show_gutter: bool,
  804    show_line_numbers: Option<bool>,
  805    show_git_diff_gutter: Option<bool>,
  806    show_code_actions: Option<bool>,
  807    show_runnables: Option<bool>,
  808    show_breakpoints: Option<bool>,
  809    git_blame_gutter_max_author_length: Option<usize>,
  810    pub display_snapshot: DisplaySnapshot,
  811    pub placeholder_text: Option<Arc<str>>,
  812    is_focused: bool,
  813    scroll_anchor: ScrollAnchor,
  814    ongoing_scroll: OngoingScroll,
  815    current_line_highlight: CurrentLineHighlight,
  816    gutter_hovered: bool,
  817}
  818
  819const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  820
  821#[derive(Default, Debug, Clone, Copy)]
  822pub struct GutterDimensions {
  823    pub left_padding: Pixels,
  824    pub right_padding: Pixels,
  825    pub width: Pixels,
  826    pub margin: Pixels,
  827    pub git_blame_entries_width: Option<Pixels>,
  828}
  829
  830impl GutterDimensions {
  831    /// The full width of the space taken up by the gutter.
  832    pub fn full_width(&self) -> Pixels {
  833        self.margin + self.width
  834    }
  835
  836    /// The width of the space reserved for the fold indicators,
  837    /// use alongside 'justify_end' and `gutter_width` to
  838    /// right align content with the line numbers
  839    pub fn fold_area_width(&self) -> Pixels {
  840        self.margin + self.right_padding
  841    }
  842}
  843
  844#[derive(Debug)]
  845pub struct RemoteSelection {
  846    pub replica_id: ReplicaId,
  847    pub selection: Selection<Anchor>,
  848    pub cursor_shape: CursorShape,
  849    pub peer_id: PeerId,
  850    pub line_mode: bool,
  851    pub participant_index: Option<ParticipantIndex>,
  852    pub user_name: Option<SharedString>,
  853}
  854
  855#[derive(Clone, Debug)]
  856struct SelectionHistoryEntry {
  857    selections: Arc<[Selection<Anchor>]>,
  858    select_next_state: Option<SelectNextState>,
  859    select_prev_state: Option<SelectNextState>,
  860    add_selections_state: Option<AddSelectionsState>,
  861}
  862
  863enum SelectionHistoryMode {
  864    Normal,
  865    Undoing,
  866    Redoing,
  867}
  868
  869#[derive(Clone, PartialEq, Eq, Hash)]
  870struct HoveredCursor {
  871    replica_id: u16,
  872    selection_id: usize,
  873}
  874
  875impl Default for SelectionHistoryMode {
  876    fn default() -> Self {
  877        Self::Normal
  878    }
  879}
  880
  881#[derive(Default)]
  882struct SelectionHistory {
  883    #[allow(clippy::type_complexity)]
  884    selections_by_transaction:
  885        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  886    mode: SelectionHistoryMode,
  887    undo_stack: VecDeque<SelectionHistoryEntry>,
  888    redo_stack: VecDeque<SelectionHistoryEntry>,
  889}
  890
  891impl SelectionHistory {
  892    fn insert_transaction(
  893        &mut self,
  894        transaction_id: TransactionId,
  895        selections: Arc<[Selection<Anchor>]>,
  896    ) {
  897        self.selections_by_transaction
  898            .insert(transaction_id, (selections, None));
  899    }
  900
  901    #[allow(clippy::type_complexity)]
  902    fn transaction(
  903        &self,
  904        transaction_id: TransactionId,
  905    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  906        self.selections_by_transaction.get(&transaction_id)
  907    }
  908
  909    #[allow(clippy::type_complexity)]
  910    fn transaction_mut(
  911        &mut self,
  912        transaction_id: TransactionId,
  913    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  914        self.selections_by_transaction.get_mut(&transaction_id)
  915    }
  916
  917    fn push(&mut self, entry: SelectionHistoryEntry) {
  918        if !entry.selections.is_empty() {
  919            match self.mode {
  920                SelectionHistoryMode::Normal => {
  921                    self.push_undo(entry);
  922                    self.redo_stack.clear();
  923                }
  924                SelectionHistoryMode::Undoing => self.push_redo(entry),
  925                SelectionHistoryMode::Redoing => self.push_undo(entry),
  926            }
  927        }
  928    }
  929
  930    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  931        if self
  932            .undo_stack
  933            .back()
  934            .map_or(true, |e| e.selections != entry.selections)
  935        {
  936            self.undo_stack.push_back(entry);
  937            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  938                self.undo_stack.pop_front();
  939            }
  940        }
  941    }
  942
  943    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  944        if self
  945            .redo_stack
  946            .back()
  947            .map_or(true, |e| e.selections != entry.selections)
  948        {
  949            self.redo_stack.push_back(entry);
  950            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  951                self.redo_stack.pop_front();
  952            }
  953        }
  954    }
  955}
  956
  957struct RowHighlight {
  958    index: usize,
  959    range: Range<Anchor>,
  960    color: Hsla,
  961    should_autoscroll: bool,
  962}
  963
  964#[derive(Clone, Debug)]
  965struct AddSelectionsState {
  966    above: bool,
  967    stack: Vec<usize>,
  968}
  969
  970#[derive(Clone)]
  971struct SelectNextState {
  972    query: AhoCorasick,
  973    wordwise: bool,
  974    done: bool,
  975}
  976
  977impl std::fmt::Debug for SelectNextState {
  978    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  979        f.debug_struct(std::any::type_name::<Self>())
  980            .field("wordwise", &self.wordwise)
  981            .field("done", &self.done)
  982            .finish()
  983    }
  984}
  985
  986#[derive(Debug)]
  987struct AutocloseRegion {
  988    selection_id: usize,
  989    range: Range<Anchor>,
  990    pair: BracketPair,
  991}
  992
  993#[derive(Debug)]
  994struct SnippetState {
  995    ranges: Vec<Vec<Range<Anchor>>>,
  996    active_index: usize,
  997    choices: Vec<Option<Vec<String>>>,
  998}
  999
 1000#[doc(hidden)]
 1001pub struct RenameState {
 1002    pub range: Range<Anchor>,
 1003    pub old_name: Arc<str>,
 1004    pub editor: Entity<Editor>,
 1005    block_id: CustomBlockId,
 1006}
 1007
 1008struct InvalidationStack<T>(Vec<T>);
 1009
 1010struct RegisteredInlineCompletionProvider {
 1011    provider: Arc<dyn InlineCompletionProviderHandle>,
 1012    _subscription: Subscription,
 1013}
 1014
 1015#[derive(Debug, PartialEq, Eq)]
 1016struct ActiveDiagnosticGroup {
 1017    primary_range: Range<Anchor>,
 1018    primary_message: String,
 1019    group_id: usize,
 1020    blocks: HashMap<CustomBlockId, Diagnostic>,
 1021    is_valid: bool,
 1022}
 1023
 1024#[derive(Serialize, Deserialize, Clone, Debug)]
 1025pub struct ClipboardSelection {
 1026    /// The number of bytes in this selection.
 1027    pub len: usize,
 1028    /// Whether this was a full-line selection.
 1029    pub is_entire_line: bool,
 1030    /// The indentation of the first line when this content was originally copied.
 1031    pub first_line_indent: u32,
 1032}
 1033
 1034#[derive(Debug)]
 1035pub(crate) struct NavigationData {
 1036    cursor_anchor: Anchor,
 1037    cursor_position: Point,
 1038    scroll_anchor: ScrollAnchor,
 1039    scroll_top_row: u32,
 1040}
 1041
 1042#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1043pub enum GotoDefinitionKind {
 1044    Symbol,
 1045    Declaration,
 1046    Type,
 1047    Implementation,
 1048}
 1049
 1050#[derive(Debug, Clone)]
 1051enum InlayHintRefreshReason {
 1052    ModifiersChanged(bool),
 1053    Toggle(bool),
 1054    SettingsChange(InlayHintSettings),
 1055    NewLinesShown,
 1056    BufferEdited(HashSet<Arc<Language>>),
 1057    RefreshRequested,
 1058    ExcerptsRemoved(Vec<ExcerptId>),
 1059}
 1060
 1061impl InlayHintRefreshReason {
 1062    fn description(&self) -> &'static str {
 1063        match self {
 1064            Self::ModifiersChanged(_) => "modifiers changed",
 1065            Self::Toggle(_) => "toggle",
 1066            Self::SettingsChange(_) => "settings change",
 1067            Self::NewLinesShown => "new lines shown",
 1068            Self::BufferEdited(_) => "buffer edited",
 1069            Self::RefreshRequested => "refresh requested",
 1070            Self::ExcerptsRemoved(_) => "excerpts removed",
 1071        }
 1072    }
 1073}
 1074
 1075pub enum FormatTarget {
 1076    Buffers,
 1077    Ranges(Vec<Range<MultiBufferPoint>>),
 1078}
 1079
 1080pub(crate) struct FocusedBlock {
 1081    id: BlockId,
 1082    focus_handle: WeakFocusHandle,
 1083}
 1084
 1085#[derive(Clone)]
 1086enum JumpData {
 1087    MultiBufferRow {
 1088        row: MultiBufferRow,
 1089        line_offset_from_top: u32,
 1090    },
 1091    MultiBufferPoint {
 1092        excerpt_id: ExcerptId,
 1093        position: Point,
 1094        anchor: text::Anchor,
 1095        line_offset_from_top: u32,
 1096    },
 1097}
 1098
 1099pub enum MultibufferSelectionMode {
 1100    First,
 1101    All,
 1102}
 1103
 1104#[derive(Clone, Copy, Debug, Default)]
 1105pub struct RewrapOptions {
 1106    pub override_language_settings: bool,
 1107    pub preserve_existing_whitespace: bool,
 1108}
 1109
 1110impl Editor {
 1111    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1112        let buffer = cx.new(|cx| Buffer::local("", cx));
 1113        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1114        Self::new(
 1115            EditorMode::SingleLine { auto_width: false },
 1116            buffer,
 1117            None,
 1118            window,
 1119            cx,
 1120        )
 1121    }
 1122
 1123    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1124        let buffer = cx.new(|cx| Buffer::local("", cx));
 1125        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1126        Self::new(EditorMode::Full, buffer, None, window, cx)
 1127    }
 1128
 1129    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1130        let buffer = cx.new(|cx| Buffer::local("", cx));
 1131        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1132        Self::new(
 1133            EditorMode::SingleLine { auto_width: true },
 1134            buffer,
 1135            None,
 1136            window,
 1137            cx,
 1138        )
 1139    }
 1140
 1141    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1142        let buffer = cx.new(|cx| Buffer::local("", cx));
 1143        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1144        Self::new(
 1145            EditorMode::AutoHeight { max_lines },
 1146            buffer,
 1147            None,
 1148            window,
 1149            cx,
 1150        )
 1151    }
 1152
 1153    pub fn for_buffer(
 1154        buffer: Entity<Buffer>,
 1155        project: Option<Entity<Project>>,
 1156        window: &mut Window,
 1157        cx: &mut Context<Self>,
 1158    ) -> Self {
 1159        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1160        Self::new(EditorMode::Full, buffer, project, window, cx)
 1161    }
 1162
 1163    pub fn for_multibuffer(
 1164        buffer: Entity<MultiBuffer>,
 1165        project: Option<Entity<Project>>,
 1166        window: &mut Window,
 1167        cx: &mut Context<Self>,
 1168    ) -> Self {
 1169        Self::new(EditorMode::Full, buffer, project, window, cx)
 1170    }
 1171
 1172    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1173        let mut clone = Self::new(
 1174            self.mode,
 1175            self.buffer.clone(),
 1176            self.project.clone(),
 1177            window,
 1178            cx,
 1179        );
 1180        self.display_map.update(cx, |display_map, cx| {
 1181            let snapshot = display_map.snapshot(cx);
 1182            clone.display_map.update(cx, |display_map, cx| {
 1183                display_map.set_state(&snapshot, cx);
 1184            });
 1185        });
 1186        clone.selections.clone_state(&self.selections);
 1187        clone.scroll_manager.clone_state(&self.scroll_manager);
 1188        clone.searchable = self.searchable;
 1189        clone
 1190    }
 1191
 1192    pub fn new(
 1193        mode: EditorMode,
 1194        buffer: Entity<MultiBuffer>,
 1195        project: Option<Entity<Project>>,
 1196        window: &mut Window,
 1197        cx: &mut Context<Self>,
 1198    ) -> Self {
 1199        let style = window.text_style();
 1200        let font_size = style.font_size.to_pixels(window.rem_size());
 1201        let editor = cx.entity().downgrade();
 1202        let fold_placeholder = FoldPlaceholder {
 1203            constrain_width: true,
 1204            render: Arc::new(move |fold_id, fold_range, cx| {
 1205                let editor = editor.clone();
 1206                div()
 1207                    .id(fold_id)
 1208                    .bg(cx.theme().colors().ghost_element_background)
 1209                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1210                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1211                    .rounded_xs()
 1212                    .size_full()
 1213                    .cursor_pointer()
 1214                    .child("")
 1215                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1216                    .on_click(move |_, _window, cx| {
 1217                        editor
 1218                            .update(cx, |editor, cx| {
 1219                                editor.unfold_ranges(
 1220                                    &[fold_range.start..fold_range.end],
 1221                                    true,
 1222                                    false,
 1223                                    cx,
 1224                                );
 1225                                cx.stop_propagation();
 1226                            })
 1227                            .ok();
 1228                    })
 1229                    .into_any()
 1230            }),
 1231            merge_adjacent: true,
 1232            ..Default::default()
 1233        };
 1234        let display_map = cx.new(|cx| {
 1235            DisplayMap::new(
 1236                buffer.clone(),
 1237                style.font(),
 1238                font_size,
 1239                None,
 1240                FILE_HEADER_HEIGHT,
 1241                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1242                fold_placeholder,
 1243                cx,
 1244            )
 1245        });
 1246
 1247        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1248
 1249        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1250
 1251        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1252            .then(|| language_settings::SoftWrap::None);
 1253
 1254        let mut project_subscriptions = Vec::new();
 1255        if mode == EditorMode::Full {
 1256            if let Some(project) = project.as_ref() {
 1257                project_subscriptions.push(cx.subscribe_in(
 1258                    project,
 1259                    window,
 1260                    |editor, _, event, window, cx| match event {
 1261                        project::Event::RefreshCodeLens => {
 1262                            // we always query lens with actions, without storing them, always refreshing them
 1263                        }
 1264                        project::Event::RefreshInlayHints => {
 1265                            editor
 1266                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1267                        }
 1268                        project::Event::SnippetEdit(id, snippet_edits) => {
 1269                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1270                                let focus_handle = editor.focus_handle(cx);
 1271                                if focus_handle.is_focused(window) {
 1272                                    let snapshot = buffer.read(cx).snapshot();
 1273                                    for (range, snippet) in snippet_edits {
 1274                                        let editor_range =
 1275                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1276                                        editor
 1277                                            .insert_snippet(
 1278                                                &[editor_range],
 1279                                                snippet.clone(),
 1280                                                window,
 1281                                                cx,
 1282                                            )
 1283                                            .ok();
 1284                                    }
 1285                                }
 1286                            }
 1287                        }
 1288                        _ => {}
 1289                    },
 1290                ));
 1291                if let Some(task_inventory) = project
 1292                    .read(cx)
 1293                    .task_store()
 1294                    .read(cx)
 1295                    .task_inventory()
 1296                    .cloned()
 1297                {
 1298                    project_subscriptions.push(cx.observe_in(
 1299                        &task_inventory,
 1300                        window,
 1301                        |editor, _, window, cx| {
 1302                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1303                        },
 1304                    ));
 1305                };
 1306
 1307                project_subscriptions.push(cx.subscribe_in(
 1308                    &project.read(cx).breakpoint_store(),
 1309                    window,
 1310                    |editor, _, event, window, cx| match event {
 1311                        BreakpointStoreEvent::ActiveDebugLineChanged => {
 1312                            editor.go_to_active_debug_line(window, cx);
 1313                        }
 1314                        _ => {}
 1315                    },
 1316                ));
 1317            }
 1318        }
 1319
 1320        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1321
 1322        let inlay_hint_settings =
 1323            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1324        let focus_handle = cx.focus_handle();
 1325        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1326            .detach();
 1327        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1328            .detach();
 1329        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1330            .detach();
 1331        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1332            .detach();
 1333
 1334        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1335            Some(false)
 1336        } else {
 1337            None
 1338        };
 1339
 1340        let breakpoint_store = match (mode, project.as_ref()) {
 1341            (EditorMode::Full, Some(project)) => Some(project.read(cx).breakpoint_store()),
 1342            _ => None,
 1343        };
 1344
 1345        let mut code_action_providers = Vec::new();
 1346        let mut load_uncommitted_diff = None;
 1347        if let Some(project) = project.clone() {
 1348            load_uncommitted_diff = Some(
 1349                get_uncommitted_diff_for_buffer(
 1350                    &project,
 1351                    buffer.read(cx).all_buffers(),
 1352                    buffer.clone(),
 1353                    cx,
 1354                )
 1355                .shared(),
 1356            );
 1357            code_action_providers.push(Rc::new(project) as Rc<_>);
 1358        }
 1359
 1360        let mut this = Self {
 1361            focus_handle,
 1362            show_cursor_when_unfocused: false,
 1363            last_focused_descendant: None,
 1364            buffer: buffer.clone(),
 1365            display_map: display_map.clone(),
 1366            selections,
 1367            scroll_manager: ScrollManager::new(cx),
 1368            columnar_selection_tail: None,
 1369            add_selections_state: None,
 1370            select_next_state: None,
 1371            select_prev_state: None,
 1372            selection_history: Default::default(),
 1373            autoclose_regions: Default::default(),
 1374            snippet_stack: Default::default(),
 1375            select_larger_syntax_node_stack: Vec::new(),
 1376            ime_transaction: Default::default(),
 1377            active_diagnostics: None,
 1378            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1379            inline_diagnostics_update: Task::ready(()),
 1380            inline_diagnostics: Vec::new(),
 1381            soft_wrap_mode_override,
 1382            hard_wrap: None,
 1383            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1384            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1385            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1386            project,
 1387            blink_manager: blink_manager.clone(),
 1388            show_local_selections: true,
 1389            show_scrollbars: true,
 1390            mode,
 1391            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1392            show_gutter: mode == EditorMode::Full,
 1393            show_line_numbers: None,
 1394            use_relative_line_numbers: None,
 1395            show_git_diff_gutter: None,
 1396            show_code_actions: None,
 1397            show_runnables: None,
 1398            show_breakpoints: None,
 1399            show_wrap_guides: None,
 1400            show_indent_guides,
 1401            placeholder_text: None,
 1402            highlight_order: 0,
 1403            highlighted_rows: HashMap::default(),
 1404            background_highlights: Default::default(),
 1405            gutter_highlights: TreeMap::default(),
 1406            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1407            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1408            nav_history: None,
 1409            context_menu: RefCell::new(None),
 1410            mouse_context_menu: None,
 1411            completion_tasks: Default::default(),
 1412            signature_help_state: SignatureHelpState::default(),
 1413            auto_signature_help: None,
 1414            find_all_references_task_sources: Vec::new(),
 1415            next_completion_id: 0,
 1416            next_inlay_id: 0,
 1417            code_action_providers,
 1418            available_code_actions: Default::default(),
 1419            code_actions_task: Default::default(),
 1420            selection_highlight_task: Default::default(),
 1421            document_highlights_task: Default::default(),
 1422            linked_editing_range_task: Default::default(),
 1423            pending_rename: Default::default(),
 1424            searchable: true,
 1425            cursor_shape: EditorSettings::get_global(cx)
 1426                .cursor_shape
 1427                .unwrap_or_default(),
 1428            current_line_highlight: None,
 1429            autoindent_mode: Some(AutoindentMode::EachLine),
 1430            collapse_matches: false,
 1431            workspace: None,
 1432            input_enabled: true,
 1433            use_modal_editing: mode == EditorMode::Full,
 1434            read_only: false,
 1435            use_autoclose: true,
 1436            use_auto_surround: true,
 1437            auto_replace_emoji_shortcode: false,
 1438            jsx_tag_auto_close_enabled_in_any_buffer: false,
 1439            leader_peer_id: None,
 1440            remote_id: None,
 1441            hover_state: Default::default(),
 1442            pending_mouse_down: None,
 1443            hovered_link_state: Default::default(),
 1444            edit_prediction_provider: None,
 1445            active_inline_completion: None,
 1446            stale_inline_completion_in_menu: None,
 1447            edit_prediction_preview: EditPredictionPreview::Inactive {
 1448                released_too_fast: false,
 1449            },
 1450            inline_diagnostics_enabled: mode == EditorMode::Full,
 1451            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1452
 1453            gutter_hovered: false,
 1454            pixel_position_of_newest_cursor: None,
 1455            last_bounds: None,
 1456            last_position_map: None,
 1457            expect_bounds_change: None,
 1458            gutter_dimensions: GutterDimensions::default(),
 1459            style: None,
 1460            show_cursor_names: false,
 1461            hovered_cursors: Default::default(),
 1462            next_editor_action_id: EditorActionId::default(),
 1463            editor_actions: Rc::default(),
 1464            inline_completions_hidden_for_vim_mode: false,
 1465            show_inline_completions_override: None,
 1466            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1467            edit_prediction_settings: EditPredictionSettings::Disabled,
 1468            edit_prediction_indent_conflict: false,
 1469            edit_prediction_requires_modifier_in_indent_conflict: true,
 1470            custom_context_menu: None,
 1471            show_git_blame_gutter: false,
 1472            show_git_blame_inline: false,
 1473            show_selection_menu: None,
 1474            show_git_blame_inline_delay_task: None,
 1475            git_blame_inline_tooltip: None,
 1476            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1477            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1478                .session
 1479                .restore_unsaved_buffers,
 1480            blame: None,
 1481            blame_subscription: None,
 1482            tasks: Default::default(),
 1483
 1484            breakpoint_store,
 1485            gutter_breakpoint_indicator: None,
 1486            _subscriptions: vec![
 1487                cx.observe(&buffer, Self::on_buffer_changed),
 1488                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1489                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1490                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1491                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1492                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1493                cx.observe_window_activation(window, |editor, window, cx| {
 1494                    let active = window.is_window_active();
 1495                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1496                        if active {
 1497                            blink_manager.enable(cx);
 1498                        } else {
 1499                            blink_manager.disable(cx);
 1500                        }
 1501                    });
 1502                }),
 1503            ],
 1504            tasks_update_task: None,
 1505            linked_edit_ranges: Default::default(),
 1506            in_project_search: false,
 1507            previous_search_ranges: None,
 1508            breadcrumb_header: None,
 1509            focused_block: None,
 1510            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1511            addons: HashMap::default(),
 1512            registered_buffers: HashMap::default(),
 1513            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1514            selection_mark_mode: false,
 1515            toggle_fold_multiple_buffers: Task::ready(()),
 1516            serialize_selections: Task::ready(()),
 1517            text_style_refinement: None,
 1518            load_diff_task: load_uncommitted_diff,
 1519        };
 1520        if let Some(breakpoints) = this.breakpoint_store.as_ref() {
 1521            this._subscriptions
 1522                .push(cx.observe(breakpoints, |_, _, cx| {
 1523                    cx.notify();
 1524                }));
 1525        }
 1526        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1527        this._subscriptions.extend(project_subscriptions);
 1528
 1529        this.end_selection(window, cx);
 1530        this.scroll_manager.show_scrollbar(window, cx);
 1531        jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
 1532
 1533        if mode == EditorMode::Full {
 1534            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1535            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1536
 1537            if this.git_blame_inline_enabled {
 1538                this.git_blame_inline_enabled = true;
 1539                this.start_git_blame_inline(false, window, cx);
 1540            }
 1541
 1542            this.go_to_active_debug_line(window, cx);
 1543
 1544            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1545                if let Some(project) = this.project.as_ref() {
 1546                    let handle = project.update(cx, |project, cx| {
 1547                        project.register_buffer_with_language_servers(&buffer, cx)
 1548                    });
 1549                    this.registered_buffers
 1550                        .insert(buffer.read(cx).remote_id(), handle);
 1551                }
 1552            }
 1553        }
 1554
 1555        this.report_editor_event("Editor Opened", None, cx);
 1556        this
 1557    }
 1558
 1559    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1560        self.mouse_context_menu
 1561            .as_ref()
 1562            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1563    }
 1564
 1565    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1566        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1567    }
 1568
 1569    fn key_context_internal(
 1570        &self,
 1571        has_active_edit_prediction: bool,
 1572        window: &Window,
 1573        cx: &App,
 1574    ) -> KeyContext {
 1575        let mut key_context = KeyContext::new_with_defaults();
 1576        key_context.add("Editor");
 1577        let mode = match self.mode {
 1578            EditorMode::SingleLine { .. } => "single_line",
 1579            EditorMode::AutoHeight { .. } => "auto_height",
 1580            EditorMode::Full => "full",
 1581        };
 1582
 1583        if EditorSettings::jupyter_enabled(cx) {
 1584            key_context.add("jupyter");
 1585        }
 1586
 1587        key_context.set("mode", mode);
 1588        if self.pending_rename.is_some() {
 1589            key_context.add("renaming");
 1590        }
 1591
 1592        match self.context_menu.borrow().as_ref() {
 1593            Some(CodeContextMenu::Completions(_)) => {
 1594                key_context.add("menu");
 1595                key_context.add("showing_completions");
 1596            }
 1597            Some(CodeContextMenu::CodeActions(_)) => {
 1598                key_context.add("menu");
 1599                key_context.add("showing_code_actions")
 1600            }
 1601            None => {}
 1602        }
 1603
 1604        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1605        if !self.focus_handle(cx).contains_focused(window, cx)
 1606            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1607        {
 1608            for addon in self.addons.values() {
 1609                addon.extend_key_context(&mut key_context, cx)
 1610            }
 1611        }
 1612
 1613        if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
 1614            if let Some(extension) = singleton_buffer
 1615                .read(cx)
 1616                .file()
 1617                .and_then(|file| file.path().extension()?.to_str())
 1618            {
 1619                key_context.set("extension", extension.to_string());
 1620            }
 1621        } else {
 1622            key_context.add("multibuffer");
 1623        }
 1624
 1625        if has_active_edit_prediction {
 1626            if self.edit_prediction_in_conflict() {
 1627                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1628            } else {
 1629                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1630                key_context.add("copilot_suggestion");
 1631            }
 1632        }
 1633
 1634        if self.selection_mark_mode {
 1635            key_context.add("selection_mode");
 1636        }
 1637
 1638        key_context
 1639    }
 1640
 1641    pub fn edit_prediction_in_conflict(&self) -> bool {
 1642        if !self.show_edit_predictions_in_menu() {
 1643            return false;
 1644        }
 1645
 1646        let showing_completions = self
 1647            .context_menu
 1648            .borrow()
 1649            .as_ref()
 1650            .map_or(false, |context| {
 1651                matches!(context, CodeContextMenu::Completions(_))
 1652            });
 1653
 1654        showing_completions
 1655            || self.edit_prediction_requires_modifier()
 1656            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1657            // bindings to insert tab characters.
 1658            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 1659    }
 1660
 1661    pub fn accept_edit_prediction_keybind(
 1662        &self,
 1663        window: &Window,
 1664        cx: &App,
 1665    ) -> AcceptEditPredictionBinding {
 1666        let key_context = self.key_context_internal(true, window, cx);
 1667        let in_conflict = self.edit_prediction_in_conflict();
 1668
 1669        AcceptEditPredictionBinding(
 1670            window
 1671                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1672                .into_iter()
 1673                .filter(|binding| {
 1674                    !in_conflict
 1675                        || binding
 1676                            .keystrokes()
 1677                            .first()
 1678                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1679                })
 1680                .rev()
 1681                .min_by_key(|binding| {
 1682                    binding
 1683                        .keystrokes()
 1684                        .first()
 1685                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1686                }),
 1687        )
 1688    }
 1689
 1690    pub fn new_file(
 1691        workspace: &mut Workspace,
 1692        _: &workspace::NewFile,
 1693        window: &mut Window,
 1694        cx: &mut Context<Workspace>,
 1695    ) {
 1696        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1697            "Failed to create buffer",
 1698            window,
 1699            cx,
 1700            |e, _, _| match e.error_code() {
 1701                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1702                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1703                e.error_tag("required").unwrap_or("the latest version")
 1704            )),
 1705                _ => None,
 1706            },
 1707        );
 1708    }
 1709
 1710    pub fn new_in_workspace(
 1711        workspace: &mut Workspace,
 1712        window: &mut Window,
 1713        cx: &mut Context<Workspace>,
 1714    ) -> Task<Result<Entity<Editor>>> {
 1715        let project = workspace.project().clone();
 1716        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1717
 1718        cx.spawn_in(window, async move |workspace, cx| {
 1719            let buffer = create.await?;
 1720            workspace.update_in(cx, |workspace, window, cx| {
 1721                let editor =
 1722                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1723                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1724                editor
 1725            })
 1726        })
 1727    }
 1728
 1729    fn new_file_vertical(
 1730        workspace: &mut Workspace,
 1731        _: &workspace::NewFileSplitVertical,
 1732        window: &mut Window,
 1733        cx: &mut Context<Workspace>,
 1734    ) {
 1735        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1736    }
 1737
 1738    fn new_file_horizontal(
 1739        workspace: &mut Workspace,
 1740        _: &workspace::NewFileSplitHorizontal,
 1741        window: &mut Window,
 1742        cx: &mut Context<Workspace>,
 1743    ) {
 1744        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1745    }
 1746
 1747    fn new_file_in_direction(
 1748        workspace: &mut Workspace,
 1749        direction: SplitDirection,
 1750        window: &mut Window,
 1751        cx: &mut Context<Workspace>,
 1752    ) {
 1753        let project = workspace.project().clone();
 1754        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1755
 1756        cx.spawn_in(window, async move |workspace, cx| {
 1757            let buffer = create.await?;
 1758            workspace.update_in(cx, move |workspace, window, cx| {
 1759                workspace.split_item(
 1760                    direction,
 1761                    Box::new(
 1762                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1763                    ),
 1764                    window,
 1765                    cx,
 1766                )
 1767            })?;
 1768            anyhow::Ok(())
 1769        })
 1770        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1771            match e.error_code() {
 1772                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1773                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1774                e.error_tag("required").unwrap_or("the latest version")
 1775            )),
 1776                _ => None,
 1777            }
 1778        });
 1779    }
 1780
 1781    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1782        self.leader_peer_id
 1783    }
 1784
 1785    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1786        &self.buffer
 1787    }
 1788
 1789    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1790        self.workspace.as_ref()?.0.upgrade()
 1791    }
 1792
 1793    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1794        self.buffer().read(cx).title(cx)
 1795    }
 1796
 1797    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1798        let git_blame_gutter_max_author_length = self
 1799            .render_git_blame_gutter(cx)
 1800            .then(|| {
 1801                if let Some(blame) = self.blame.as_ref() {
 1802                    let max_author_length =
 1803                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1804                    Some(max_author_length)
 1805                } else {
 1806                    None
 1807                }
 1808            })
 1809            .flatten();
 1810
 1811        EditorSnapshot {
 1812            mode: self.mode,
 1813            show_gutter: self.show_gutter,
 1814            show_line_numbers: self.show_line_numbers,
 1815            show_git_diff_gutter: self.show_git_diff_gutter,
 1816            show_code_actions: self.show_code_actions,
 1817            show_runnables: self.show_runnables,
 1818            show_breakpoints: self.show_breakpoints,
 1819            git_blame_gutter_max_author_length,
 1820            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1821            scroll_anchor: self.scroll_manager.anchor(),
 1822            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1823            placeholder_text: self.placeholder_text.clone(),
 1824            is_focused: self.focus_handle.is_focused(window),
 1825            current_line_highlight: self
 1826                .current_line_highlight
 1827                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1828            gutter_hovered: self.gutter_hovered,
 1829        }
 1830    }
 1831
 1832    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1833        self.buffer.read(cx).language_at(point, cx)
 1834    }
 1835
 1836    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1837        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1838    }
 1839
 1840    pub fn active_excerpt(
 1841        &self,
 1842        cx: &App,
 1843    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1844        self.buffer
 1845            .read(cx)
 1846            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1847    }
 1848
 1849    pub fn mode(&self) -> EditorMode {
 1850        self.mode
 1851    }
 1852
 1853    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1854        self.collaboration_hub.as_deref()
 1855    }
 1856
 1857    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1858        self.collaboration_hub = Some(hub);
 1859    }
 1860
 1861    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1862        self.in_project_search = in_project_search;
 1863    }
 1864
 1865    pub fn set_custom_context_menu(
 1866        &mut self,
 1867        f: impl 'static
 1868            + Fn(
 1869                &mut Self,
 1870                DisplayPoint,
 1871                &mut Window,
 1872                &mut Context<Self>,
 1873            ) -> Option<Entity<ui::ContextMenu>>,
 1874    ) {
 1875        self.custom_context_menu = Some(Box::new(f))
 1876    }
 1877
 1878    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1879        self.completion_provider = provider;
 1880    }
 1881
 1882    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1883        self.semantics_provider.clone()
 1884    }
 1885
 1886    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1887        self.semantics_provider = provider;
 1888    }
 1889
 1890    pub fn set_edit_prediction_provider<T>(
 1891        &mut self,
 1892        provider: Option<Entity<T>>,
 1893        window: &mut Window,
 1894        cx: &mut Context<Self>,
 1895    ) where
 1896        T: EditPredictionProvider,
 1897    {
 1898        self.edit_prediction_provider =
 1899            provider.map(|provider| RegisteredInlineCompletionProvider {
 1900                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1901                    if this.focus_handle.is_focused(window) {
 1902                        this.update_visible_inline_completion(window, cx);
 1903                    }
 1904                }),
 1905                provider: Arc::new(provider),
 1906            });
 1907        self.update_edit_prediction_settings(cx);
 1908        self.refresh_inline_completion(false, false, window, cx);
 1909    }
 1910
 1911    pub fn placeholder_text(&self) -> Option<&str> {
 1912        self.placeholder_text.as_deref()
 1913    }
 1914
 1915    pub fn set_placeholder_text(
 1916        &mut self,
 1917        placeholder_text: impl Into<Arc<str>>,
 1918        cx: &mut Context<Self>,
 1919    ) {
 1920        let placeholder_text = Some(placeholder_text.into());
 1921        if self.placeholder_text != placeholder_text {
 1922            self.placeholder_text = placeholder_text;
 1923            cx.notify();
 1924        }
 1925    }
 1926
 1927    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1928        self.cursor_shape = cursor_shape;
 1929
 1930        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1931        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1932
 1933        cx.notify();
 1934    }
 1935
 1936    pub fn set_current_line_highlight(
 1937        &mut self,
 1938        current_line_highlight: Option<CurrentLineHighlight>,
 1939    ) {
 1940        self.current_line_highlight = current_line_highlight;
 1941    }
 1942
 1943    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1944        self.collapse_matches = collapse_matches;
 1945    }
 1946
 1947    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1948        let buffers = self.buffer.read(cx).all_buffers();
 1949        let Some(project) = self.project.as_ref() else {
 1950            return;
 1951        };
 1952        project.update(cx, |project, cx| {
 1953            for buffer in buffers {
 1954                self.registered_buffers
 1955                    .entry(buffer.read(cx).remote_id())
 1956                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 1957            }
 1958        })
 1959    }
 1960
 1961    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1962        if self.collapse_matches {
 1963            return range.start..range.start;
 1964        }
 1965        range.clone()
 1966    }
 1967
 1968    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1969        if self.display_map.read(cx).clip_at_line_ends != clip {
 1970            self.display_map
 1971                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1972        }
 1973    }
 1974
 1975    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1976        self.input_enabled = input_enabled;
 1977    }
 1978
 1979    pub fn set_inline_completions_hidden_for_vim_mode(
 1980        &mut self,
 1981        hidden: bool,
 1982        window: &mut Window,
 1983        cx: &mut Context<Self>,
 1984    ) {
 1985        if hidden != self.inline_completions_hidden_for_vim_mode {
 1986            self.inline_completions_hidden_for_vim_mode = hidden;
 1987            if hidden {
 1988                self.update_visible_inline_completion(window, cx);
 1989            } else {
 1990                self.refresh_inline_completion(true, false, window, cx);
 1991            }
 1992        }
 1993    }
 1994
 1995    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1996        self.menu_inline_completions_policy = value;
 1997    }
 1998
 1999    pub fn set_autoindent(&mut self, autoindent: bool) {
 2000        if autoindent {
 2001            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2002        } else {
 2003            self.autoindent_mode = None;
 2004        }
 2005    }
 2006
 2007    pub fn read_only(&self, cx: &App) -> bool {
 2008        self.read_only || self.buffer.read(cx).read_only()
 2009    }
 2010
 2011    pub fn set_read_only(&mut self, read_only: bool) {
 2012        self.read_only = read_only;
 2013    }
 2014
 2015    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2016        self.use_autoclose = autoclose;
 2017    }
 2018
 2019    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2020        self.use_auto_surround = auto_surround;
 2021    }
 2022
 2023    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2024        self.auto_replace_emoji_shortcode = auto_replace;
 2025    }
 2026
 2027    pub fn toggle_edit_predictions(
 2028        &mut self,
 2029        _: &ToggleEditPrediction,
 2030        window: &mut Window,
 2031        cx: &mut Context<Self>,
 2032    ) {
 2033        if self.show_inline_completions_override.is_some() {
 2034            self.set_show_edit_predictions(None, window, cx);
 2035        } else {
 2036            let show_edit_predictions = !self.edit_predictions_enabled();
 2037            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 2038        }
 2039    }
 2040
 2041    pub fn set_show_edit_predictions(
 2042        &mut self,
 2043        show_edit_predictions: Option<bool>,
 2044        window: &mut Window,
 2045        cx: &mut Context<Self>,
 2046    ) {
 2047        self.show_inline_completions_override = show_edit_predictions;
 2048        self.update_edit_prediction_settings(cx);
 2049
 2050        if let Some(false) = show_edit_predictions {
 2051            self.discard_inline_completion(false, cx);
 2052        } else {
 2053            self.refresh_inline_completion(false, true, window, cx);
 2054        }
 2055    }
 2056
 2057    fn inline_completions_disabled_in_scope(
 2058        &self,
 2059        buffer: &Entity<Buffer>,
 2060        buffer_position: language::Anchor,
 2061        cx: &App,
 2062    ) -> bool {
 2063        let snapshot = buffer.read(cx).snapshot();
 2064        let settings = snapshot.settings_at(buffer_position, cx);
 2065
 2066        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2067            return false;
 2068        };
 2069
 2070        scope.override_name().map_or(false, |scope_name| {
 2071            settings
 2072                .edit_predictions_disabled_in
 2073                .iter()
 2074                .any(|s| s == scope_name)
 2075        })
 2076    }
 2077
 2078    pub fn set_use_modal_editing(&mut self, to: bool) {
 2079        self.use_modal_editing = to;
 2080    }
 2081
 2082    pub fn use_modal_editing(&self) -> bool {
 2083        self.use_modal_editing
 2084    }
 2085
 2086    fn selections_did_change(
 2087        &mut self,
 2088        local: bool,
 2089        old_cursor_position: &Anchor,
 2090        show_completions: bool,
 2091        window: &mut Window,
 2092        cx: &mut Context<Self>,
 2093    ) {
 2094        window.invalidate_character_coordinates();
 2095
 2096        // Copy selections to primary selection buffer
 2097        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2098        if local {
 2099            let selections = self.selections.all::<usize>(cx);
 2100            let buffer_handle = self.buffer.read(cx).read(cx);
 2101
 2102            let mut text = String::new();
 2103            for (index, selection) in selections.iter().enumerate() {
 2104                let text_for_selection = buffer_handle
 2105                    .text_for_range(selection.start..selection.end)
 2106                    .collect::<String>();
 2107
 2108                text.push_str(&text_for_selection);
 2109                if index != selections.len() - 1 {
 2110                    text.push('\n');
 2111                }
 2112            }
 2113
 2114            if !text.is_empty() {
 2115                cx.write_to_primary(ClipboardItem::new_string(text));
 2116            }
 2117        }
 2118
 2119        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2120            self.buffer.update(cx, |buffer, cx| {
 2121                buffer.set_active_selections(
 2122                    &self.selections.disjoint_anchors(),
 2123                    self.selections.line_mode,
 2124                    self.cursor_shape,
 2125                    cx,
 2126                )
 2127            });
 2128        }
 2129        let display_map = self
 2130            .display_map
 2131            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2132        let buffer = &display_map.buffer_snapshot;
 2133        self.add_selections_state = None;
 2134        self.select_next_state = None;
 2135        self.select_prev_state = None;
 2136        self.select_larger_syntax_node_stack.clear();
 2137        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2138        self.snippet_stack
 2139            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2140        self.take_rename(false, window, cx);
 2141
 2142        let new_cursor_position = self.selections.newest_anchor().head();
 2143
 2144        self.push_to_nav_history(
 2145            *old_cursor_position,
 2146            Some(new_cursor_position.to_point(buffer)),
 2147            cx,
 2148        );
 2149
 2150        if local {
 2151            let new_cursor_position = self.selections.newest_anchor().head();
 2152            let mut context_menu = self.context_menu.borrow_mut();
 2153            let completion_menu = match context_menu.as_ref() {
 2154                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2155                _ => {
 2156                    *context_menu = None;
 2157                    None
 2158                }
 2159            };
 2160            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2161                if !self.registered_buffers.contains_key(&buffer_id) {
 2162                    if let Some(project) = self.project.as_ref() {
 2163                        project.update(cx, |project, cx| {
 2164                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2165                                return;
 2166                            };
 2167                            self.registered_buffers.insert(
 2168                                buffer_id,
 2169                                project.register_buffer_with_language_servers(&buffer, cx),
 2170                            );
 2171                        })
 2172                    }
 2173                }
 2174            }
 2175
 2176            if let Some(completion_menu) = completion_menu {
 2177                let cursor_position = new_cursor_position.to_offset(buffer);
 2178                let (word_range, kind) =
 2179                    buffer.surrounding_word(completion_menu.initial_position, true);
 2180                if kind == Some(CharKind::Word)
 2181                    && word_range.to_inclusive().contains(&cursor_position)
 2182                {
 2183                    let mut completion_menu = completion_menu.clone();
 2184                    drop(context_menu);
 2185
 2186                    let query = Self::completion_query(buffer, cursor_position);
 2187                    cx.spawn(async move |this, cx| {
 2188                        completion_menu
 2189                            .filter(query.as_deref(), cx.background_executor().clone())
 2190                            .await;
 2191
 2192                        this.update(cx, |this, cx| {
 2193                            let mut context_menu = this.context_menu.borrow_mut();
 2194                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2195                            else {
 2196                                return;
 2197                            };
 2198
 2199                            if menu.id > completion_menu.id {
 2200                                return;
 2201                            }
 2202
 2203                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2204                            drop(context_menu);
 2205                            cx.notify();
 2206                        })
 2207                    })
 2208                    .detach();
 2209
 2210                    if show_completions {
 2211                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2212                    }
 2213                } else {
 2214                    drop(context_menu);
 2215                    self.hide_context_menu(window, cx);
 2216                }
 2217            } else {
 2218                drop(context_menu);
 2219            }
 2220
 2221            hide_hover(self, cx);
 2222
 2223            if old_cursor_position.to_display_point(&display_map).row()
 2224                != new_cursor_position.to_display_point(&display_map).row()
 2225            {
 2226                self.available_code_actions.take();
 2227            }
 2228            self.refresh_code_actions(window, cx);
 2229            self.refresh_document_highlights(cx);
 2230            self.refresh_selected_text_highlights(window, cx);
 2231            refresh_matching_bracket_highlights(self, window, cx);
 2232            self.update_visible_inline_completion(window, cx);
 2233            self.edit_prediction_requires_modifier_in_indent_conflict = true;
 2234            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2235            if self.git_blame_inline_enabled {
 2236                self.start_inline_blame_timer(window, cx);
 2237            }
 2238        }
 2239
 2240        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2241        cx.emit(EditorEvent::SelectionsChanged { local });
 2242
 2243        let selections = &self.selections.disjoint;
 2244        if selections.len() == 1 {
 2245            cx.emit(SearchEvent::ActiveMatchChanged)
 2246        }
 2247        if local
 2248            && self.is_singleton(cx)
 2249            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
 2250        {
 2251            if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
 2252                let background_executor = cx.background_executor().clone();
 2253                let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2254                let snapshot = self.buffer().read(cx).snapshot(cx);
 2255                let selections = selections.clone();
 2256                self.serialize_selections = cx.background_spawn(async move {
 2257                    background_executor.timer(Duration::from_millis(100)).await;
 2258                    let selections = selections
 2259                        .iter()
 2260                        .map(|selection| {
 2261                            (
 2262                                selection.start.to_offset(&snapshot),
 2263                                selection.end.to_offset(&snapshot),
 2264                            )
 2265                        })
 2266                        .collect();
 2267                    DB.save_editor_selections(editor_id, workspace_id, selections)
 2268                        .await
 2269                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2270                        .log_err();
 2271                });
 2272            }
 2273        }
 2274
 2275        cx.notify();
 2276    }
 2277
 2278    pub fn sync_selections(
 2279        &mut self,
 2280        other: Entity<Editor>,
 2281        cx: &mut Context<Self>,
 2282    ) -> gpui::Subscription {
 2283        let other_selections = other.read(cx).selections.disjoint.to_vec();
 2284        self.selections.change_with(cx, |selections| {
 2285            selections.select_anchors(other_selections);
 2286        });
 2287
 2288        let other_subscription =
 2289            cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
 2290                EditorEvent::SelectionsChanged { local: true } => {
 2291                    let other_selections = other.read(cx).selections.disjoint.to_vec();
 2292                    if other_selections.is_empty() {
 2293                        return;
 2294                    }
 2295                    this.selections.change_with(cx, |selections| {
 2296                        selections.select_anchors(other_selections);
 2297                    });
 2298                }
 2299                _ => {}
 2300            });
 2301
 2302        let this_subscription =
 2303            cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
 2304                EditorEvent::SelectionsChanged { local: true } => {
 2305                    let these_selections = this.selections.disjoint.to_vec();
 2306                    if these_selections.is_empty() {
 2307                        return;
 2308                    }
 2309                    other.update(cx, |other_editor, cx| {
 2310                        other_editor.selections.change_with(cx, |selections| {
 2311                            selections.select_anchors(these_selections);
 2312                        })
 2313                    });
 2314                }
 2315                _ => {}
 2316            });
 2317
 2318        Subscription::join(other_subscription, this_subscription)
 2319    }
 2320
 2321    pub fn change_selections<R>(
 2322        &mut self,
 2323        autoscroll: Option<Autoscroll>,
 2324        window: &mut Window,
 2325        cx: &mut Context<Self>,
 2326        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2327    ) -> R {
 2328        self.change_selections_inner(autoscroll, true, window, cx, change)
 2329    }
 2330
 2331    fn change_selections_inner<R>(
 2332        &mut self,
 2333        autoscroll: Option<Autoscroll>,
 2334        request_completions: bool,
 2335        window: &mut Window,
 2336        cx: &mut Context<Self>,
 2337        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2338    ) -> R {
 2339        let old_cursor_position = self.selections.newest_anchor().head();
 2340        self.push_to_selection_history();
 2341
 2342        let (changed, result) = self.selections.change_with(cx, change);
 2343
 2344        if changed {
 2345            if let Some(autoscroll) = autoscroll {
 2346                self.request_autoscroll(autoscroll, cx);
 2347            }
 2348            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2349
 2350            if self.should_open_signature_help_automatically(
 2351                &old_cursor_position,
 2352                self.signature_help_state.backspace_pressed(),
 2353                cx,
 2354            ) {
 2355                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2356            }
 2357            self.signature_help_state.set_backspace_pressed(false);
 2358        }
 2359
 2360        result
 2361    }
 2362
 2363    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2364    where
 2365        I: IntoIterator<Item = (Range<S>, T)>,
 2366        S: ToOffset,
 2367        T: Into<Arc<str>>,
 2368    {
 2369        if self.read_only(cx) {
 2370            return;
 2371        }
 2372
 2373        self.buffer
 2374            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2375    }
 2376
 2377    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2378    where
 2379        I: IntoIterator<Item = (Range<S>, T)>,
 2380        S: ToOffset,
 2381        T: Into<Arc<str>>,
 2382    {
 2383        if self.read_only(cx) {
 2384            return;
 2385        }
 2386
 2387        self.buffer.update(cx, |buffer, cx| {
 2388            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2389        });
 2390    }
 2391
 2392    pub fn edit_with_block_indent<I, S, T>(
 2393        &mut self,
 2394        edits: I,
 2395        original_indent_columns: Vec<Option<u32>>,
 2396        cx: &mut Context<Self>,
 2397    ) where
 2398        I: IntoIterator<Item = (Range<S>, T)>,
 2399        S: ToOffset,
 2400        T: Into<Arc<str>>,
 2401    {
 2402        if self.read_only(cx) {
 2403            return;
 2404        }
 2405
 2406        self.buffer.update(cx, |buffer, cx| {
 2407            buffer.edit(
 2408                edits,
 2409                Some(AutoindentMode::Block {
 2410                    original_indent_columns,
 2411                }),
 2412                cx,
 2413            )
 2414        });
 2415    }
 2416
 2417    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2418        self.hide_context_menu(window, cx);
 2419
 2420        match phase {
 2421            SelectPhase::Begin {
 2422                position,
 2423                add,
 2424                click_count,
 2425            } => self.begin_selection(position, add, click_count, window, cx),
 2426            SelectPhase::BeginColumnar {
 2427                position,
 2428                goal_column,
 2429                reset,
 2430            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2431            SelectPhase::Extend {
 2432                position,
 2433                click_count,
 2434            } => self.extend_selection(position, click_count, window, cx),
 2435            SelectPhase::Update {
 2436                position,
 2437                goal_column,
 2438                scroll_delta,
 2439            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2440            SelectPhase::End => self.end_selection(window, cx),
 2441        }
 2442    }
 2443
 2444    fn extend_selection(
 2445        &mut self,
 2446        position: DisplayPoint,
 2447        click_count: usize,
 2448        window: &mut Window,
 2449        cx: &mut Context<Self>,
 2450    ) {
 2451        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2452        let tail = self.selections.newest::<usize>(cx).tail();
 2453        self.begin_selection(position, false, click_count, window, cx);
 2454
 2455        let position = position.to_offset(&display_map, Bias::Left);
 2456        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2457
 2458        let mut pending_selection = self
 2459            .selections
 2460            .pending_anchor()
 2461            .expect("extend_selection not called with pending selection");
 2462        if position >= tail {
 2463            pending_selection.start = tail_anchor;
 2464        } else {
 2465            pending_selection.end = tail_anchor;
 2466            pending_selection.reversed = true;
 2467        }
 2468
 2469        let mut pending_mode = self.selections.pending_mode().unwrap();
 2470        match &mut pending_mode {
 2471            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2472            _ => {}
 2473        }
 2474
 2475        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2476            s.set_pending(pending_selection, pending_mode)
 2477        });
 2478    }
 2479
 2480    fn begin_selection(
 2481        &mut self,
 2482        position: DisplayPoint,
 2483        add: bool,
 2484        click_count: usize,
 2485        window: &mut Window,
 2486        cx: &mut Context<Self>,
 2487    ) {
 2488        if !self.focus_handle.is_focused(window) {
 2489            self.last_focused_descendant = None;
 2490            window.focus(&self.focus_handle);
 2491        }
 2492
 2493        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2494        let buffer = &display_map.buffer_snapshot;
 2495        let newest_selection = self.selections.newest_anchor().clone();
 2496        let position = display_map.clip_point(position, Bias::Left);
 2497
 2498        let start;
 2499        let end;
 2500        let mode;
 2501        let mut auto_scroll;
 2502        match click_count {
 2503            1 => {
 2504                start = buffer.anchor_before(position.to_point(&display_map));
 2505                end = start;
 2506                mode = SelectMode::Character;
 2507                auto_scroll = true;
 2508            }
 2509            2 => {
 2510                let range = movement::surrounding_word(&display_map, position);
 2511                start = buffer.anchor_before(range.start.to_point(&display_map));
 2512                end = buffer.anchor_before(range.end.to_point(&display_map));
 2513                mode = SelectMode::Word(start..end);
 2514                auto_scroll = true;
 2515            }
 2516            3 => {
 2517                let position = display_map
 2518                    .clip_point(position, Bias::Left)
 2519                    .to_point(&display_map);
 2520                let line_start = display_map.prev_line_boundary(position).0;
 2521                let next_line_start = buffer.clip_point(
 2522                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2523                    Bias::Left,
 2524                );
 2525                start = buffer.anchor_before(line_start);
 2526                end = buffer.anchor_before(next_line_start);
 2527                mode = SelectMode::Line(start..end);
 2528                auto_scroll = true;
 2529            }
 2530            _ => {
 2531                start = buffer.anchor_before(0);
 2532                end = buffer.anchor_before(buffer.len());
 2533                mode = SelectMode::All;
 2534                auto_scroll = false;
 2535            }
 2536        }
 2537        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2538
 2539        let point_to_delete: Option<usize> = {
 2540            let selected_points: Vec<Selection<Point>> =
 2541                self.selections.disjoint_in_range(start..end, cx);
 2542
 2543            if !add || click_count > 1 {
 2544                None
 2545            } else if !selected_points.is_empty() {
 2546                Some(selected_points[0].id)
 2547            } else {
 2548                let clicked_point_already_selected =
 2549                    self.selections.disjoint.iter().find(|selection| {
 2550                        selection.start.to_point(buffer) == start.to_point(buffer)
 2551                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2552                    });
 2553
 2554                clicked_point_already_selected.map(|selection| selection.id)
 2555            }
 2556        };
 2557
 2558        let selections_count = self.selections.count();
 2559
 2560        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2561            if let Some(point_to_delete) = point_to_delete {
 2562                s.delete(point_to_delete);
 2563
 2564                if selections_count == 1 {
 2565                    s.set_pending_anchor_range(start..end, mode);
 2566                }
 2567            } else {
 2568                if !add {
 2569                    s.clear_disjoint();
 2570                } else if click_count > 1 {
 2571                    s.delete(newest_selection.id)
 2572                }
 2573
 2574                s.set_pending_anchor_range(start..end, mode);
 2575            }
 2576        });
 2577    }
 2578
 2579    fn begin_columnar_selection(
 2580        &mut self,
 2581        position: DisplayPoint,
 2582        goal_column: u32,
 2583        reset: bool,
 2584        window: &mut Window,
 2585        cx: &mut Context<Self>,
 2586    ) {
 2587        if !self.focus_handle.is_focused(window) {
 2588            self.last_focused_descendant = None;
 2589            window.focus(&self.focus_handle);
 2590        }
 2591
 2592        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2593
 2594        if reset {
 2595            let pointer_position = display_map
 2596                .buffer_snapshot
 2597                .anchor_before(position.to_point(&display_map));
 2598
 2599            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2600                s.clear_disjoint();
 2601                s.set_pending_anchor_range(
 2602                    pointer_position..pointer_position,
 2603                    SelectMode::Character,
 2604                );
 2605            });
 2606        }
 2607
 2608        let tail = self.selections.newest::<Point>(cx).tail();
 2609        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2610
 2611        if !reset {
 2612            self.select_columns(
 2613                tail.to_display_point(&display_map),
 2614                position,
 2615                goal_column,
 2616                &display_map,
 2617                window,
 2618                cx,
 2619            );
 2620        }
 2621    }
 2622
 2623    fn update_selection(
 2624        &mut self,
 2625        position: DisplayPoint,
 2626        goal_column: u32,
 2627        scroll_delta: gpui::Point<f32>,
 2628        window: &mut Window,
 2629        cx: &mut Context<Self>,
 2630    ) {
 2631        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2632
 2633        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2634            let tail = tail.to_display_point(&display_map);
 2635            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2636        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2637            let buffer = self.buffer.read(cx).snapshot(cx);
 2638            let head;
 2639            let tail;
 2640            let mode = self.selections.pending_mode().unwrap();
 2641            match &mode {
 2642                SelectMode::Character => {
 2643                    head = position.to_point(&display_map);
 2644                    tail = pending.tail().to_point(&buffer);
 2645                }
 2646                SelectMode::Word(original_range) => {
 2647                    let original_display_range = original_range.start.to_display_point(&display_map)
 2648                        ..original_range.end.to_display_point(&display_map);
 2649                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2650                        ..original_display_range.end.to_point(&display_map);
 2651                    if movement::is_inside_word(&display_map, position)
 2652                        || original_display_range.contains(&position)
 2653                    {
 2654                        let word_range = movement::surrounding_word(&display_map, position);
 2655                        if word_range.start < original_display_range.start {
 2656                            head = word_range.start.to_point(&display_map);
 2657                        } else {
 2658                            head = word_range.end.to_point(&display_map);
 2659                        }
 2660                    } else {
 2661                        head = position.to_point(&display_map);
 2662                    }
 2663
 2664                    if head <= original_buffer_range.start {
 2665                        tail = original_buffer_range.end;
 2666                    } else {
 2667                        tail = original_buffer_range.start;
 2668                    }
 2669                }
 2670                SelectMode::Line(original_range) => {
 2671                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2672
 2673                    let position = display_map
 2674                        .clip_point(position, Bias::Left)
 2675                        .to_point(&display_map);
 2676                    let line_start = display_map.prev_line_boundary(position).0;
 2677                    let next_line_start = buffer.clip_point(
 2678                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2679                        Bias::Left,
 2680                    );
 2681
 2682                    if line_start < original_range.start {
 2683                        head = line_start
 2684                    } else {
 2685                        head = next_line_start
 2686                    }
 2687
 2688                    if head <= original_range.start {
 2689                        tail = original_range.end;
 2690                    } else {
 2691                        tail = original_range.start;
 2692                    }
 2693                }
 2694                SelectMode::All => {
 2695                    return;
 2696                }
 2697            };
 2698
 2699            if head < tail {
 2700                pending.start = buffer.anchor_before(head);
 2701                pending.end = buffer.anchor_before(tail);
 2702                pending.reversed = true;
 2703            } else {
 2704                pending.start = buffer.anchor_before(tail);
 2705                pending.end = buffer.anchor_before(head);
 2706                pending.reversed = false;
 2707            }
 2708
 2709            self.change_selections(None, window, cx, |s| {
 2710                s.set_pending(pending, mode);
 2711            });
 2712        } else {
 2713            log::error!("update_selection dispatched with no pending selection");
 2714            return;
 2715        }
 2716
 2717        self.apply_scroll_delta(scroll_delta, window, cx);
 2718        cx.notify();
 2719    }
 2720
 2721    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2722        self.columnar_selection_tail.take();
 2723        if self.selections.pending_anchor().is_some() {
 2724            let selections = self.selections.all::<usize>(cx);
 2725            self.change_selections(None, window, cx, |s| {
 2726                s.select(selections);
 2727                s.clear_pending();
 2728            });
 2729        }
 2730    }
 2731
 2732    fn select_columns(
 2733        &mut self,
 2734        tail: DisplayPoint,
 2735        head: DisplayPoint,
 2736        goal_column: u32,
 2737        display_map: &DisplaySnapshot,
 2738        window: &mut Window,
 2739        cx: &mut Context<Self>,
 2740    ) {
 2741        let start_row = cmp::min(tail.row(), head.row());
 2742        let end_row = cmp::max(tail.row(), head.row());
 2743        let start_column = cmp::min(tail.column(), goal_column);
 2744        let end_column = cmp::max(tail.column(), goal_column);
 2745        let reversed = start_column < tail.column();
 2746
 2747        let selection_ranges = (start_row.0..=end_row.0)
 2748            .map(DisplayRow)
 2749            .filter_map(|row| {
 2750                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2751                    let start = display_map
 2752                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2753                        .to_point(display_map);
 2754                    let end = display_map
 2755                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2756                        .to_point(display_map);
 2757                    if reversed {
 2758                        Some(end..start)
 2759                    } else {
 2760                        Some(start..end)
 2761                    }
 2762                } else {
 2763                    None
 2764                }
 2765            })
 2766            .collect::<Vec<_>>();
 2767
 2768        self.change_selections(None, window, cx, |s| {
 2769            s.select_ranges(selection_ranges);
 2770        });
 2771        cx.notify();
 2772    }
 2773
 2774    pub fn has_pending_nonempty_selection(&self) -> bool {
 2775        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2776            Some(Selection { start, end, .. }) => start != end,
 2777            None => false,
 2778        };
 2779
 2780        pending_nonempty_selection
 2781            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2782    }
 2783
 2784    pub fn has_pending_selection(&self) -> bool {
 2785        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2786    }
 2787
 2788    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2789        self.selection_mark_mode = false;
 2790
 2791        if self.clear_expanded_diff_hunks(cx) {
 2792            cx.notify();
 2793            return;
 2794        }
 2795        if self.dismiss_menus_and_popups(true, window, cx) {
 2796            return;
 2797        }
 2798
 2799        if self.mode == EditorMode::Full
 2800            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2801        {
 2802            return;
 2803        }
 2804
 2805        cx.propagate();
 2806    }
 2807
 2808    pub fn dismiss_menus_and_popups(
 2809        &mut self,
 2810        is_user_requested: bool,
 2811        window: &mut Window,
 2812        cx: &mut Context<Self>,
 2813    ) -> bool {
 2814        if self.take_rename(false, window, cx).is_some() {
 2815            return true;
 2816        }
 2817
 2818        if hide_hover(self, cx) {
 2819            return true;
 2820        }
 2821
 2822        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2823            return true;
 2824        }
 2825
 2826        if self.hide_context_menu(window, cx).is_some() {
 2827            return true;
 2828        }
 2829
 2830        if self.mouse_context_menu.take().is_some() {
 2831            return true;
 2832        }
 2833
 2834        if is_user_requested && self.discard_inline_completion(true, cx) {
 2835            return true;
 2836        }
 2837
 2838        if self.snippet_stack.pop().is_some() {
 2839            return true;
 2840        }
 2841
 2842        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2843            self.dismiss_diagnostics(cx);
 2844            return true;
 2845        }
 2846
 2847        false
 2848    }
 2849
 2850    fn linked_editing_ranges_for(
 2851        &self,
 2852        selection: Range<text::Anchor>,
 2853        cx: &App,
 2854    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2855        if self.linked_edit_ranges.is_empty() {
 2856            return None;
 2857        }
 2858        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2859            selection.end.buffer_id.and_then(|end_buffer_id| {
 2860                if selection.start.buffer_id != Some(end_buffer_id) {
 2861                    return None;
 2862                }
 2863                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2864                let snapshot = buffer.read(cx).snapshot();
 2865                self.linked_edit_ranges
 2866                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2867                    .map(|ranges| (ranges, snapshot, buffer))
 2868            })?;
 2869        use text::ToOffset as TO;
 2870        // find offset from the start of current range to current cursor position
 2871        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2872
 2873        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2874        let start_difference = start_offset - start_byte_offset;
 2875        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2876        let end_difference = end_offset - start_byte_offset;
 2877        // Current range has associated linked ranges.
 2878        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2879        for range in linked_ranges.iter() {
 2880            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2881            let end_offset = start_offset + end_difference;
 2882            let start_offset = start_offset + start_difference;
 2883            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2884                continue;
 2885            }
 2886            if self.selections.disjoint_anchor_ranges().any(|s| {
 2887                if s.start.buffer_id != selection.start.buffer_id
 2888                    || s.end.buffer_id != selection.end.buffer_id
 2889                {
 2890                    return false;
 2891                }
 2892                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2893                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2894            }) {
 2895                continue;
 2896            }
 2897            let start = buffer_snapshot.anchor_after(start_offset);
 2898            let end = buffer_snapshot.anchor_after(end_offset);
 2899            linked_edits
 2900                .entry(buffer.clone())
 2901                .or_default()
 2902                .push(start..end);
 2903        }
 2904        Some(linked_edits)
 2905    }
 2906
 2907    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2908        let text: Arc<str> = text.into();
 2909
 2910        if self.read_only(cx) {
 2911            return;
 2912        }
 2913
 2914        let selections = self.selections.all_adjusted(cx);
 2915        let mut bracket_inserted = false;
 2916        let mut edits = Vec::new();
 2917        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2918        let mut new_selections = Vec::with_capacity(selections.len());
 2919        let mut new_autoclose_regions = Vec::new();
 2920        let snapshot = self.buffer.read(cx).read(cx);
 2921
 2922        for (selection, autoclose_region) in
 2923            self.selections_with_autoclose_regions(selections, &snapshot)
 2924        {
 2925            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2926                // Determine if the inserted text matches the opening or closing
 2927                // bracket of any of this language's bracket pairs.
 2928                let mut bracket_pair = None;
 2929                let mut is_bracket_pair_start = false;
 2930                let mut is_bracket_pair_end = false;
 2931                if !text.is_empty() {
 2932                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2933                    //  and they are removing the character that triggered IME popup.
 2934                    for (pair, enabled) in scope.brackets() {
 2935                        if !pair.close && !pair.surround {
 2936                            continue;
 2937                        }
 2938
 2939                        if enabled && pair.start.ends_with(text.as_ref()) {
 2940                            let prefix_len = pair.start.len() - text.len();
 2941                            let preceding_text_matches_prefix = prefix_len == 0
 2942                                || (selection.start.column >= (prefix_len as u32)
 2943                                    && snapshot.contains_str_at(
 2944                                        Point::new(
 2945                                            selection.start.row,
 2946                                            selection.start.column - (prefix_len as u32),
 2947                                        ),
 2948                                        &pair.start[..prefix_len],
 2949                                    ));
 2950                            if preceding_text_matches_prefix {
 2951                                bracket_pair = Some(pair.clone());
 2952                                is_bracket_pair_start = true;
 2953                                break;
 2954                            }
 2955                        }
 2956                        if pair.end.as_str() == text.as_ref() {
 2957                            bracket_pair = Some(pair.clone());
 2958                            is_bracket_pair_end = true;
 2959                            break;
 2960                        }
 2961                    }
 2962                }
 2963
 2964                if let Some(bracket_pair) = bracket_pair {
 2965                    let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
 2966                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2967                    let auto_surround =
 2968                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2969                    if selection.is_empty() {
 2970                        if is_bracket_pair_start {
 2971                            // If the inserted text is a suffix of an opening bracket and the
 2972                            // selection is preceded by the rest of the opening bracket, then
 2973                            // insert the closing bracket.
 2974                            let following_text_allows_autoclose = snapshot
 2975                                .chars_at(selection.start)
 2976                                .next()
 2977                                .map_or(true, |c| scope.should_autoclose_before(c));
 2978
 2979                            let preceding_text_allows_autoclose = selection.start.column == 0
 2980                                || snapshot.reversed_chars_at(selection.start).next().map_or(
 2981                                    true,
 2982                                    |c| {
 2983                                        bracket_pair.start != bracket_pair.end
 2984                                            || !snapshot
 2985                                                .char_classifier_at(selection.start)
 2986                                                .is_word(c)
 2987                                    },
 2988                                );
 2989
 2990                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2991                                && bracket_pair.start.len() == 1
 2992                            {
 2993                                let target = bracket_pair.start.chars().next().unwrap();
 2994                                let current_line_count = snapshot
 2995                                    .reversed_chars_at(selection.start)
 2996                                    .take_while(|&c| c != '\n')
 2997                                    .filter(|&c| c == target)
 2998                                    .count();
 2999                                current_line_count % 2 == 1
 3000                            } else {
 3001                                false
 3002                            };
 3003
 3004                            if autoclose
 3005                                && bracket_pair.close
 3006                                && following_text_allows_autoclose
 3007                                && preceding_text_allows_autoclose
 3008                                && !is_closing_quote
 3009                            {
 3010                                let anchor = snapshot.anchor_before(selection.end);
 3011                                new_selections.push((selection.map(|_| anchor), text.len()));
 3012                                new_autoclose_regions.push((
 3013                                    anchor,
 3014                                    text.len(),
 3015                                    selection.id,
 3016                                    bracket_pair.clone(),
 3017                                ));
 3018                                edits.push((
 3019                                    selection.range(),
 3020                                    format!("{}{}", text, bracket_pair.end).into(),
 3021                                ));
 3022                                bracket_inserted = true;
 3023                                continue;
 3024                            }
 3025                        }
 3026
 3027                        if let Some(region) = autoclose_region {
 3028                            // If the selection is followed by an auto-inserted closing bracket,
 3029                            // then don't insert that closing bracket again; just move the selection
 3030                            // past the closing bracket.
 3031                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3032                                && text.as_ref() == region.pair.end.as_str();
 3033                            if should_skip {
 3034                                let anchor = snapshot.anchor_after(selection.end);
 3035                                new_selections
 3036                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3037                                continue;
 3038                            }
 3039                        }
 3040
 3041                        let always_treat_brackets_as_autoclosed = snapshot
 3042                            .language_settings_at(selection.start, cx)
 3043                            .always_treat_brackets_as_autoclosed;
 3044                        if always_treat_brackets_as_autoclosed
 3045                            && is_bracket_pair_end
 3046                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3047                        {
 3048                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3049                            // and the inserted text is a closing bracket and the selection is followed
 3050                            // by the closing bracket then move the selection past the closing bracket.
 3051                            let anchor = snapshot.anchor_after(selection.end);
 3052                            new_selections.push((selection.map(|_| anchor), text.len()));
 3053                            continue;
 3054                        }
 3055                    }
 3056                    // If an opening bracket is 1 character long and is typed while
 3057                    // text is selected, then surround that text with the bracket pair.
 3058                    else if auto_surround
 3059                        && bracket_pair.surround
 3060                        && is_bracket_pair_start
 3061                        && bracket_pair.start.chars().count() == 1
 3062                    {
 3063                        edits.push((selection.start..selection.start, text.clone()));
 3064                        edits.push((
 3065                            selection.end..selection.end,
 3066                            bracket_pair.end.as_str().into(),
 3067                        ));
 3068                        bracket_inserted = true;
 3069                        new_selections.push((
 3070                            Selection {
 3071                                id: selection.id,
 3072                                start: snapshot.anchor_after(selection.start),
 3073                                end: snapshot.anchor_before(selection.end),
 3074                                reversed: selection.reversed,
 3075                                goal: selection.goal,
 3076                            },
 3077                            0,
 3078                        ));
 3079                        continue;
 3080                    }
 3081                }
 3082            }
 3083
 3084            if self.auto_replace_emoji_shortcode
 3085                && selection.is_empty()
 3086                && text.as_ref().ends_with(':')
 3087            {
 3088                if let Some(possible_emoji_short_code) =
 3089                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3090                {
 3091                    if !possible_emoji_short_code.is_empty() {
 3092                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3093                            let emoji_shortcode_start = Point::new(
 3094                                selection.start.row,
 3095                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3096                            );
 3097
 3098                            // Remove shortcode from buffer
 3099                            edits.push((
 3100                                emoji_shortcode_start..selection.start,
 3101                                "".to_string().into(),
 3102                            ));
 3103                            new_selections.push((
 3104                                Selection {
 3105                                    id: selection.id,
 3106                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3107                                    end: snapshot.anchor_before(selection.start),
 3108                                    reversed: selection.reversed,
 3109                                    goal: selection.goal,
 3110                                },
 3111                                0,
 3112                            ));
 3113
 3114                            // Insert emoji
 3115                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3116                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3117                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3118
 3119                            continue;
 3120                        }
 3121                    }
 3122                }
 3123            }
 3124
 3125            // If not handling any auto-close operation, then just replace the selected
 3126            // text with the given input and move the selection to the end of the
 3127            // newly inserted text.
 3128            let anchor = snapshot.anchor_after(selection.end);
 3129            if !self.linked_edit_ranges.is_empty() {
 3130                let start_anchor = snapshot.anchor_before(selection.start);
 3131
 3132                let is_word_char = text.chars().next().map_or(true, |char| {
 3133                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3134                    classifier.is_word(char)
 3135                });
 3136
 3137                if is_word_char {
 3138                    if let Some(ranges) = self
 3139                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3140                    {
 3141                        for (buffer, edits) in ranges {
 3142                            linked_edits
 3143                                .entry(buffer.clone())
 3144                                .or_default()
 3145                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3146                        }
 3147                    }
 3148                }
 3149            }
 3150
 3151            new_selections.push((selection.map(|_| anchor), 0));
 3152            edits.push((selection.start..selection.end, text.clone()));
 3153        }
 3154
 3155        drop(snapshot);
 3156
 3157        self.transact(window, cx, |this, window, cx| {
 3158            let initial_buffer_versions =
 3159                jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
 3160
 3161            this.buffer.update(cx, |buffer, cx| {
 3162                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3163            });
 3164            for (buffer, edits) in linked_edits {
 3165                buffer.update(cx, |buffer, cx| {
 3166                    let snapshot = buffer.snapshot();
 3167                    let edits = edits
 3168                        .into_iter()
 3169                        .map(|(range, text)| {
 3170                            use text::ToPoint as TP;
 3171                            let end_point = TP::to_point(&range.end, &snapshot);
 3172                            let start_point = TP::to_point(&range.start, &snapshot);
 3173                            (start_point..end_point, text)
 3174                        })
 3175                        .sorted_by_key(|(range, _)| range.start)
 3176                        .collect::<Vec<_>>();
 3177                    buffer.edit(edits, None, cx);
 3178                })
 3179            }
 3180            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3181            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3182            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3183            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3184                .zip(new_selection_deltas)
 3185                .map(|(selection, delta)| Selection {
 3186                    id: selection.id,
 3187                    start: selection.start + delta,
 3188                    end: selection.end + delta,
 3189                    reversed: selection.reversed,
 3190                    goal: SelectionGoal::None,
 3191                })
 3192                .collect::<Vec<_>>();
 3193
 3194            let mut i = 0;
 3195            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3196                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3197                let start = map.buffer_snapshot.anchor_before(position);
 3198                let end = map.buffer_snapshot.anchor_after(position);
 3199                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3200                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3201                        Ordering::Less => i += 1,
 3202                        Ordering::Greater => break,
 3203                        Ordering::Equal => {
 3204                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3205                                Ordering::Less => i += 1,
 3206                                Ordering::Equal => break,
 3207                                Ordering::Greater => break,
 3208                            }
 3209                        }
 3210                    }
 3211                }
 3212                this.autoclose_regions.insert(
 3213                    i,
 3214                    AutocloseRegion {
 3215                        selection_id,
 3216                        range: start..end,
 3217                        pair,
 3218                    },
 3219                );
 3220            }
 3221
 3222            let had_active_inline_completion = this.has_active_inline_completion();
 3223            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3224                s.select(new_selections)
 3225            });
 3226
 3227            if !bracket_inserted {
 3228                if let Some(on_type_format_task) =
 3229                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3230                {
 3231                    on_type_format_task.detach_and_log_err(cx);
 3232                }
 3233            }
 3234
 3235            let editor_settings = EditorSettings::get_global(cx);
 3236            if bracket_inserted
 3237                && (editor_settings.auto_signature_help
 3238                    || editor_settings.show_signature_help_after_edits)
 3239            {
 3240                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3241            }
 3242
 3243            let trigger_in_words =
 3244                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3245            if this.hard_wrap.is_some() {
 3246                let latest: Range<Point> = this.selections.newest(cx).range();
 3247                if latest.is_empty()
 3248                    && this
 3249                        .buffer()
 3250                        .read(cx)
 3251                        .snapshot(cx)
 3252                        .line_len(MultiBufferRow(latest.start.row))
 3253                        == latest.start.column
 3254                {
 3255                    this.rewrap_impl(
 3256                        RewrapOptions {
 3257                            override_language_settings: true,
 3258                            preserve_existing_whitespace: true,
 3259                        },
 3260                        cx,
 3261                    )
 3262                }
 3263            }
 3264            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3265            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3266            this.refresh_inline_completion(true, false, window, cx);
 3267            jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
 3268        });
 3269    }
 3270
 3271    fn find_possible_emoji_shortcode_at_position(
 3272        snapshot: &MultiBufferSnapshot,
 3273        position: Point,
 3274    ) -> Option<String> {
 3275        let mut chars = Vec::new();
 3276        let mut found_colon = false;
 3277        for char in snapshot.reversed_chars_at(position).take(100) {
 3278            // Found a possible emoji shortcode in the middle of the buffer
 3279            if found_colon {
 3280                if char.is_whitespace() {
 3281                    chars.reverse();
 3282                    return Some(chars.iter().collect());
 3283                }
 3284                // If the previous character is not a whitespace, we are in the middle of a word
 3285                // and we only want to complete the shortcode if the word is made up of other emojis
 3286                let mut containing_word = String::new();
 3287                for ch in snapshot
 3288                    .reversed_chars_at(position)
 3289                    .skip(chars.len() + 1)
 3290                    .take(100)
 3291                {
 3292                    if ch.is_whitespace() {
 3293                        break;
 3294                    }
 3295                    containing_word.push(ch);
 3296                }
 3297                let containing_word = containing_word.chars().rev().collect::<String>();
 3298                if util::word_consists_of_emojis(containing_word.as_str()) {
 3299                    chars.reverse();
 3300                    return Some(chars.iter().collect());
 3301                }
 3302            }
 3303
 3304            if char.is_whitespace() || !char.is_ascii() {
 3305                return None;
 3306            }
 3307            if char == ':' {
 3308                found_colon = true;
 3309            } else {
 3310                chars.push(char);
 3311            }
 3312        }
 3313        // Found a possible emoji shortcode at the beginning of the buffer
 3314        chars.reverse();
 3315        Some(chars.iter().collect())
 3316    }
 3317
 3318    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3319        self.transact(window, cx, |this, window, cx| {
 3320            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3321                let selections = this.selections.all::<usize>(cx);
 3322                let multi_buffer = this.buffer.read(cx);
 3323                let buffer = multi_buffer.snapshot(cx);
 3324                selections
 3325                    .iter()
 3326                    .map(|selection| {
 3327                        let start_point = selection.start.to_point(&buffer);
 3328                        let mut indent =
 3329                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3330                        indent.len = cmp::min(indent.len, start_point.column);
 3331                        let start = selection.start;
 3332                        let end = selection.end;
 3333                        let selection_is_empty = start == end;
 3334                        let language_scope = buffer.language_scope_at(start);
 3335                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3336                            &language_scope
 3337                        {
 3338                            let insert_extra_newline =
 3339                                insert_extra_newline_brackets(&buffer, start..end, language)
 3340                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3341
 3342                            // Comment extension on newline is allowed only for cursor selections
 3343                            let comment_delimiter = maybe!({
 3344                                if !selection_is_empty {
 3345                                    return None;
 3346                                }
 3347
 3348                                if !multi_buffer.language_settings(cx).extend_comment_on_newline {
 3349                                    return None;
 3350                                }
 3351
 3352                                let delimiters = language.line_comment_prefixes();
 3353                                let max_len_of_delimiter =
 3354                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3355                                let (snapshot, range) =
 3356                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3357
 3358                                let mut index_of_first_non_whitespace = 0;
 3359                                let comment_candidate = snapshot
 3360                                    .chars_for_range(range)
 3361                                    .skip_while(|c| {
 3362                                        let should_skip = c.is_whitespace();
 3363                                        if should_skip {
 3364                                            index_of_first_non_whitespace += 1;
 3365                                        }
 3366                                        should_skip
 3367                                    })
 3368                                    .take(max_len_of_delimiter)
 3369                                    .collect::<String>();
 3370                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3371                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3372                                })?;
 3373                                let cursor_is_placed_after_comment_marker =
 3374                                    index_of_first_non_whitespace + comment_prefix.len()
 3375                                        <= start_point.column as usize;
 3376                                if cursor_is_placed_after_comment_marker {
 3377                                    Some(comment_prefix.clone())
 3378                                } else {
 3379                                    None
 3380                                }
 3381                            });
 3382                            (comment_delimiter, insert_extra_newline)
 3383                        } else {
 3384                            (None, false)
 3385                        };
 3386
 3387                        let capacity_for_delimiter = comment_delimiter
 3388                            .as_deref()
 3389                            .map(str::len)
 3390                            .unwrap_or_default();
 3391                        let mut new_text =
 3392                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3393                        new_text.push('\n');
 3394                        new_text.extend(indent.chars());
 3395                        if let Some(delimiter) = &comment_delimiter {
 3396                            new_text.push_str(delimiter);
 3397                        }
 3398                        if insert_extra_newline {
 3399                            new_text = new_text.repeat(2);
 3400                        }
 3401
 3402                        let anchor = buffer.anchor_after(end);
 3403                        let new_selection = selection.map(|_| anchor);
 3404                        (
 3405                            (start..end, new_text),
 3406                            (insert_extra_newline, new_selection),
 3407                        )
 3408                    })
 3409                    .unzip()
 3410            };
 3411
 3412            this.edit_with_autoindent(edits, cx);
 3413            let buffer = this.buffer.read(cx).snapshot(cx);
 3414            let new_selections = selection_fixup_info
 3415                .into_iter()
 3416                .map(|(extra_newline_inserted, new_selection)| {
 3417                    let mut cursor = new_selection.end.to_point(&buffer);
 3418                    if extra_newline_inserted {
 3419                        cursor.row -= 1;
 3420                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3421                    }
 3422                    new_selection.map(|_| cursor)
 3423                })
 3424                .collect();
 3425
 3426            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3427                s.select(new_selections)
 3428            });
 3429            this.refresh_inline_completion(true, false, window, cx);
 3430        });
 3431    }
 3432
 3433    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3434        let buffer = self.buffer.read(cx);
 3435        let snapshot = buffer.snapshot(cx);
 3436
 3437        let mut edits = Vec::new();
 3438        let mut rows = Vec::new();
 3439
 3440        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3441            let cursor = selection.head();
 3442            let row = cursor.row;
 3443
 3444            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3445
 3446            let newline = "\n".to_string();
 3447            edits.push((start_of_line..start_of_line, newline));
 3448
 3449            rows.push(row + rows_inserted as u32);
 3450        }
 3451
 3452        self.transact(window, cx, |editor, window, cx| {
 3453            editor.edit(edits, cx);
 3454
 3455            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3456                let mut index = 0;
 3457                s.move_cursors_with(|map, _, _| {
 3458                    let row = rows[index];
 3459                    index += 1;
 3460
 3461                    let point = Point::new(row, 0);
 3462                    let boundary = map.next_line_boundary(point).1;
 3463                    let clipped = map.clip_point(boundary, Bias::Left);
 3464
 3465                    (clipped, SelectionGoal::None)
 3466                });
 3467            });
 3468
 3469            let mut indent_edits = Vec::new();
 3470            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3471            for row in rows {
 3472                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3473                for (row, indent) in indents {
 3474                    if indent.len == 0 {
 3475                        continue;
 3476                    }
 3477
 3478                    let text = match indent.kind {
 3479                        IndentKind::Space => " ".repeat(indent.len as usize),
 3480                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3481                    };
 3482                    let point = Point::new(row.0, 0);
 3483                    indent_edits.push((point..point, text));
 3484                }
 3485            }
 3486            editor.edit(indent_edits, cx);
 3487        });
 3488    }
 3489
 3490    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3491        let buffer = self.buffer.read(cx);
 3492        let snapshot = buffer.snapshot(cx);
 3493
 3494        let mut edits = Vec::new();
 3495        let mut rows = Vec::new();
 3496        let mut rows_inserted = 0;
 3497
 3498        for selection in self.selections.all_adjusted(cx) {
 3499            let cursor = selection.head();
 3500            let row = cursor.row;
 3501
 3502            let point = Point::new(row + 1, 0);
 3503            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3504
 3505            let newline = "\n".to_string();
 3506            edits.push((start_of_line..start_of_line, newline));
 3507
 3508            rows_inserted += 1;
 3509            rows.push(row + rows_inserted);
 3510        }
 3511
 3512        self.transact(window, cx, |editor, window, cx| {
 3513            editor.edit(edits, cx);
 3514
 3515            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3516                let mut index = 0;
 3517                s.move_cursors_with(|map, _, _| {
 3518                    let row = rows[index];
 3519                    index += 1;
 3520
 3521                    let point = Point::new(row, 0);
 3522                    let boundary = map.next_line_boundary(point).1;
 3523                    let clipped = map.clip_point(boundary, Bias::Left);
 3524
 3525                    (clipped, SelectionGoal::None)
 3526                });
 3527            });
 3528
 3529            let mut indent_edits = Vec::new();
 3530            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3531            for row in rows {
 3532                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3533                for (row, indent) in indents {
 3534                    if indent.len == 0 {
 3535                        continue;
 3536                    }
 3537
 3538                    let text = match indent.kind {
 3539                        IndentKind::Space => " ".repeat(indent.len as usize),
 3540                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3541                    };
 3542                    let point = Point::new(row.0, 0);
 3543                    indent_edits.push((point..point, text));
 3544                }
 3545            }
 3546            editor.edit(indent_edits, cx);
 3547        });
 3548    }
 3549
 3550    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3551        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3552            original_indent_columns: Vec::new(),
 3553        });
 3554        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3555    }
 3556
 3557    fn insert_with_autoindent_mode(
 3558        &mut self,
 3559        text: &str,
 3560        autoindent_mode: Option<AutoindentMode>,
 3561        window: &mut Window,
 3562        cx: &mut Context<Self>,
 3563    ) {
 3564        if self.read_only(cx) {
 3565            return;
 3566        }
 3567
 3568        let text: Arc<str> = text.into();
 3569        self.transact(window, cx, |this, window, cx| {
 3570            let old_selections = this.selections.all_adjusted(cx);
 3571            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3572                let anchors = {
 3573                    let snapshot = buffer.read(cx);
 3574                    old_selections
 3575                        .iter()
 3576                        .map(|s| {
 3577                            let anchor = snapshot.anchor_after(s.head());
 3578                            s.map(|_| anchor)
 3579                        })
 3580                        .collect::<Vec<_>>()
 3581                };
 3582                buffer.edit(
 3583                    old_selections
 3584                        .iter()
 3585                        .map(|s| (s.start..s.end, text.clone())),
 3586                    autoindent_mode,
 3587                    cx,
 3588                );
 3589                anchors
 3590            });
 3591
 3592            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3593                s.select_anchors(selection_anchors);
 3594            });
 3595
 3596            cx.notify();
 3597        });
 3598    }
 3599
 3600    fn trigger_completion_on_input(
 3601        &mut self,
 3602        text: &str,
 3603        trigger_in_words: bool,
 3604        window: &mut Window,
 3605        cx: &mut Context<Self>,
 3606    ) {
 3607        let ignore_completion_provider = self
 3608            .context_menu
 3609            .borrow()
 3610            .as_ref()
 3611            .map(|menu| match menu {
 3612                CodeContextMenu::Completions(completions_menu) => {
 3613                    completions_menu.ignore_completion_provider
 3614                }
 3615                CodeContextMenu::CodeActions(_) => false,
 3616            })
 3617            .unwrap_or(false);
 3618
 3619        if ignore_completion_provider {
 3620            self.show_word_completions(&ShowWordCompletions, window, cx);
 3621        } else if self.is_completion_trigger(text, trigger_in_words, cx) {
 3622            self.show_completions(
 3623                &ShowCompletions {
 3624                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3625                },
 3626                window,
 3627                cx,
 3628            );
 3629        } else {
 3630            self.hide_context_menu(window, cx);
 3631        }
 3632    }
 3633
 3634    fn is_completion_trigger(
 3635        &self,
 3636        text: &str,
 3637        trigger_in_words: bool,
 3638        cx: &mut Context<Self>,
 3639    ) -> bool {
 3640        let position = self.selections.newest_anchor().head();
 3641        let multibuffer = self.buffer.read(cx);
 3642        let Some(buffer) = position
 3643            .buffer_id
 3644            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3645        else {
 3646            return false;
 3647        };
 3648
 3649        if let Some(completion_provider) = &self.completion_provider {
 3650            completion_provider.is_completion_trigger(
 3651                &buffer,
 3652                position.text_anchor,
 3653                text,
 3654                trigger_in_words,
 3655                cx,
 3656            )
 3657        } else {
 3658            false
 3659        }
 3660    }
 3661
 3662    /// If any empty selections is touching the start of its innermost containing autoclose
 3663    /// region, expand it to select the brackets.
 3664    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3665        let selections = self.selections.all::<usize>(cx);
 3666        let buffer = self.buffer.read(cx).read(cx);
 3667        let new_selections = self
 3668            .selections_with_autoclose_regions(selections, &buffer)
 3669            .map(|(mut selection, region)| {
 3670                if !selection.is_empty() {
 3671                    return selection;
 3672                }
 3673
 3674                if let Some(region) = region {
 3675                    let mut range = region.range.to_offset(&buffer);
 3676                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3677                        range.start -= region.pair.start.len();
 3678                        if buffer.contains_str_at(range.start, &region.pair.start)
 3679                            && buffer.contains_str_at(range.end, &region.pair.end)
 3680                        {
 3681                            range.end += region.pair.end.len();
 3682                            selection.start = range.start;
 3683                            selection.end = range.end;
 3684
 3685                            return selection;
 3686                        }
 3687                    }
 3688                }
 3689
 3690                let always_treat_brackets_as_autoclosed = buffer
 3691                    .language_settings_at(selection.start, cx)
 3692                    .always_treat_brackets_as_autoclosed;
 3693
 3694                if !always_treat_brackets_as_autoclosed {
 3695                    return selection;
 3696                }
 3697
 3698                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3699                    for (pair, enabled) in scope.brackets() {
 3700                        if !enabled || !pair.close {
 3701                            continue;
 3702                        }
 3703
 3704                        if buffer.contains_str_at(selection.start, &pair.end) {
 3705                            let pair_start_len = pair.start.len();
 3706                            if buffer.contains_str_at(
 3707                                selection.start.saturating_sub(pair_start_len),
 3708                                &pair.start,
 3709                            ) {
 3710                                selection.start -= pair_start_len;
 3711                                selection.end += pair.end.len();
 3712
 3713                                return selection;
 3714                            }
 3715                        }
 3716                    }
 3717                }
 3718
 3719                selection
 3720            })
 3721            .collect();
 3722
 3723        drop(buffer);
 3724        self.change_selections(None, window, cx, |selections| {
 3725            selections.select(new_selections)
 3726        });
 3727    }
 3728
 3729    /// Iterate the given selections, and for each one, find the smallest surrounding
 3730    /// autoclose region. This uses the ordering of the selections and the autoclose
 3731    /// regions to avoid repeated comparisons.
 3732    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3733        &'a self,
 3734        selections: impl IntoIterator<Item = Selection<D>>,
 3735        buffer: &'a MultiBufferSnapshot,
 3736    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3737        let mut i = 0;
 3738        let mut regions = self.autoclose_regions.as_slice();
 3739        selections.into_iter().map(move |selection| {
 3740            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3741
 3742            let mut enclosing = None;
 3743            while let Some(pair_state) = regions.get(i) {
 3744                if pair_state.range.end.to_offset(buffer) < range.start {
 3745                    regions = &regions[i + 1..];
 3746                    i = 0;
 3747                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3748                    break;
 3749                } else {
 3750                    if pair_state.selection_id == selection.id {
 3751                        enclosing = Some(pair_state);
 3752                    }
 3753                    i += 1;
 3754                }
 3755            }
 3756
 3757            (selection, enclosing)
 3758        })
 3759    }
 3760
 3761    /// Remove any autoclose regions that no longer contain their selection.
 3762    fn invalidate_autoclose_regions(
 3763        &mut self,
 3764        mut selections: &[Selection<Anchor>],
 3765        buffer: &MultiBufferSnapshot,
 3766    ) {
 3767        self.autoclose_regions.retain(|state| {
 3768            let mut i = 0;
 3769            while let Some(selection) = selections.get(i) {
 3770                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3771                    selections = &selections[1..];
 3772                    continue;
 3773                }
 3774                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3775                    break;
 3776                }
 3777                if selection.id == state.selection_id {
 3778                    return true;
 3779                } else {
 3780                    i += 1;
 3781                }
 3782            }
 3783            false
 3784        });
 3785    }
 3786
 3787    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3788        let offset = position.to_offset(buffer);
 3789        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3790        if offset > word_range.start && kind == Some(CharKind::Word) {
 3791            Some(
 3792                buffer
 3793                    .text_for_range(word_range.start..offset)
 3794                    .collect::<String>(),
 3795            )
 3796        } else {
 3797            None
 3798        }
 3799    }
 3800
 3801    pub fn toggle_inlay_hints(
 3802        &mut self,
 3803        _: &ToggleInlayHints,
 3804        _: &mut Window,
 3805        cx: &mut Context<Self>,
 3806    ) {
 3807        self.refresh_inlay_hints(
 3808            InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
 3809            cx,
 3810        );
 3811    }
 3812
 3813    pub fn inlay_hints_enabled(&self) -> bool {
 3814        self.inlay_hint_cache.enabled
 3815    }
 3816
 3817    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3818        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3819            return;
 3820        }
 3821
 3822        let reason_description = reason.description();
 3823        let ignore_debounce = matches!(
 3824            reason,
 3825            InlayHintRefreshReason::SettingsChange(_)
 3826                | InlayHintRefreshReason::Toggle(_)
 3827                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3828                | InlayHintRefreshReason::ModifiersChanged(_)
 3829        );
 3830        let (invalidate_cache, required_languages) = match reason {
 3831            InlayHintRefreshReason::ModifiersChanged(enabled) => {
 3832                match self.inlay_hint_cache.modifiers_override(enabled) {
 3833                    Some(enabled) => {
 3834                        if enabled {
 3835                            (InvalidationStrategy::RefreshRequested, None)
 3836                        } else {
 3837                            self.splice_inlays(
 3838                                &self
 3839                                    .visible_inlay_hints(cx)
 3840                                    .iter()
 3841                                    .map(|inlay| inlay.id)
 3842                                    .collect::<Vec<InlayId>>(),
 3843                                Vec::new(),
 3844                                cx,
 3845                            );
 3846                            return;
 3847                        }
 3848                    }
 3849                    None => return,
 3850                }
 3851            }
 3852            InlayHintRefreshReason::Toggle(enabled) => {
 3853                if self.inlay_hint_cache.toggle(enabled) {
 3854                    if enabled {
 3855                        (InvalidationStrategy::RefreshRequested, None)
 3856                    } else {
 3857                        self.splice_inlays(
 3858                            &self
 3859                                .visible_inlay_hints(cx)
 3860                                .iter()
 3861                                .map(|inlay| inlay.id)
 3862                                .collect::<Vec<InlayId>>(),
 3863                            Vec::new(),
 3864                            cx,
 3865                        );
 3866                        return;
 3867                    }
 3868                } else {
 3869                    return;
 3870                }
 3871            }
 3872            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3873                match self.inlay_hint_cache.update_settings(
 3874                    &self.buffer,
 3875                    new_settings,
 3876                    self.visible_inlay_hints(cx),
 3877                    cx,
 3878                ) {
 3879                    ControlFlow::Break(Some(InlaySplice {
 3880                        to_remove,
 3881                        to_insert,
 3882                    })) => {
 3883                        self.splice_inlays(&to_remove, to_insert, cx);
 3884                        return;
 3885                    }
 3886                    ControlFlow::Break(None) => return,
 3887                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3888                }
 3889            }
 3890            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3891                if let Some(InlaySplice {
 3892                    to_remove,
 3893                    to_insert,
 3894                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3895                {
 3896                    self.splice_inlays(&to_remove, to_insert, cx);
 3897                }
 3898                return;
 3899            }
 3900            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3901            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3902                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3903            }
 3904            InlayHintRefreshReason::RefreshRequested => {
 3905                (InvalidationStrategy::RefreshRequested, None)
 3906            }
 3907        };
 3908
 3909        if let Some(InlaySplice {
 3910            to_remove,
 3911            to_insert,
 3912        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3913            reason_description,
 3914            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3915            invalidate_cache,
 3916            ignore_debounce,
 3917            cx,
 3918        ) {
 3919            self.splice_inlays(&to_remove, to_insert, cx);
 3920        }
 3921    }
 3922
 3923    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3924        self.display_map
 3925            .read(cx)
 3926            .current_inlays()
 3927            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3928            .cloned()
 3929            .collect()
 3930    }
 3931
 3932    pub fn excerpts_for_inlay_hints_query(
 3933        &self,
 3934        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3935        cx: &mut Context<Editor>,
 3936    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3937        let Some(project) = self.project.as_ref() else {
 3938            return HashMap::default();
 3939        };
 3940        let project = project.read(cx);
 3941        let multi_buffer = self.buffer().read(cx);
 3942        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3943        let multi_buffer_visible_start = self
 3944            .scroll_manager
 3945            .anchor()
 3946            .anchor
 3947            .to_point(&multi_buffer_snapshot);
 3948        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3949            multi_buffer_visible_start
 3950                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3951            Bias::Left,
 3952        );
 3953        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3954        multi_buffer_snapshot
 3955            .range_to_buffer_ranges(multi_buffer_visible_range)
 3956            .into_iter()
 3957            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3958            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3959                let buffer_file = project::File::from_dyn(buffer.file())?;
 3960                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3961                let worktree_entry = buffer_worktree
 3962                    .read(cx)
 3963                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3964                if worktree_entry.is_ignored {
 3965                    return None;
 3966                }
 3967
 3968                let language = buffer.language()?;
 3969                if let Some(restrict_to_languages) = restrict_to_languages {
 3970                    if !restrict_to_languages.contains(language) {
 3971                        return None;
 3972                    }
 3973                }
 3974                Some((
 3975                    excerpt_id,
 3976                    (
 3977                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3978                        buffer.version().clone(),
 3979                        excerpt_visible_range,
 3980                    ),
 3981                ))
 3982            })
 3983            .collect()
 3984    }
 3985
 3986    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3987        TextLayoutDetails {
 3988            text_system: window.text_system().clone(),
 3989            editor_style: self.style.clone().unwrap(),
 3990            rem_size: window.rem_size(),
 3991            scroll_anchor: self.scroll_manager.anchor(),
 3992            visible_rows: self.visible_line_count(),
 3993            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3994        }
 3995    }
 3996
 3997    pub fn splice_inlays(
 3998        &self,
 3999        to_remove: &[InlayId],
 4000        to_insert: Vec<Inlay>,
 4001        cx: &mut Context<Self>,
 4002    ) {
 4003        self.display_map.update(cx, |display_map, cx| {
 4004            display_map.splice_inlays(to_remove, to_insert, cx)
 4005        });
 4006        cx.notify();
 4007    }
 4008
 4009    fn trigger_on_type_formatting(
 4010        &self,
 4011        input: String,
 4012        window: &mut Window,
 4013        cx: &mut Context<Self>,
 4014    ) -> Option<Task<Result<()>>> {
 4015        if input.len() != 1 {
 4016            return None;
 4017        }
 4018
 4019        let project = self.project.as_ref()?;
 4020        let position = self.selections.newest_anchor().head();
 4021        let (buffer, buffer_position) = self
 4022            .buffer
 4023            .read(cx)
 4024            .text_anchor_for_position(position, cx)?;
 4025
 4026        let settings = language_settings::language_settings(
 4027            buffer
 4028                .read(cx)
 4029                .language_at(buffer_position)
 4030                .map(|l| l.name()),
 4031            buffer.read(cx).file(),
 4032            cx,
 4033        );
 4034        if !settings.use_on_type_format {
 4035            return None;
 4036        }
 4037
 4038        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4039        // hence we do LSP request & edit on host side only — add formats to host's history.
 4040        let push_to_lsp_host_history = true;
 4041        // If this is not the host, append its history with new edits.
 4042        let push_to_client_history = project.read(cx).is_via_collab();
 4043
 4044        let on_type_formatting = project.update(cx, |project, cx| {
 4045            project.on_type_format(
 4046                buffer.clone(),
 4047                buffer_position,
 4048                input,
 4049                push_to_lsp_host_history,
 4050                cx,
 4051            )
 4052        });
 4053        Some(cx.spawn_in(window, async move |editor, cx| {
 4054            if let Some(transaction) = on_type_formatting.await? {
 4055                if push_to_client_history {
 4056                    buffer
 4057                        .update(cx, |buffer, _| {
 4058                            buffer.push_transaction(transaction, Instant::now());
 4059                        })
 4060                        .ok();
 4061                }
 4062                editor.update(cx, |editor, cx| {
 4063                    editor.refresh_document_highlights(cx);
 4064                })?;
 4065            }
 4066            Ok(())
 4067        }))
 4068    }
 4069
 4070    pub fn show_word_completions(
 4071        &mut self,
 4072        _: &ShowWordCompletions,
 4073        window: &mut Window,
 4074        cx: &mut Context<Self>,
 4075    ) {
 4076        self.open_completions_menu(true, None, window, cx);
 4077    }
 4078
 4079    pub fn show_completions(
 4080        &mut self,
 4081        options: &ShowCompletions,
 4082        window: &mut Window,
 4083        cx: &mut Context<Self>,
 4084    ) {
 4085        self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
 4086    }
 4087
 4088    fn open_completions_menu(
 4089        &mut self,
 4090        ignore_completion_provider: bool,
 4091        trigger: Option<&str>,
 4092        window: &mut Window,
 4093        cx: &mut Context<Self>,
 4094    ) {
 4095        if self.pending_rename.is_some() {
 4096            return;
 4097        }
 4098        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 4099            return;
 4100        }
 4101
 4102        let position = self.selections.newest_anchor().head();
 4103        if position.diff_base_anchor.is_some() {
 4104            return;
 4105        }
 4106        let (buffer, buffer_position) =
 4107            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4108                output
 4109            } else {
 4110                return;
 4111            };
 4112        let buffer_snapshot = buffer.read(cx).snapshot();
 4113        let show_completion_documentation = buffer_snapshot
 4114            .settings_at(buffer_position, cx)
 4115            .show_completion_documentation;
 4116
 4117        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4118
 4119        let trigger_kind = match trigger {
 4120            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4121                CompletionTriggerKind::TRIGGER_CHARACTER
 4122            }
 4123            _ => CompletionTriggerKind::INVOKED,
 4124        };
 4125        let completion_context = CompletionContext {
 4126            trigger_character: trigger.and_then(|trigger| {
 4127                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4128                    Some(String::from(trigger))
 4129                } else {
 4130                    None
 4131                }
 4132            }),
 4133            trigger_kind,
 4134        };
 4135
 4136        let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
 4137        let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
 4138            let word_to_exclude = buffer_snapshot
 4139                .text_for_range(old_range.clone())
 4140                .collect::<String>();
 4141            (
 4142                buffer_snapshot.anchor_before(old_range.start)
 4143                    ..buffer_snapshot.anchor_after(old_range.end),
 4144                Some(word_to_exclude),
 4145            )
 4146        } else {
 4147            (buffer_position..buffer_position, None)
 4148        };
 4149
 4150        let completion_settings = language_settings(
 4151            buffer_snapshot
 4152                .language_at(buffer_position)
 4153                .map(|language| language.name()),
 4154            buffer_snapshot.file(),
 4155            cx,
 4156        )
 4157        .completions;
 4158
 4159        // The document can be large, so stay in reasonable bounds when searching for words,
 4160        // otherwise completion pop-up might be slow to appear.
 4161        const WORD_LOOKUP_ROWS: u32 = 5_000;
 4162        let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
 4163        let min_word_search = buffer_snapshot.clip_point(
 4164            Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
 4165            Bias::Left,
 4166        );
 4167        let max_word_search = buffer_snapshot.clip_point(
 4168            Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
 4169            Bias::Right,
 4170        );
 4171        let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
 4172            ..buffer_snapshot.point_to_offset(max_word_search);
 4173
 4174        let provider = self
 4175            .completion_provider
 4176            .as_ref()
 4177            .filter(|_| !ignore_completion_provider);
 4178        let skip_digits = query
 4179            .as_ref()
 4180            .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
 4181
 4182        let (mut words, provided_completions) = match provider {
 4183            Some(provider) => {
 4184                let completions =
 4185                    provider.completions(&buffer, buffer_position, completion_context, window, cx);
 4186
 4187                let words = match completion_settings.words {
 4188                    WordsCompletionMode::Disabled => Task::ready(HashMap::default()),
 4189                    WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
 4190                        .background_spawn(async move {
 4191                            buffer_snapshot.words_in_range(WordsQuery {
 4192                                fuzzy_contents: None,
 4193                                range: word_search_range,
 4194                                skip_digits,
 4195                            })
 4196                        }),
 4197                };
 4198
 4199                (words, completions)
 4200            }
 4201            None => (
 4202                cx.background_spawn(async move {
 4203                    buffer_snapshot.words_in_range(WordsQuery {
 4204                        fuzzy_contents: None,
 4205                        range: word_search_range,
 4206                        skip_digits,
 4207                    })
 4208                }),
 4209                Task::ready(Ok(None)),
 4210            ),
 4211        };
 4212
 4213        let sort_completions = provider
 4214            .as_ref()
 4215            .map_or(true, |provider| provider.sort_completions());
 4216
 4217        let id = post_inc(&mut self.next_completion_id);
 4218        let task = cx.spawn_in(window, async move |editor, cx| {
 4219            async move {
 4220                editor.update(cx, |this, _| {
 4221                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4222                })?;
 4223
 4224                let mut completions = Vec::new();
 4225                if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
 4226                    completions.extend(provided_completions);
 4227                    if completion_settings.words == WordsCompletionMode::Fallback {
 4228                        words = Task::ready(HashMap::default());
 4229                    }
 4230                }
 4231
 4232                let mut words = words.await;
 4233                if let Some(word_to_exclude) = &word_to_exclude {
 4234                    words.remove(word_to_exclude);
 4235                }
 4236                for lsp_completion in &completions {
 4237                    words.remove(&lsp_completion.new_text);
 4238                }
 4239                completions.extend(words.into_iter().map(|(word, word_range)| Completion {
 4240                    old_range: old_range.clone(),
 4241                    new_text: word.clone(),
 4242                    label: CodeLabel::plain(word, None),
 4243                    documentation: None,
 4244                    source: CompletionSource::BufferWord {
 4245                        word_range,
 4246                        resolved: false,
 4247                    },
 4248                    confirm: None,
 4249                }));
 4250
 4251                let menu = if completions.is_empty() {
 4252                    None
 4253                } else {
 4254                    let mut menu = CompletionsMenu::new(
 4255                        id,
 4256                        sort_completions,
 4257                        show_completion_documentation,
 4258                        ignore_completion_provider,
 4259                        position,
 4260                        buffer.clone(),
 4261                        completions.into(),
 4262                    );
 4263
 4264                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4265                        .await;
 4266
 4267                    menu.visible().then_some(menu)
 4268                };
 4269
 4270                editor.update_in(cx, |editor, window, cx| {
 4271                    match editor.context_menu.borrow().as_ref() {
 4272                        None => {}
 4273                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4274                            if prev_menu.id > id {
 4275                                return;
 4276                            }
 4277                        }
 4278                        _ => return,
 4279                    }
 4280
 4281                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4282                        let mut menu = menu.unwrap();
 4283                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4284
 4285                        *editor.context_menu.borrow_mut() =
 4286                            Some(CodeContextMenu::Completions(menu));
 4287
 4288                        if editor.show_edit_predictions_in_menu() {
 4289                            editor.update_visible_inline_completion(window, cx);
 4290                        } else {
 4291                            editor.discard_inline_completion(false, cx);
 4292                        }
 4293
 4294                        cx.notify();
 4295                    } else if editor.completion_tasks.len() <= 1 {
 4296                        // If there are no more completion tasks and the last menu was
 4297                        // empty, we should hide it.
 4298                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4299                        // If it was already hidden and we don't show inline
 4300                        // completions in the menu, we should also show the
 4301                        // inline-completion when available.
 4302                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4303                            editor.update_visible_inline_completion(window, cx);
 4304                        }
 4305                    }
 4306                })?;
 4307
 4308                anyhow::Ok(())
 4309            }
 4310            .log_err()
 4311            .await
 4312        });
 4313
 4314        self.completion_tasks.push((id, task));
 4315    }
 4316
 4317    pub fn confirm_completion(
 4318        &mut self,
 4319        action: &ConfirmCompletion,
 4320        window: &mut Window,
 4321        cx: &mut Context<Self>,
 4322    ) -> Option<Task<Result<()>>> {
 4323        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4324    }
 4325
 4326    pub fn compose_completion(
 4327        &mut self,
 4328        action: &ComposeCompletion,
 4329        window: &mut Window,
 4330        cx: &mut Context<Self>,
 4331    ) -> Option<Task<Result<()>>> {
 4332        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4333    }
 4334
 4335    fn do_completion(
 4336        &mut self,
 4337        item_ix: Option<usize>,
 4338        intent: CompletionIntent,
 4339        window: &mut Window,
 4340        cx: &mut Context<Editor>,
 4341    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4342        use language::ToOffset as _;
 4343
 4344        let completions_menu =
 4345            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4346                menu
 4347            } else {
 4348                return None;
 4349            };
 4350
 4351        let entries = completions_menu.entries.borrow();
 4352        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4353        if self.show_edit_predictions_in_menu() {
 4354            self.discard_inline_completion(true, cx);
 4355        }
 4356        let candidate_id = mat.candidate_id;
 4357        drop(entries);
 4358
 4359        let buffer_handle = completions_menu.buffer;
 4360        let completion = completions_menu
 4361            .completions
 4362            .borrow()
 4363            .get(candidate_id)?
 4364            .clone();
 4365        cx.stop_propagation();
 4366
 4367        let snippet;
 4368        let text;
 4369
 4370        if completion.is_snippet() {
 4371            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4372            text = snippet.as_ref().unwrap().text.clone();
 4373        } else {
 4374            snippet = None;
 4375            text = completion.new_text.clone();
 4376        };
 4377        let selections = self.selections.all::<usize>(cx);
 4378        let buffer = buffer_handle.read(cx);
 4379        let old_range = completion.old_range.to_offset(buffer);
 4380        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4381
 4382        let newest_selection = self.selections.newest_anchor();
 4383        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4384            return None;
 4385        }
 4386
 4387        let lookbehind = newest_selection
 4388            .start
 4389            .text_anchor
 4390            .to_offset(buffer)
 4391            .saturating_sub(old_range.start);
 4392        let lookahead = old_range
 4393            .end
 4394            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4395        let mut common_prefix_len = old_text
 4396            .bytes()
 4397            .zip(text.bytes())
 4398            .take_while(|(a, b)| a == b)
 4399            .count();
 4400
 4401        let snapshot = self.buffer.read(cx).snapshot(cx);
 4402        let mut range_to_replace: Option<Range<isize>> = None;
 4403        let mut ranges = Vec::new();
 4404        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4405        for selection in &selections {
 4406            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4407                let start = selection.start.saturating_sub(lookbehind);
 4408                let end = selection.end + lookahead;
 4409                if selection.id == newest_selection.id {
 4410                    range_to_replace = Some(
 4411                        ((start + common_prefix_len) as isize - selection.start as isize)
 4412                            ..(end as isize - selection.start as isize),
 4413                    );
 4414                }
 4415                ranges.push(start + common_prefix_len..end);
 4416            } else {
 4417                common_prefix_len = 0;
 4418                ranges.clear();
 4419                ranges.extend(selections.iter().map(|s| {
 4420                    if s.id == newest_selection.id {
 4421                        range_to_replace = Some(
 4422                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4423                                - selection.start as isize
 4424                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4425                                    - selection.start as isize,
 4426                        );
 4427                        old_range.clone()
 4428                    } else {
 4429                        s.start..s.end
 4430                    }
 4431                }));
 4432                break;
 4433            }
 4434            if !self.linked_edit_ranges.is_empty() {
 4435                let start_anchor = snapshot.anchor_before(selection.head());
 4436                let end_anchor = snapshot.anchor_after(selection.tail());
 4437                if let Some(ranges) = self
 4438                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4439                {
 4440                    for (buffer, edits) in ranges {
 4441                        linked_edits.entry(buffer.clone()).or_default().extend(
 4442                            edits
 4443                                .into_iter()
 4444                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4445                        );
 4446                    }
 4447                }
 4448            }
 4449        }
 4450        let text = &text[common_prefix_len..];
 4451
 4452        cx.emit(EditorEvent::InputHandled {
 4453            utf16_range_to_replace: range_to_replace,
 4454            text: text.into(),
 4455        });
 4456
 4457        self.transact(window, cx, |this, window, cx| {
 4458            if let Some(mut snippet) = snippet {
 4459                snippet.text = text.to_string();
 4460                for tabstop in snippet
 4461                    .tabstops
 4462                    .iter_mut()
 4463                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4464                {
 4465                    tabstop.start -= common_prefix_len as isize;
 4466                    tabstop.end -= common_prefix_len as isize;
 4467                }
 4468
 4469                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4470            } else {
 4471                this.buffer.update(cx, |buffer, cx| {
 4472                    buffer.edit(
 4473                        ranges.iter().map(|range| (range.clone(), text)),
 4474                        this.autoindent_mode.clone(),
 4475                        cx,
 4476                    );
 4477                });
 4478            }
 4479            for (buffer, edits) in linked_edits {
 4480                buffer.update(cx, |buffer, cx| {
 4481                    let snapshot = buffer.snapshot();
 4482                    let edits = edits
 4483                        .into_iter()
 4484                        .map(|(range, text)| {
 4485                            use text::ToPoint as TP;
 4486                            let end_point = TP::to_point(&range.end, &snapshot);
 4487                            let start_point = TP::to_point(&range.start, &snapshot);
 4488                            (start_point..end_point, text)
 4489                        })
 4490                        .sorted_by_key(|(range, _)| range.start)
 4491                        .collect::<Vec<_>>();
 4492                    buffer.edit(edits, None, cx);
 4493                })
 4494            }
 4495
 4496            this.refresh_inline_completion(true, false, window, cx);
 4497        });
 4498
 4499        let show_new_completions_on_confirm = completion
 4500            .confirm
 4501            .as_ref()
 4502            .map_or(false, |confirm| confirm(intent, window, cx));
 4503        if show_new_completions_on_confirm {
 4504            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4505        }
 4506
 4507        let provider = self.completion_provider.as_ref()?;
 4508        drop(completion);
 4509        let apply_edits = provider.apply_additional_edits_for_completion(
 4510            buffer_handle,
 4511            completions_menu.completions.clone(),
 4512            candidate_id,
 4513            true,
 4514            cx,
 4515        );
 4516
 4517        let editor_settings = EditorSettings::get_global(cx);
 4518        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4519            // After the code completion is finished, users often want to know what signatures are needed.
 4520            // so we should automatically call signature_help
 4521            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4522        }
 4523
 4524        Some(cx.foreground_executor().spawn(async move {
 4525            apply_edits.await?;
 4526            Ok(())
 4527        }))
 4528    }
 4529
 4530    pub fn toggle_code_actions(
 4531        &mut self,
 4532        action: &ToggleCodeActions,
 4533        window: &mut Window,
 4534        cx: &mut Context<Self>,
 4535    ) {
 4536        let mut context_menu = self.context_menu.borrow_mut();
 4537        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4538            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4539                // Toggle if we're selecting the same one
 4540                *context_menu = None;
 4541                cx.notify();
 4542                return;
 4543            } else {
 4544                // Otherwise, clear it and start a new one
 4545                *context_menu = None;
 4546                cx.notify();
 4547            }
 4548        }
 4549        drop(context_menu);
 4550        let snapshot = self.snapshot(window, cx);
 4551        let deployed_from_indicator = action.deployed_from_indicator;
 4552        let mut task = self.code_actions_task.take();
 4553        let action = action.clone();
 4554        cx.spawn_in(window, async move |editor, cx| {
 4555            while let Some(prev_task) = task {
 4556                prev_task.await.log_err();
 4557                task = editor.update(cx, |this, _| this.code_actions_task.take())?;
 4558            }
 4559
 4560            let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
 4561                if editor.focus_handle.is_focused(window) {
 4562                    let multibuffer_point = action
 4563                        .deployed_from_indicator
 4564                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4565                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4566                    let (buffer, buffer_row) = snapshot
 4567                        .buffer_snapshot
 4568                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4569                        .and_then(|(buffer_snapshot, range)| {
 4570                            editor
 4571                                .buffer
 4572                                .read(cx)
 4573                                .buffer(buffer_snapshot.remote_id())
 4574                                .map(|buffer| (buffer, range.start.row))
 4575                        })?;
 4576                    let (_, code_actions) = editor
 4577                        .available_code_actions
 4578                        .clone()
 4579                        .and_then(|(location, code_actions)| {
 4580                            let snapshot = location.buffer.read(cx).snapshot();
 4581                            let point_range = location.range.to_point(&snapshot);
 4582                            let point_range = point_range.start.row..=point_range.end.row;
 4583                            if point_range.contains(&buffer_row) {
 4584                                Some((location, code_actions))
 4585                            } else {
 4586                                None
 4587                            }
 4588                        })
 4589                        .unzip();
 4590                    let buffer_id = buffer.read(cx).remote_id();
 4591                    let tasks = editor
 4592                        .tasks
 4593                        .get(&(buffer_id, buffer_row))
 4594                        .map(|t| Arc::new(t.to_owned()));
 4595                    if tasks.is_none() && code_actions.is_none() {
 4596                        return None;
 4597                    }
 4598
 4599                    editor.completion_tasks.clear();
 4600                    editor.discard_inline_completion(false, cx);
 4601                    let task_context =
 4602                        tasks
 4603                            .as_ref()
 4604                            .zip(editor.project.clone())
 4605                            .map(|(tasks, project)| {
 4606                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4607                            });
 4608
 4609                    Some(cx.spawn_in(window, async move |editor, cx| {
 4610                        let task_context = match task_context {
 4611                            Some(task_context) => task_context.await,
 4612                            None => None,
 4613                        };
 4614                        let resolved_tasks =
 4615                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4616                                Rc::new(ResolvedTasks {
 4617                                    templates: tasks.resolve(&task_context).collect(),
 4618                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4619                                        multibuffer_point.row,
 4620                                        tasks.column,
 4621                                    )),
 4622                                })
 4623                            });
 4624                        let spawn_straight_away = resolved_tasks
 4625                            .as_ref()
 4626                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4627                            && code_actions
 4628                                .as_ref()
 4629                                .map_or(true, |actions| actions.is_empty());
 4630                        if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
 4631                            *editor.context_menu.borrow_mut() =
 4632                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4633                                    buffer,
 4634                                    actions: CodeActionContents {
 4635                                        tasks: resolved_tasks,
 4636                                        actions: code_actions,
 4637                                    },
 4638                                    selected_item: Default::default(),
 4639                                    scroll_handle: UniformListScrollHandle::default(),
 4640                                    deployed_from_indicator,
 4641                                }));
 4642                            if spawn_straight_away {
 4643                                if let Some(task) = editor.confirm_code_action(
 4644                                    &ConfirmCodeAction { item_ix: Some(0) },
 4645                                    window,
 4646                                    cx,
 4647                                ) {
 4648                                    cx.notify();
 4649                                    return task;
 4650                                }
 4651                            }
 4652                            cx.notify();
 4653                            Task::ready(Ok(()))
 4654                        }) {
 4655                            task.await
 4656                        } else {
 4657                            Ok(())
 4658                        }
 4659                    }))
 4660                } else {
 4661                    Some(Task::ready(Ok(())))
 4662                }
 4663            })?;
 4664            if let Some(task) = spawned_test_task {
 4665                task.await?;
 4666            }
 4667
 4668            Ok::<_, anyhow::Error>(())
 4669        })
 4670        .detach_and_log_err(cx);
 4671    }
 4672
 4673    pub fn confirm_code_action(
 4674        &mut self,
 4675        action: &ConfirmCodeAction,
 4676        window: &mut Window,
 4677        cx: &mut Context<Self>,
 4678    ) -> Option<Task<Result<()>>> {
 4679        let actions_menu =
 4680            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4681                menu
 4682            } else {
 4683                return None;
 4684            };
 4685        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4686        let action = actions_menu.actions.get(action_ix)?;
 4687        let title = action.label();
 4688        let buffer = actions_menu.buffer;
 4689        let workspace = self.workspace()?;
 4690
 4691        match action {
 4692            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4693                workspace.update(cx, |workspace, cx| {
 4694                    workspace::tasks::schedule_resolved_task(
 4695                        workspace,
 4696                        task_source_kind,
 4697                        resolved_task,
 4698                        false,
 4699                        cx,
 4700                    );
 4701
 4702                    Some(Task::ready(Ok(())))
 4703                })
 4704            }
 4705            CodeActionsItem::CodeAction {
 4706                excerpt_id,
 4707                action,
 4708                provider,
 4709            } => {
 4710                let apply_code_action =
 4711                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4712                let workspace = workspace.downgrade();
 4713                Some(cx.spawn_in(window, async move |editor, cx| {
 4714                    let project_transaction = apply_code_action.await?;
 4715                    Self::open_project_transaction(
 4716                        &editor,
 4717                        workspace,
 4718                        project_transaction,
 4719                        title,
 4720                        cx,
 4721                    )
 4722                    .await
 4723                }))
 4724            }
 4725        }
 4726    }
 4727
 4728    pub async fn open_project_transaction(
 4729        this: &WeakEntity<Editor>,
 4730        workspace: WeakEntity<Workspace>,
 4731        transaction: ProjectTransaction,
 4732        title: String,
 4733        cx: &mut AsyncWindowContext,
 4734    ) -> Result<()> {
 4735        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4736        cx.update(|_, cx| {
 4737            entries.sort_unstable_by_key(|(buffer, _)| {
 4738                buffer.read(cx).file().map(|f| f.path().clone())
 4739            });
 4740        })?;
 4741
 4742        // If the project transaction's edits are all contained within this editor, then
 4743        // avoid opening a new editor to display them.
 4744
 4745        if let Some((buffer, transaction)) = entries.first() {
 4746            if entries.len() == 1 {
 4747                let excerpt = this.update(cx, |editor, cx| {
 4748                    editor
 4749                        .buffer()
 4750                        .read(cx)
 4751                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4752                })?;
 4753                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4754                    if excerpted_buffer == *buffer {
 4755                        let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
 4756                            let excerpt_range = excerpt_range.to_offset(buffer);
 4757                            buffer
 4758                                .edited_ranges_for_transaction::<usize>(transaction)
 4759                                .all(|range| {
 4760                                    excerpt_range.start <= range.start
 4761                                        && excerpt_range.end >= range.end
 4762                                })
 4763                        })?;
 4764
 4765                        if all_edits_within_excerpt {
 4766                            return Ok(());
 4767                        }
 4768                    }
 4769                }
 4770            }
 4771        } else {
 4772            return Ok(());
 4773        }
 4774
 4775        let mut ranges_to_highlight = Vec::new();
 4776        let excerpt_buffer = cx.new(|cx| {
 4777            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4778            for (buffer_handle, transaction) in &entries {
 4779                let buffer = buffer_handle.read(cx);
 4780                ranges_to_highlight.extend(
 4781                    multibuffer.push_excerpts_with_context_lines(
 4782                        buffer_handle.clone(),
 4783                        buffer
 4784                            .edited_ranges_for_transaction::<usize>(transaction)
 4785                            .collect(),
 4786                        DEFAULT_MULTIBUFFER_CONTEXT,
 4787                        cx,
 4788                    ),
 4789                );
 4790            }
 4791            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4792            multibuffer
 4793        })?;
 4794
 4795        workspace.update_in(cx, |workspace, window, cx| {
 4796            let project = workspace.project().clone();
 4797            let editor =
 4798                cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
 4799            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4800            editor.update(cx, |editor, cx| {
 4801                editor.highlight_background::<Self>(
 4802                    &ranges_to_highlight,
 4803                    |theme| theme.editor_highlighted_line_background,
 4804                    cx,
 4805                );
 4806            });
 4807        })?;
 4808
 4809        Ok(())
 4810    }
 4811
 4812    pub fn clear_code_action_providers(&mut self) {
 4813        self.code_action_providers.clear();
 4814        self.available_code_actions.take();
 4815    }
 4816
 4817    pub fn add_code_action_provider(
 4818        &mut self,
 4819        provider: Rc<dyn CodeActionProvider>,
 4820        window: &mut Window,
 4821        cx: &mut Context<Self>,
 4822    ) {
 4823        if self
 4824            .code_action_providers
 4825            .iter()
 4826            .any(|existing_provider| existing_provider.id() == provider.id())
 4827        {
 4828            return;
 4829        }
 4830
 4831        self.code_action_providers.push(provider);
 4832        self.refresh_code_actions(window, cx);
 4833    }
 4834
 4835    pub fn remove_code_action_provider(
 4836        &mut self,
 4837        id: Arc<str>,
 4838        window: &mut Window,
 4839        cx: &mut Context<Self>,
 4840    ) {
 4841        self.code_action_providers
 4842            .retain(|provider| provider.id() != id);
 4843        self.refresh_code_actions(window, cx);
 4844    }
 4845
 4846    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4847        let buffer = self.buffer.read(cx);
 4848        let newest_selection = self.selections.newest_anchor().clone();
 4849        if newest_selection.head().diff_base_anchor.is_some() {
 4850            return None;
 4851        }
 4852        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4853        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4854        if start_buffer != end_buffer {
 4855            return None;
 4856        }
 4857
 4858        self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
 4859            cx.background_executor()
 4860                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4861                .await;
 4862
 4863            let (providers, tasks) = this.update_in(cx, |this, window, cx| {
 4864                let providers = this.code_action_providers.clone();
 4865                let tasks = this
 4866                    .code_action_providers
 4867                    .iter()
 4868                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4869                    .collect::<Vec<_>>();
 4870                (providers, tasks)
 4871            })?;
 4872
 4873            let mut actions = Vec::new();
 4874            for (provider, provider_actions) in
 4875                providers.into_iter().zip(future::join_all(tasks).await)
 4876            {
 4877                if let Some(provider_actions) = provider_actions.log_err() {
 4878                    actions.extend(provider_actions.into_iter().map(|action| {
 4879                        AvailableCodeAction {
 4880                            excerpt_id: newest_selection.start.excerpt_id,
 4881                            action,
 4882                            provider: provider.clone(),
 4883                        }
 4884                    }));
 4885                }
 4886            }
 4887
 4888            this.update(cx, |this, cx| {
 4889                this.available_code_actions = if actions.is_empty() {
 4890                    None
 4891                } else {
 4892                    Some((
 4893                        Location {
 4894                            buffer: start_buffer,
 4895                            range: start..end,
 4896                        },
 4897                        actions.into(),
 4898                    ))
 4899                };
 4900                cx.notify();
 4901            })
 4902        }));
 4903        None
 4904    }
 4905
 4906    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4907        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4908            self.show_git_blame_inline = false;
 4909
 4910            self.show_git_blame_inline_delay_task =
 4911                Some(cx.spawn_in(window, async move |this, cx| {
 4912                    cx.background_executor().timer(delay).await;
 4913
 4914                    this.update(cx, |this, cx| {
 4915                        this.show_git_blame_inline = true;
 4916                        cx.notify();
 4917                    })
 4918                    .log_err();
 4919                }));
 4920        }
 4921    }
 4922
 4923    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4924        if self.pending_rename.is_some() {
 4925            return None;
 4926        }
 4927
 4928        let provider = self.semantics_provider.clone()?;
 4929        let buffer = self.buffer.read(cx);
 4930        let newest_selection = self.selections.newest_anchor().clone();
 4931        let cursor_position = newest_selection.head();
 4932        let (cursor_buffer, cursor_buffer_position) =
 4933            buffer.text_anchor_for_position(cursor_position, cx)?;
 4934        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4935        if cursor_buffer != tail_buffer {
 4936            return None;
 4937        }
 4938        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4939        self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
 4940            cx.background_executor()
 4941                .timer(Duration::from_millis(debounce))
 4942                .await;
 4943
 4944            let highlights = if let Some(highlights) = cx
 4945                .update(|cx| {
 4946                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4947                })
 4948                .ok()
 4949                .flatten()
 4950            {
 4951                highlights.await.log_err()
 4952            } else {
 4953                None
 4954            };
 4955
 4956            if let Some(highlights) = highlights {
 4957                this.update(cx, |this, cx| {
 4958                    if this.pending_rename.is_some() {
 4959                        return;
 4960                    }
 4961
 4962                    let buffer_id = cursor_position.buffer_id;
 4963                    let buffer = this.buffer.read(cx);
 4964                    if !buffer
 4965                        .text_anchor_for_position(cursor_position, cx)
 4966                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4967                    {
 4968                        return;
 4969                    }
 4970
 4971                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4972                    let mut write_ranges = Vec::new();
 4973                    let mut read_ranges = Vec::new();
 4974                    for highlight in highlights {
 4975                        for (excerpt_id, excerpt_range) in
 4976                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4977                        {
 4978                            let start = highlight
 4979                                .range
 4980                                .start
 4981                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4982                            let end = highlight
 4983                                .range
 4984                                .end
 4985                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4986                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4987                                continue;
 4988                            }
 4989
 4990                            let range = Anchor {
 4991                                buffer_id,
 4992                                excerpt_id,
 4993                                text_anchor: start,
 4994                                diff_base_anchor: None,
 4995                            }..Anchor {
 4996                                buffer_id,
 4997                                excerpt_id,
 4998                                text_anchor: end,
 4999                                diff_base_anchor: None,
 5000                            };
 5001                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5002                                write_ranges.push(range);
 5003                            } else {
 5004                                read_ranges.push(range);
 5005                            }
 5006                        }
 5007                    }
 5008
 5009                    this.highlight_background::<DocumentHighlightRead>(
 5010                        &read_ranges,
 5011                        |theme| theme.editor_document_highlight_read_background,
 5012                        cx,
 5013                    );
 5014                    this.highlight_background::<DocumentHighlightWrite>(
 5015                        &write_ranges,
 5016                        |theme| theme.editor_document_highlight_write_background,
 5017                        cx,
 5018                    );
 5019                    cx.notify();
 5020                })
 5021                .log_err();
 5022            }
 5023        }));
 5024        None
 5025    }
 5026
 5027    pub fn refresh_selected_text_highlights(
 5028        &mut self,
 5029        window: &mut Window,
 5030        cx: &mut Context<Editor>,
 5031    ) {
 5032        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 5033            return;
 5034        }
 5035        self.selection_highlight_task.take();
 5036        if !EditorSettings::get_global(cx).selection_highlight {
 5037            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5038            return;
 5039        }
 5040        if self.selections.count() != 1 || self.selections.line_mode {
 5041            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5042            return;
 5043        }
 5044        let selection = self.selections.newest::<Point>(cx);
 5045        if selection.is_empty() || selection.start.row != selection.end.row {
 5046            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5047            return;
 5048        }
 5049        let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
 5050        self.selection_highlight_task = Some(cx.spawn_in(window, async move |editor, cx| {
 5051            cx.background_executor()
 5052                .timer(Duration::from_millis(debounce))
 5053                .await;
 5054            let Some(Some(matches_task)) = editor
 5055                .update_in(cx, |editor, _, cx| {
 5056                    if editor.selections.count() != 1 || editor.selections.line_mode {
 5057                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5058                        return None;
 5059                    }
 5060                    let selection = editor.selections.newest::<Point>(cx);
 5061                    if selection.is_empty() || selection.start.row != selection.end.row {
 5062                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5063                        return None;
 5064                    }
 5065                    let buffer = editor.buffer().read(cx).snapshot(cx);
 5066                    let query = buffer.text_for_range(selection.range()).collect::<String>();
 5067                    if query.trim().is_empty() {
 5068                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5069                        return None;
 5070                    }
 5071                    Some(cx.background_spawn(async move {
 5072                        let mut ranges = Vec::new();
 5073                        let selection_anchors = selection.range().to_anchors(&buffer);
 5074                        for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
 5075                            for (search_buffer, search_range, excerpt_id) in
 5076                                buffer.range_to_buffer_ranges(range)
 5077                            {
 5078                                ranges.extend(
 5079                                    project::search::SearchQuery::text(
 5080                                        query.clone(),
 5081                                        false,
 5082                                        false,
 5083                                        false,
 5084                                        Default::default(),
 5085                                        Default::default(),
 5086                                        None,
 5087                                    )
 5088                                    .unwrap()
 5089                                    .search(search_buffer, Some(search_range.clone()))
 5090                                    .await
 5091                                    .into_iter()
 5092                                    .filter_map(
 5093                                        |match_range| {
 5094                                            let start = search_buffer.anchor_after(
 5095                                                search_range.start + match_range.start,
 5096                                            );
 5097                                            let end = search_buffer.anchor_before(
 5098                                                search_range.start + match_range.end,
 5099                                            );
 5100                                            let range = Anchor::range_in_buffer(
 5101                                                excerpt_id,
 5102                                                search_buffer.remote_id(),
 5103                                                start..end,
 5104                                            );
 5105                                            (range != selection_anchors).then_some(range)
 5106                                        },
 5107                                    ),
 5108                                );
 5109                            }
 5110                        }
 5111                        ranges
 5112                    }))
 5113                })
 5114                .log_err()
 5115            else {
 5116                return;
 5117            };
 5118            let matches = matches_task.await;
 5119            editor
 5120                .update_in(cx, |editor, _, cx| {
 5121                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5122                    if !matches.is_empty() {
 5123                        editor.highlight_background::<SelectedTextHighlight>(
 5124                            &matches,
 5125                            |theme| theme.editor_document_highlight_bracket_background,
 5126                            cx,
 5127                        )
 5128                    }
 5129                })
 5130                .log_err();
 5131        }));
 5132    }
 5133
 5134    pub fn refresh_inline_completion(
 5135        &mut self,
 5136        debounce: bool,
 5137        user_requested: bool,
 5138        window: &mut Window,
 5139        cx: &mut Context<Self>,
 5140    ) -> Option<()> {
 5141        let provider = self.edit_prediction_provider()?;
 5142        let cursor = self.selections.newest_anchor().head();
 5143        let (buffer, cursor_buffer_position) =
 5144            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5145
 5146        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 5147            self.discard_inline_completion(false, cx);
 5148            return None;
 5149        }
 5150
 5151        if !user_requested
 5152            && (!self.should_show_edit_predictions()
 5153                || !self.is_focused(window)
 5154                || buffer.read(cx).is_empty())
 5155        {
 5156            self.discard_inline_completion(false, cx);
 5157            return None;
 5158        }
 5159
 5160        self.update_visible_inline_completion(window, cx);
 5161        provider.refresh(
 5162            self.project.clone(),
 5163            buffer,
 5164            cursor_buffer_position,
 5165            debounce,
 5166            cx,
 5167        );
 5168        Some(())
 5169    }
 5170
 5171    fn show_edit_predictions_in_menu(&self) -> bool {
 5172        match self.edit_prediction_settings {
 5173            EditPredictionSettings::Disabled => false,
 5174            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 5175        }
 5176    }
 5177
 5178    pub fn edit_predictions_enabled(&self) -> bool {
 5179        match self.edit_prediction_settings {
 5180            EditPredictionSettings::Disabled => false,
 5181            EditPredictionSettings::Enabled { .. } => true,
 5182        }
 5183    }
 5184
 5185    fn edit_prediction_requires_modifier(&self) -> bool {
 5186        match self.edit_prediction_settings {
 5187            EditPredictionSettings::Disabled => false,
 5188            EditPredictionSettings::Enabled {
 5189                preview_requires_modifier,
 5190                ..
 5191            } => preview_requires_modifier,
 5192        }
 5193    }
 5194
 5195    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 5196        if self.edit_prediction_provider.is_none() {
 5197            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5198        } else {
 5199            let selection = self.selections.newest_anchor();
 5200            let cursor = selection.head();
 5201
 5202            if let Some((buffer, cursor_buffer_position)) =
 5203                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5204            {
 5205                self.edit_prediction_settings =
 5206                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5207            }
 5208        }
 5209    }
 5210
 5211    fn edit_prediction_settings_at_position(
 5212        &self,
 5213        buffer: &Entity<Buffer>,
 5214        buffer_position: language::Anchor,
 5215        cx: &App,
 5216    ) -> EditPredictionSettings {
 5217        if self.mode != EditorMode::Full
 5218            || !self.show_inline_completions_override.unwrap_or(true)
 5219            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 5220        {
 5221            return EditPredictionSettings::Disabled;
 5222        }
 5223
 5224        let buffer = buffer.read(cx);
 5225
 5226        let file = buffer.file();
 5227
 5228        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 5229            return EditPredictionSettings::Disabled;
 5230        };
 5231
 5232        let by_provider = matches!(
 5233            self.menu_inline_completions_policy,
 5234            MenuInlineCompletionsPolicy::ByProvider
 5235        );
 5236
 5237        let show_in_menu = by_provider
 5238            && self
 5239                .edit_prediction_provider
 5240                .as_ref()
 5241                .map_or(false, |provider| {
 5242                    provider.provider.show_completions_in_menu()
 5243                });
 5244
 5245        let preview_requires_modifier =
 5246            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 5247
 5248        EditPredictionSettings::Enabled {
 5249            show_in_menu,
 5250            preview_requires_modifier,
 5251        }
 5252    }
 5253
 5254    fn should_show_edit_predictions(&self) -> bool {
 5255        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 5256    }
 5257
 5258    pub fn edit_prediction_preview_is_active(&self) -> bool {
 5259        matches!(
 5260            self.edit_prediction_preview,
 5261            EditPredictionPreview::Active { .. }
 5262        )
 5263    }
 5264
 5265    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 5266        let cursor = self.selections.newest_anchor().head();
 5267        if let Some((buffer, cursor_position)) =
 5268            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5269        {
 5270            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 5271        } else {
 5272            false
 5273        }
 5274    }
 5275
 5276    fn edit_predictions_enabled_in_buffer(
 5277        &self,
 5278        buffer: &Entity<Buffer>,
 5279        buffer_position: language::Anchor,
 5280        cx: &App,
 5281    ) -> bool {
 5282        maybe!({
 5283            if self.read_only(cx) {
 5284                return Some(false);
 5285            }
 5286            let provider = self.edit_prediction_provider()?;
 5287            if !provider.is_enabled(&buffer, buffer_position, cx) {
 5288                return Some(false);
 5289            }
 5290            let buffer = buffer.read(cx);
 5291            let Some(file) = buffer.file() else {
 5292                return Some(true);
 5293            };
 5294            let settings = all_language_settings(Some(file), cx);
 5295            Some(settings.edit_predictions_enabled_for_file(file, cx))
 5296        })
 5297        .unwrap_or(false)
 5298    }
 5299
 5300    fn cycle_inline_completion(
 5301        &mut self,
 5302        direction: Direction,
 5303        window: &mut Window,
 5304        cx: &mut Context<Self>,
 5305    ) -> Option<()> {
 5306        let provider = self.edit_prediction_provider()?;
 5307        let cursor = self.selections.newest_anchor().head();
 5308        let (buffer, cursor_buffer_position) =
 5309            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5310        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 5311            return None;
 5312        }
 5313
 5314        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5315        self.update_visible_inline_completion(window, cx);
 5316
 5317        Some(())
 5318    }
 5319
 5320    pub fn show_inline_completion(
 5321        &mut self,
 5322        _: &ShowEditPrediction,
 5323        window: &mut Window,
 5324        cx: &mut Context<Self>,
 5325    ) {
 5326        if !self.has_active_inline_completion() {
 5327            self.refresh_inline_completion(false, true, window, cx);
 5328            return;
 5329        }
 5330
 5331        self.update_visible_inline_completion(window, cx);
 5332    }
 5333
 5334    pub fn display_cursor_names(
 5335        &mut self,
 5336        _: &DisplayCursorNames,
 5337        window: &mut Window,
 5338        cx: &mut Context<Self>,
 5339    ) {
 5340        self.show_cursor_names(window, cx);
 5341    }
 5342
 5343    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5344        self.show_cursor_names = true;
 5345        cx.notify();
 5346        cx.spawn_in(window, async move |this, cx| {
 5347            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5348            this.update(cx, |this, cx| {
 5349                this.show_cursor_names = false;
 5350                cx.notify()
 5351            })
 5352            .ok()
 5353        })
 5354        .detach();
 5355    }
 5356
 5357    pub fn next_edit_prediction(
 5358        &mut self,
 5359        _: &NextEditPrediction,
 5360        window: &mut Window,
 5361        cx: &mut Context<Self>,
 5362    ) {
 5363        if self.has_active_inline_completion() {
 5364            self.cycle_inline_completion(Direction::Next, window, cx);
 5365        } else {
 5366            let is_copilot_disabled = self
 5367                .refresh_inline_completion(false, true, window, cx)
 5368                .is_none();
 5369            if is_copilot_disabled {
 5370                cx.propagate();
 5371            }
 5372        }
 5373    }
 5374
 5375    pub fn previous_edit_prediction(
 5376        &mut self,
 5377        _: &PreviousEditPrediction,
 5378        window: &mut Window,
 5379        cx: &mut Context<Self>,
 5380    ) {
 5381        if self.has_active_inline_completion() {
 5382            self.cycle_inline_completion(Direction::Prev, window, cx);
 5383        } else {
 5384            let is_copilot_disabled = self
 5385                .refresh_inline_completion(false, true, window, cx)
 5386                .is_none();
 5387            if is_copilot_disabled {
 5388                cx.propagate();
 5389            }
 5390        }
 5391    }
 5392
 5393    pub fn accept_edit_prediction(
 5394        &mut self,
 5395        _: &AcceptEditPrediction,
 5396        window: &mut Window,
 5397        cx: &mut Context<Self>,
 5398    ) {
 5399        if self.show_edit_predictions_in_menu() {
 5400            self.hide_context_menu(window, cx);
 5401        }
 5402
 5403        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5404            return;
 5405        };
 5406
 5407        self.report_inline_completion_event(
 5408            active_inline_completion.completion_id.clone(),
 5409            true,
 5410            cx,
 5411        );
 5412
 5413        match &active_inline_completion.completion {
 5414            InlineCompletion::Move { target, .. } => {
 5415                let target = *target;
 5416
 5417                if let Some(position_map) = &self.last_position_map {
 5418                    if position_map
 5419                        .visible_row_range
 5420                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5421                        || !self.edit_prediction_requires_modifier()
 5422                    {
 5423                        self.unfold_ranges(&[target..target], true, false, cx);
 5424                        // Note that this is also done in vim's handler of the Tab action.
 5425                        self.change_selections(
 5426                            Some(Autoscroll::newest()),
 5427                            window,
 5428                            cx,
 5429                            |selections| {
 5430                                selections.select_anchor_ranges([target..target]);
 5431                            },
 5432                        );
 5433                        self.clear_row_highlights::<EditPredictionPreview>();
 5434
 5435                        self.edit_prediction_preview
 5436                            .set_previous_scroll_position(None);
 5437                    } else {
 5438                        self.edit_prediction_preview
 5439                            .set_previous_scroll_position(Some(
 5440                                position_map.snapshot.scroll_anchor,
 5441                            ));
 5442
 5443                        self.highlight_rows::<EditPredictionPreview>(
 5444                            target..target,
 5445                            cx.theme().colors().editor_highlighted_line_background,
 5446                            true,
 5447                            cx,
 5448                        );
 5449                        self.request_autoscroll(Autoscroll::fit(), cx);
 5450                    }
 5451                }
 5452            }
 5453            InlineCompletion::Edit { edits, .. } => {
 5454                if let Some(provider) = self.edit_prediction_provider() {
 5455                    provider.accept(cx);
 5456                }
 5457
 5458                let snapshot = self.buffer.read(cx).snapshot(cx);
 5459                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5460
 5461                self.buffer.update(cx, |buffer, cx| {
 5462                    buffer.edit(edits.iter().cloned(), None, cx)
 5463                });
 5464
 5465                self.change_selections(None, window, cx, |s| {
 5466                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5467                });
 5468
 5469                self.update_visible_inline_completion(window, cx);
 5470                if self.active_inline_completion.is_none() {
 5471                    self.refresh_inline_completion(true, true, window, cx);
 5472                }
 5473
 5474                cx.notify();
 5475            }
 5476        }
 5477
 5478        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 5479    }
 5480
 5481    pub fn accept_partial_inline_completion(
 5482        &mut self,
 5483        _: &AcceptPartialEditPrediction,
 5484        window: &mut Window,
 5485        cx: &mut Context<Self>,
 5486    ) {
 5487        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5488            return;
 5489        };
 5490        if self.selections.count() != 1 {
 5491            return;
 5492        }
 5493
 5494        self.report_inline_completion_event(
 5495            active_inline_completion.completion_id.clone(),
 5496            true,
 5497            cx,
 5498        );
 5499
 5500        match &active_inline_completion.completion {
 5501            InlineCompletion::Move { target, .. } => {
 5502                let target = *target;
 5503                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5504                    selections.select_anchor_ranges([target..target]);
 5505                });
 5506            }
 5507            InlineCompletion::Edit { edits, .. } => {
 5508                // Find an insertion that starts at the cursor position.
 5509                let snapshot = self.buffer.read(cx).snapshot(cx);
 5510                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5511                let insertion = edits.iter().find_map(|(range, text)| {
 5512                    let range = range.to_offset(&snapshot);
 5513                    if range.is_empty() && range.start == cursor_offset {
 5514                        Some(text)
 5515                    } else {
 5516                        None
 5517                    }
 5518                });
 5519
 5520                if let Some(text) = insertion {
 5521                    let mut partial_completion = text
 5522                        .chars()
 5523                        .by_ref()
 5524                        .take_while(|c| c.is_alphabetic())
 5525                        .collect::<String>();
 5526                    if partial_completion.is_empty() {
 5527                        partial_completion = text
 5528                            .chars()
 5529                            .by_ref()
 5530                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5531                            .collect::<String>();
 5532                    }
 5533
 5534                    cx.emit(EditorEvent::InputHandled {
 5535                        utf16_range_to_replace: None,
 5536                        text: partial_completion.clone().into(),
 5537                    });
 5538
 5539                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5540
 5541                    self.refresh_inline_completion(true, true, window, cx);
 5542                    cx.notify();
 5543                } else {
 5544                    self.accept_edit_prediction(&Default::default(), window, cx);
 5545                }
 5546            }
 5547        }
 5548    }
 5549
 5550    fn discard_inline_completion(
 5551        &mut self,
 5552        should_report_inline_completion_event: bool,
 5553        cx: &mut Context<Self>,
 5554    ) -> bool {
 5555        if should_report_inline_completion_event {
 5556            let completion_id = self
 5557                .active_inline_completion
 5558                .as_ref()
 5559                .and_then(|active_completion| active_completion.completion_id.clone());
 5560
 5561            self.report_inline_completion_event(completion_id, false, cx);
 5562        }
 5563
 5564        if let Some(provider) = self.edit_prediction_provider() {
 5565            provider.discard(cx);
 5566        }
 5567
 5568        self.take_active_inline_completion(cx)
 5569    }
 5570
 5571    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5572        let Some(provider) = self.edit_prediction_provider() else {
 5573            return;
 5574        };
 5575
 5576        let Some((_, buffer, _)) = self
 5577            .buffer
 5578            .read(cx)
 5579            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5580        else {
 5581            return;
 5582        };
 5583
 5584        let extension = buffer
 5585            .read(cx)
 5586            .file()
 5587            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5588
 5589        let event_type = match accepted {
 5590            true => "Edit Prediction Accepted",
 5591            false => "Edit Prediction Discarded",
 5592        };
 5593        telemetry::event!(
 5594            event_type,
 5595            provider = provider.name(),
 5596            prediction_id = id,
 5597            suggestion_accepted = accepted,
 5598            file_extension = extension,
 5599        );
 5600    }
 5601
 5602    pub fn has_active_inline_completion(&self) -> bool {
 5603        self.active_inline_completion.is_some()
 5604    }
 5605
 5606    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5607        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5608            return false;
 5609        };
 5610
 5611        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5612        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5613        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5614        true
 5615    }
 5616
 5617    /// Returns true when we're displaying the edit prediction popover below the cursor
 5618    /// like we are not previewing and the LSP autocomplete menu is visible
 5619    /// or we are in `when_holding_modifier` mode.
 5620    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5621        if self.edit_prediction_preview_is_active()
 5622            || !self.show_edit_predictions_in_menu()
 5623            || !self.edit_predictions_enabled()
 5624        {
 5625            return false;
 5626        }
 5627
 5628        if self.has_visible_completions_menu() {
 5629            return true;
 5630        }
 5631
 5632        has_completion && self.edit_prediction_requires_modifier()
 5633    }
 5634
 5635    fn handle_modifiers_changed(
 5636        &mut self,
 5637        modifiers: Modifiers,
 5638        position_map: &PositionMap,
 5639        window: &mut Window,
 5640        cx: &mut Context<Self>,
 5641    ) {
 5642        if self.show_edit_predictions_in_menu() {
 5643            self.update_edit_prediction_preview(&modifiers, window, cx);
 5644        }
 5645
 5646        self.update_selection_mode(&modifiers, position_map, window, cx);
 5647
 5648        let mouse_position = window.mouse_position();
 5649        if !position_map.text_hitbox.is_hovered(window) {
 5650            return;
 5651        }
 5652
 5653        self.update_hovered_link(
 5654            position_map.point_for_position(mouse_position),
 5655            &position_map.snapshot,
 5656            modifiers,
 5657            window,
 5658            cx,
 5659        )
 5660    }
 5661
 5662    fn update_selection_mode(
 5663        &mut self,
 5664        modifiers: &Modifiers,
 5665        position_map: &PositionMap,
 5666        window: &mut Window,
 5667        cx: &mut Context<Self>,
 5668    ) {
 5669        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 5670            return;
 5671        }
 5672
 5673        let mouse_position = window.mouse_position();
 5674        let point_for_position = position_map.point_for_position(mouse_position);
 5675        let position = point_for_position.previous_valid;
 5676
 5677        self.select(
 5678            SelectPhase::BeginColumnar {
 5679                position,
 5680                reset: false,
 5681                goal_column: point_for_position.exact_unclipped.column(),
 5682            },
 5683            window,
 5684            cx,
 5685        );
 5686    }
 5687
 5688    fn update_edit_prediction_preview(
 5689        &mut self,
 5690        modifiers: &Modifiers,
 5691        window: &mut Window,
 5692        cx: &mut Context<Self>,
 5693    ) {
 5694        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5695        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5696            return;
 5697        };
 5698
 5699        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5700            if matches!(
 5701                self.edit_prediction_preview,
 5702                EditPredictionPreview::Inactive { .. }
 5703            ) {
 5704                self.edit_prediction_preview = EditPredictionPreview::Active {
 5705                    previous_scroll_position: None,
 5706                    since: Instant::now(),
 5707                };
 5708
 5709                self.update_visible_inline_completion(window, cx);
 5710                cx.notify();
 5711            }
 5712        } else if let EditPredictionPreview::Active {
 5713            previous_scroll_position,
 5714            since,
 5715        } = self.edit_prediction_preview
 5716        {
 5717            if let (Some(previous_scroll_position), Some(position_map)) =
 5718                (previous_scroll_position, self.last_position_map.as_ref())
 5719            {
 5720                self.set_scroll_position(
 5721                    previous_scroll_position
 5722                        .scroll_position(&position_map.snapshot.display_snapshot),
 5723                    window,
 5724                    cx,
 5725                );
 5726            }
 5727
 5728            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 5729                released_too_fast: since.elapsed() < Duration::from_millis(200),
 5730            };
 5731            self.clear_row_highlights::<EditPredictionPreview>();
 5732            self.update_visible_inline_completion(window, cx);
 5733            cx.notify();
 5734        }
 5735    }
 5736
 5737    fn update_visible_inline_completion(
 5738        &mut self,
 5739        _window: &mut Window,
 5740        cx: &mut Context<Self>,
 5741    ) -> Option<()> {
 5742        let selection = self.selections.newest_anchor();
 5743        let cursor = selection.head();
 5744        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5745        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5746        let excerpt_id = cursor.excerpt_id;
 5747
 5748        let show_in_menu = self.show_edit_predictions_in_menu();
 5749        let completions_menu_has_precedence = !show_in_menu
 5750            && (self.context_menu.borrow().is_some()
 5751                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5752
 5753        if completions_menu_has_precedence
 5754            || !offset_selection.is_empty()
 5755            || self
 5756                .active_inline_completion
 5757                .as_ref()
 5758                .map_or(false, |completion| {
 5759                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5760                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5761                    !invalidation_range.contains(&offset_selection.head())
 5762                })
 5763        {
 5764            self.discard_inline_completion(false, cx);
 5765            return None;
 5766        }
 5767
 5768        self.take_active_inline_completion(cx);
 5769        let Some(provider) = self.edit_prediction_provider() else {
 5770            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5771            return None;
 5772        };
 5773
 5774        let (buffer, cursor_buffer_position) =
 5775            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5776
 5777        self.edit_prediction_settings =
 5778            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5779
 5780        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 5781
 5782        if self.edit_prediction_indent_conflict {
 5783            let cursor_point = cursor.to_point(&multibuffer);
 5784
 5785            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 5786
 5787            if let Some((_, indent)) = indents.iter().next() {
 5788                if indent.len == cursor_point.column {
 5789                    self.edit_prediction_indent_conflict = false;
 5790                }
 5791            }
 5792        }
 5793
 5794        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5795        let edits = inline_completion
 5796            .edits
 5797            .into_iter()
 5798            .flat_map(|(range, new_text)| {
 5799                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5800                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5801                Some((start..end, new_text))
 5802            })
 5803            .collect::<Vec<_>>();
 5804        if edits.is_empty() {
 5805            return None;
 5806        }
 5807
 5808        let first_edit_start = edits.first().unwrap().0.start;
 5809        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5810        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5811
 5812        let last_edit_end = edits.last().unwrap().0.end;
 5813        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5814        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5815
 5816        let cursor_row = cursor.to_point(&multibuffer).row;
 5817
 5818        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5819
 5820        let mut inlay_ids = Vec::new();
 5821        let invalidation_row_range;
 5822        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5823            Some(cursor_row..edit_end_row)
 5824        } else if cursor_row > edit_end_row {
 5825            Some(edit_start_row..cursor_row)
 5826        } else {
 5827            None
 5828        };
 5829        let is_move =
 5830            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5831        let completion = if is_move {
 5832            invalidation_row_range =
 5833                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5834            let target = first_edit_start;
 5835            InlineCompletion::Move { target, snapshot }
 5836        } else {
 5837            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 5838                && !self.inline_completions_hidden_for_vim_mode;
 5839
 5840            if show_completions_in_buffer {
 5841                if edits
 5842                    .iter()
 5843                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5844                {
 5845                    let mut inlays = Vec::new();
 5846                    for (range, new_text) in &edits {
 5847                        let inlay = Inlay::inline_completion(
 5848                            post_inc(&mut self.next_inlay_id),
 5849                            range.start,
 5850                            new_text.as_str(),
 5851                        );
 5852                        inlay_ids.push(inlay.id);
 5853                        inlays.push(inlay);
 5854                    }
 5855
 5856                    self.splice_inlays(&[], inlays, cx);
 5857                } else {
 5858                    let background_color = cx.theme().status().deleted_background;
 5859                    self.highlight_text::<InlineCompletionHighlight>(
 5860                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5861                        HighlightStyle {
 5862                            background_color: Some(background_color),
 5863                            ..Default::default()
 5864                        },
 5865                        cx,
 5866                    );
 5867                }
 5868            }
 5869
 5870            invalidation_row_range = edit_start_row..edit_end_row;
 5871
 5872            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5873                if provider.show_tab_accept_marker() {
 5874                    EditDisplayMode::TabAccept
 5875                } else {
 5876                    EditDisplayMode::Inline
 5877                }
 5878            } else {
 5879                EditDisplayMode::DiffPopover
 5880            };
 5881
 5882            InlineCompletion::Edit {
 5883                edits,
 5884                edit_preview: inline_completion.edit_preview,
 5885                display_mode,
 5886                snapshot,
 5887            }
 5888        };
 5889
 5890        let invalidation_range = multibuffer
 5891            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5892            ..multibuffer.anchor_after(Point::new(
 5893                invalidation_row_range.end,
 5894                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5895            ));
 5896
 5897        self.stale_inline_completion_in_menu = None;
 5898        self.active_inline_completion = Some(InlineCompletionState {
 5899            inlay_ids,
 5900            completion,
 5901            completion_id: inline_completion.id,
 5902            invalidation_range,
 5903        });
 5904
 5905        cx.notify();
 5906
 5907        Some(())
 5908    }
 5909
 5910    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5911        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5912    }
 5913
 5914    fn render_code_actions_indicator(
 5915        &self,
 5916        _style: &EditorStyle,
 5917        row: DisplayRow,
 5918        is_active: bool,
 5919        breakpoint: Option<&(Anchor, Breakpoint)>,
 5920        cx: &mut Context<Self>,
 5921    ) -> Option<IconButton> {
 5922        let color = Color::Muted;
 5923
 5924        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 5925        let bp_kind = Arc::new(
 5926            breakpoint
 5927                .map(|(_, bp)| bp.kind.clone())
 5928                .unwrap_or(BreakpointKind::Standard),
 5929        );
 5930
 5931        if self.available_code_actions.is_some() {
 5932            Some(
 5933                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5934                    .shape(ui::IconButtonShape::Square)
 5935                    .icon_size(IconSize::XSmall)
 5936                    .icon_color(color)
 5937                    .toggle_state(is_active)
 5938                    .tooltip({
 5939                        let focus_handle = self.focus_handle.clone();
 5940                        move |window, cx| {
 5941                            Tooltip::for_action_in(
 5942                                "Toggle Code Actions",
 5943                                &ToggleCodeActions {
 5944                                    deployed_from_indicator: None,
 5945                                },
 5946                                &focus_handle,
 5947                                window,
 5948                                cx,
 5949                            )
 5950                        }
 5951                    })
 5952                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5953                        window.focus(&editor.focus_handle(cx));
 5954                        editor.toggle_code_actions(
 5955                            &ToggleCodeActions {
 5956                                deployed_from_indicator: Some(row),
 5957                            },
 5958                            window,
 5959                            cx,
 5960                        );
 5961                    }))
 5962                    .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 5963                        editor.set_breakpoint_context_menu(
 5964                            row,
 5965                            position,
 5966                            bp_kind.clone(),
 5967                            event.down.position,
 5968                            window,
 5969                            cx,
 5970                        );
 5971                    })),
 5972            )
 5973        } else {
 5974            None
 5975        }
 5976    }
 5977
 5978    fn clear_tasks(&mut self) {
 5979        self.tasks.clear()
 5980    }
 5981
 5982    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5983        if self.tasks.insert(key, value).is_some() {
 5984            // This case should hopefully be rare, but just in case...
 5985            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5986        }
 5987    }
 5988
 5989    /// Get all display points of breakpoints that will be rendered within editor
 5990    ///
 5991    /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
 5992    /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
 5993    /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
 5994    fn active_breakpoints(
 5995        &mut self,
 5996        range: Range<DisplayRow>,
 5997        window: &mut Window,
 5998        cx: &mut Context<Self>,
 5999    ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
 6000        let mut breakpoint_display_points = HashMap::default();
 6001
 6002        let Some(breakpoint_store) = self.breakpoint_store.clone() else {
 6003            return breakpoint_display_points;
 6004        };
 6005
 6006        let snapshot = self.snapshot(window, cx);
 6007
 6008        let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
 6009        let Some(project) = self.project.as_ref() else {
 6010            return breakpoint_display_points;
 6011        };
 6012
 6013        if let Some(buffer) = self.buffer.read(cx).as_singleton() {
 6014            let buffer_snapshot = buffer.read(cx).snapshot();
 6015
 6016            for breakpoint in
 6017                breakpoint_store
 6018                    .read(cx)
 6019                    .breakpoints(&buffer, None, buffer_snapshot.clone(), cx)
 6020            {
 6021                let point = buffer_snapshot.summary_for_anchor::<Point>(&breakpoint.0);
 6022                let anchor = multi_buffer_snapshot.anchor_before(point);
 6023                breakpoint_display_points.insert(
 6024                    snapshot
 6025                        .point_to_display_point(
 6026                            MultiBufferPoint {
 6027                                row: point.row,
 6028                                column: point.column,
 6029                            },
 6030                            Bias::Left,
 6031                        )
 6032                        .row(),
 6033                    (anchor, breakpoint.1.clone()),
 6034                );
 6035            }
 6036
 6037            return breakpoint_display_points;
 6038        }
 6039
 6040        let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
 6041            ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
 6042        for excerpt_boundary in multi_buffer_snapshot.excerpt_boundaries_in_range(range) {
 6043            let info = excerpt_boundary.next;
 6044
 6045            let Some(excerpt_ranges) = multi_buffer_snapshot.range_for_excerpt(info.id) else {
 6046                continue;
 6047            };
 6048
 6049            let Some(buffer) =
 6050                project.read_with(cx, |this, cx| this.buffer_for_id(info.buffer_id, cx))
 6051            else {
 6052                continue;
 6053            };
 6054
 6055            if buffer.read(cx).file().is_none() {
 6056                continue;
 6057            }
 6058            let breakpoints = breakpoint_store.read(cx).breakpoints(
 6059                &buffer,
 6060                Some(info.range.context.start..info.range.context.end),
 6061                info.buffer.clone(),
 6062                cx,
 6063            );
 6064
 6065            // To translate a breakpoint's position within a singular buffer to a multi buffer
 6066            // position we need to know it's excerpt starting location, it's position within
 6067            // the singular buffer, and if that position is within the excerpt's range.
 6068            let excerpt_head = excerpt_ranges
 6069                .start
 6070                .to_display_point(&snapshot.display_snapshot);
 6071
 6072            let buffer_start = info
 6073                .buffer
 6074                .summary_for_anchor::<Point>(&info.range.context.start);
 6075
 6076            for (anchor, breakpoint) in breakpoints {
 6077                let as_row = info.buffer.summary_for_anchor::<Point>(&anchor).row;
 6078                let delta = as_row - buffer_start.row;
 6079
 6080                let position = excerpt_head + DisplayPoint::new(DisplayRow(delta), 0);
 6081
 6082                let anchor = snapshot.display_point_to_anchor(position, Bias::Left);
 6083
 6084                breakpoint_display_points.insert(position.row(), (anchor, breakpoint.clone()));
 6085            }
 6086        }
 6087
 6088        breakpoint_display_points
 6089    }
 6090
 6091    fn breakpoint_context_menu(
 6092        &self,
 6093        anchor: Anchor,
 6094        kind: Arc<BreakpointKind>,
 6095        window: &mut Window,
 6096        cx: &mut Context<Self>,
 6097    ) -> Entity<ui::ContextMenu> {
 6098        let weak_editor = cx.weak_entity();
 6099        let focus_handle = self.focus_handle(cx);
 6100
 6101        let second_entry_msg = if kind.log_message().is_some() {
 6102            "Edit Log Breakpoint"
 6103        } else {
 6104            "Add Log Breakpoint"
 6105        };
 6106
 6107        ui::ContextMenu::build(window, cx, |menu, _, _cx| {
 6108            menu.on_blur_subscription(Subscription::new(|| {}))
 6109                .context(focus_handle)
 6110                .entry("Toggle Breakpoint", None, {
 6111                    let weak_editor = weak_editor.clone();
 6112                    move |_window, cx| {
 6113                        weak_editor
 6114                            .update(cx, |this, cx| {
 6115                                this.edit_breakpoint_at_anchor(
 6116                                    anchor,
 6117                                    BreakpointKind::Standard,
 6118                                    BreakpointEditAction::Toggle,
 6119                                    cx,
 6120                                );
 6121                            })
 6122                            .log_err();
 6123                    }
 6124                })
 6125                .entry(second_entry_msg, None, move |window, cx| {
 6126                    weak_editor
 6127                        .update(cx, |this, cx| {
 6128                            this.add_edit_breakpoint_block(anchor, kind.as_ref(), window, cx);
 6129                        })
 6130                        .log_err();
 6131                })
 6132        })
 6133    }
 6134
 6135    fn render_breakpoint(
 6136        &self,
 6137        position: Anchor,
 6138        row: DisplayRow,
 6139        kind: &BreakpointKind,
 6140        cx: &mut Context<Self>,
 6141    ) -> IconButton {
 6142        let color = if self
 6143            .gutter_breakpoint_indicator
 6144            .is_some_and(|gutter_bp| gutter_bp.row() == row)
 6145        {
 6146            Color::Hint
 6147        } else {
 6148            Color::Debugger
 6149        };
 6150
 6151        let icon = match &kind {
 6152            BreakpointKind::Standard => ui::IconName::DebugBreakpoint,
 6153            BreakpointKind::Log(_) => ui::IconName::DebugLogBreakpoint,
 6154        };
 6155        let arc_kind = Arc::new(kind.clone());
 6156        let arc_kind2 = arc_kind.clone();
 6157
 6158        IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
 6159            .icon_size(IconSize::XSmall)
 6160            .size(ui::ButtonSize::None)
 6161            .icon_color(color)
 6162            .style(ButtonStyle::Transparent)
 6163            .on_click(cx.listener(move |editor, _e, window, cx| {
 6164                window.focus(&editor.focus_handle(cx));
 6165                editor.edit_breakpoint_at_anchor(
 6166                    position,
 6167                    arc_kind.as_ref().clone(),
 6168                    BreakpointEditAction::Toggle,
 6169                    cx,
 6170                );
 6171            }))
 6172            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6173                editor.set_breakpoint_context_menu(
 6174                    row,
 6175                    Some(position),
 6176                    arc_kind2.clone(),
 6177                    event.down.position,
 6178                    window,
 6179                    cx,
 6180                );
 6181            }))
 6182    }
 6183
 6184    fn build_tasks_context(
 6185        project: &Entity<Project>,
 6186        buffer: &Entity<Buffer>,
 6187        buffer_row: u32,
 6188        tasks: &Arc<RunnableTasks>,
 6189        cx: &mut Context<Self>,
 6190    ) -> Task<Option<task::TaskContext>> {
 6191        let position = Point::new(buffer_row, tasks.column);
 6192        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 6193        let location = Location {
 6194            buffer: buffer.clone(),
 6195            range: range_start..range_start,
 6196        };
 6197        // Fill in the environmental variables from the tree-sitter captures
 6198        let mut captured_task_variables = TaskVariables::default();
 6199        for (capture_name, value) in tasks.extra_variables.clone() {
 6200            captured_task_variables.insert(
 6201                task::VariableName::Custom(capture_name.into()),
 6202                value.clone(),
 6203            );
 6204        }
 6205        project.update(cx, |project, cx| {
 6206            project.task_store().update(cx, |task_store, cx| {
 6207                task_store.task_context_for_location(captured_task_variables, location, cx)
 6208            })
 6209        })
 6210    }
 6211
 6212    pub fn spawn_nearest_task(
 6213        &mut self,
 6214        action: &SpawnNearestTask,
 6215        window: &mut Window,
 6216        cx: &mut Context<Self>,
 6217    ) {
 6218        let Some((workspace, _)) = self.workspace.clone() else {
 6219            return;
 6220        };
 6221        let Some(project) = self.project.clone() else {
 6222            return;
 6223        };
 6224
 6225        // Try to find a closest, enclosing node using tree-sitter that has a
 6226        // task
 6227        let Some((buffer, buffer_row, tasks)) = self
 6228            .find_enclosing_node_task(cx)
 6229            // Or find the task that's closest in row-distance.
 6230            .or_else(|| self.find_closest_task(cx))
 6231        else {
 6232            return;
 6233        };
 6234
 6235        let reveal_strategy = action.reveal;
 6236        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 6237        cx.spawn_in(window, async move |_, cx| {
 6238            let context = task_context.await?;
 6239            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 6240
 6241            let resolved = resolved_task.resolved.as_mut()?;
 6242            resolved.reveal = reveal_strategy;
 6243
 6244            workspace
 6245                .update(cx, |workspace, cx| {
 6246                    workspace::tasks::schedule_resolved_task(
 6247                        workspace,
 6248                        task_source_kind,
 6249                        resolved_task,
 6250                        false,
 6251                        cx,
 6252                    );
 6253                })
 6254                .ok()
 6255        })
 6256        .detach();
 6257    }
 6258
 6259    fn find_closest_task(
 6260        &mut self,
 6261        cx: &mut Context<Self>,
 6262    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6263        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 6264
 6265        let ((buffer_id, row), tasks) = self
 6266            .tasks
 6267            .iter()
 6268            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 6269
 6270        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 6271        let tasks = Arc::new(tasks.to_owned());
 6272        Some((buffer, *row, tasks))
 6273    }
 6274
 6275    fn find_enclosing_node_task(
 6276        &mut self,
 6277        cx: &mut Context<Self>,
 6278    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6279        let snapshot = self.buffer.read(cx).snapshot(cx);
 6280        let offset = self.selections.newest::<usize>(cx).head();
 6281        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 6282        let buffer_id = excerpt.buffer().remote_id();
 6283
 6284        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 6285        let mut cursor = layer.node().walk();
 6286
 6287        while cursor.goto_first_child_for_byte(offset).is_some() {
 6288            if cursor.node().end_byte() == offset {
 6289                cursor.goto_next_sibling();
 6290            }
 6291        }
 6292
 6293        // Ascend to the smallest ancestor that contains the range and has a task.
 6294        loop {
 6295            let node = cursor.node();
 6296            let node_range = node.byte_range();
 6297            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 6298
 6299            // Check if this node contains our offset
 6300            if node_range.start <= offset && node_range.end >= offset {
 6301                // If it contains offset, check for task
 6302                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 6303                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 6304                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 6305                }
 6306            }
 6307
 6308            if !cursor.goto_parent() {
 6309                break;
 6310            }
 6311        }
 6312        None
 6313    }
 6314
 6315    fn render_run_indicator(
 6316        &self,
 6317        _style: &EditorStyle,
 6318        is_active: bool,
 6319        row: DisplayRow,
 6320        breakpoint: Option<(Anchor, Breakpoint)>,
 6321        cx: &mut Context<Self>,
 6322    ) -> IconButton {
 6323        let color = Color::Muted;
 6324
 6325        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6326        let bp_kind = Arc::new(
 6327            breakpoint
 6328                .map(|(_, bp)| bp.kind)
 6329                .unwrap_or(BreakpointKind::Standard),
 6330        );
 6331
 6332        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 6333            .shape(ui::IconButtonShape::Square)
 6334            .icon_size(IconSize::XSmall)
 6335            .icon_color(color)
 6336            .toggle_state(is_active)
 6337            .on_click(cx.listener(move |editor, _e, window, cx| {
 6338                window.focus(&editor.focus_handle(cx));
 6339                editor.toggle_code_actions(
 6340                    &ToggleCodeActions {
 6341                        deployed_from_indicator: Some(row),
 6342                    },
 6343                    window,
 6344                    cx,
 6345                );
 6346            }))
 6347            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6348                editor.set_breakpoint_context_menu(
 6349                    row,
 6350                    position,
 6351                    bp_kind.clone(),
 6352                    event.down.position,
 6353                    window,
 6354                    cx,
 6355                );
 6356            }))
 6357    }
 6358
 6359    pub fn context_menu_visible(&self) -> bool {
 6360        !self.edit_prediction_preview_is_active()
 6361            && self
 6362                .context_menu
 6363                .borrow()
 6364                .as_ref()
 6365                .map_or(false, |menu| menu.visible())
 6366    }
 6367
 6368    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 6369        self.context_menu
 6370            .borrow()
 6371            .as_ref()
 6372            .map(|menu| menu.origin())
 6373    }
 6374
 6375    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 6376    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 6377
 6378    fn render_edit_prediction_popover(
 6379        &mut self,
 6380        text_bounds: &Bounds<Pixels>,
 6381        content_origin: gpui::Point<Pixels>,
 6382        editor_snapshot: &EditorSnapshot,
 6383        visible_row_range: Range<DisplayRow>,
 6384        scroll_top: f32,
 6385        scroll_bottom: f32,
 6386        line_layouts: &[LineWithInvisibles],
 6387        line_height: Pixels,
 6388        scroll_pixel_position: gpui::Point<Pixels>,
 6389        newest_selection_head: Option<DisplayPoint>,
 6390        editor_width: Pixels,
 6391        style: &EditorStyle,
 6392        window: &mut Window,
 6393        cx: &mut App,
 6394    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6395        let active_inline_completion = self.active_inline_completion.as_ref()?;
 6396
 6397        if self.edit_prediction_visible_in_cursor_popover(true) {
 6398            return None;
 6399        }
 6400
 6401        match &active_inline_completion.completion {
 6402            InlineCompletion::Move { target, .. } => {
 6403                let target_display_point = target.to_display_point(editor_snapshot);
 6404
 6405                if self.edit_prediction_requires_modifier() {
 6406                    if !self.edit_prediction_preview_is_active() {
 6407                        return None;
 6408                    }
 6409
 6410                    self.render_edit_prediction_modifier_jump_popover(
 6411                        text_bounds,
 6412                        content_origin,
 6413                        visible_row_range,
 6414                        line_layouts,
 6415                        line_height,
 6416                        scroll_pixel_position,
 6417                        newest_selection_head,
 6418                        target_display_point,
 6419                        window,
 6420                        cx,
 6421                    )
 6422                } else {
 6423                    self.render_edit_prediction_eager_jump_popover(
 6424                        text_bounds,
 6425                        content_origin,
 6426                        editor_snapshot,
 6427                        visible_row_range,
 6428                        scroll_top,
 6429                        scroll_bottom,
 6430                        line_height,
 6431                        scroll_pixel_position,
 6432                        target_display_point,
 6433                        editor_width,
 6434                        window,
 6435                        cx,
 6436                    )
 6437                }
 6438            }
 6439            InlineCompletion::Edit {
 6440                display_mode: EditDisplayMode::Inline,
 6441                ..
 6442            } => None,
 6443            InlineCompletion::Edit {
 6444                display_mode: EditDisplayMode::TabAccept,
 6445                edits,
 6446                ..
 6447            } => {
 6448                let range = &edits.first()?.0;
 6449                let target_display_point = range.end.to_display_point(editor_snapshot);
 6450
 6451                self.render_edit_prediction_end_of_line_popover(
 6452                    "Accept",
 6453                    editor_snapshot,
 6454                    visible_row_range,
 6455                    target_display_point,
 6456                    line_height,
 6457                    scroll_pixel_position,
 6458                    content_origin,
 6459                    editor_width,
 6460                    window,
 6461                    cx,
 6462                )
 6463            }
 6464            InlineCompletion::Edit {
 6465                edits,
 6466                edit_preview,
 6467                display_mode: EditDisplayMode::DiffPopover,
 6468                snapshot,
 6469            } => self.render_edit_prediction_diff_popover(
 6470                text_bounds,
 6471                content_origin,
 6472                editor_snapshot,
 6473                visible_row_range,
 6474                line_layouts,
 6475                line_height,
 6476                scroll_pixel_position,
 6477                newest_selection_head,
 6478                editor_width,
 6479                style,
 6480                edits,
 6481                edit_preview,
 6482                snapshot,
 6483                window,
 6484                cx,
 6485            ),
 6486        }
 6487    }
 6488
 6489    fn render_edit_prediction_modifier_jump_popover(
 6490        &mut self,
 6491        text_bounds: &Bounds<Pixels>,
 6492        content_origin: gpui::Point<Pixels>,
 6493        visible_row_range: Range<DisplayRow>,
 6494        line_layouts: &[LineWithInvisibles],
 6495        line_height: Pixels,
 6496        scroll_pixel_position: gpui::Point<Pixels>,
 6497        newest_selection_head: Option<DisplayPoint>,
 6498        target_display_point: DisplayPoint,
 6499        window: &mut Window,
 6500        cx: &mut App,
 6501    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6502        let scrolled_content_origin =
 6503            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 6504
 6505        const SCROLL_PADDING_Y: Pixels = px(12.);
 6506
 6507        if target_display_point.row() < visible_row_range.start {
 6508            return self.render_edit_prediction_scroll_popover(
 6509                |_| SCROLL_PADDING_Y,
 6510                IconName::ArrowUp,
 6511                visible_row_range,
 6512                line_layouts,
 6513                newest_selection_head,
 6514                scrolled_content_origin,
 6515                window,
 6516                cx,
 6517            );
 6518        } else if target_display_point.row() >= visible_row_range.end {
 6519            return self.render_edit_prediction_scroll_popover(
 6520                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 6521                IconName::ArrowDown,
 6522                visible_row_range,
 6523                line_layouts,
 6524                newest_selection_head,
 6525                scrolled_content_origin,
 6526                window,
 6527                cx,
 6528            );
 6529        }
 6530
 6531        const POLE_WIDTH: Pixels = px(2.);
 6532
 6533        let line_layout =
 6534            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 6535        let target_column = target_display_point.column() as usize;
 6536
 6537        let target_x = line_layout.x_for_index(target_column);
 6538        let target_y =
 6539            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 6540
 6541        let flag_on_right = target_x < text_bounds.size.width / 2.;
 6542
 6543        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 6544        border_color.l += 0.001;
 6545
 6546        let mut element = v_flex()
 6547            .items_end()
 6548            .when(flag_on_right, |el| el.items_start())
 6549            .child(if flag_on_right {
 6550                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6551                    .rounded_bl(px(0.))
 6552                    .rounded_tl(px(0.))
 6553                    .border_l_2()
 6554                    .border_color(border_color)
 6555            } else {
 6556                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6557                    .rounded_br(px(0.))
 6558                    .rounded_tr(px(0.))
 6559                    .border_r_2()
 6560                    .border_color(border_color)
 6561            })
 6562            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 6563            .into_any();
 6564
 6565        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6566
 6567        let mut origin = scrolled_content_origin + point(target_x, target_y)
 6568            - point(
 6569                if flag_on_right {
 6570                    POLE_WIDTH
 6571                } else {
 6572                    size.width - POLE_WIDTH
 6573                },
 6574                size.height - line_height,
 6575            );
 6576
 6577        origin.x = origin.x.max(content_origin.x);
 6578
 6579        element.prepaint_at(origin, window, cx);
 6580
 6581        Some((element, origin))
 6582    }
 6583
 6584    fn render_edit_prediction_scroll_popover(
 6585        &mut self,
 6586        to_y: impl Fn(Size<Pixels>) -> Pixels,
 6587        scroll_icon: IconName,
 6588        visible_row_range: Range<DisplayRow>,
 6589        line_layouts: &[LineWithInvisibles],
 6590        newest_selection_head: Option<DisplayPoint>,
 6591        scrolled_content_origin: gpui::Point<Pixels>,
 6592        window: &mut Window,
 6593        cx: &mut App,
 6594    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6595        let mut element = self
 6596            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 6597            .into_any();
 6598
 6599        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6600
 6601        let cursor = newest_selection_head?;
 6602        let cursor_row_layout =
 6603            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 6604        let cursor_column = cursor.column() as usize;
 6605
 6606        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 6607
 6608        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 6609
 6610        element.prepaint_at(origin, window, cx);
 6611        Some((element, origin))
 6612    }
 6613
 6614    fn render_edit_prediction_eager_jump_popover(
 6615        &mut self,
 6616        text_bounds: &Bounds<Pixels>,
 6617        content_origin: gpui::Point<Pixels>,
 6618        editor_snapshot: &EditorSnapshot,
 6619        visible_row_range: Range<DisplayRow>,
 6620        scroll_top: f32,
 6621        scroll_bottom: f32,
 6622        line_height: Pixels,
 6623        scroll_pixel_position: gpui::Point<Pixels>,
 6624        target_display_point: DisplayPoint,
 6625        editor_width: Pixels,
 6626        window: &mut Window,
 6627        cx: &mut App,
 6628    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6629        if target_display_point.row().as_f32() < scroll_top {
 6630            let mut element = self
 6631                .render_edit_prediction_line_popover(
 6632                    "Jump to Edit",
 6633                    Some(IconName::ArrowUp),
 6634                    window,
 6635                    cx,
 6636                )?
 6637                .into_any();
 6638
 6639            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6640            let offset = point(
 6641                (text_bounds.size.width - size.width) / 2.,
 6642                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6643            );
 6644
 6645            let origin = text_bounds.origin + offset;
 6646            element.prepaint_at(origin, window, cx);
 6647            Some((element, origin))
 6648        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 6649            let mut element = self
 6650                .render_edit_prediction_line_popover(
 6651                    "Jump to Edit",
 6652                    Some(IconName::ArrowDown),
 6653                    window,
 6654                    cx,
 6655                )?
 6656                .into_any();
 6657
 6658            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6659            let offset = point(
 6660                (text_bounds.size.width - size.width) / 2.,
 6661                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6662            );
 6663
 6664            let origin = text_bounds.origin + offset;
 6665            element.prepaint_at(origin, window, cx);
 6666            Some((element, origin))
 6667        } else {
 6668            self.render_edit_prediction_end_of_line_popover(
 6669                "Jump to Edit",
 6670                editor_snapshot,
 6671                visible_row_range,
 6672                target_display_point,
 6673                line_height,
 6674                scroll_pixel_position,
 6675                content_origin,
 6676                editor_width,
 6677                window,
 6678                cx,
 6679            )
 6680        }
 6681    }
 6682
 6683    fn render_edit_prediction_end_of_line_popover(
 6684        self: &mut Editor,
 6685        label: &'static str,
 6686        editor_snapshot: &EditorSnapshot,
 6687        visible_row_range: Range<DisplayRow>,
 6688        target_display_point: DisplayPoint,
 6689        line_height: Pixels,
 6690        scroll_pixel_position: gpui::Point<Pixels>,
 6691        content_origin: gpui::Point<Pixels>,
 6692        editor_width: Pixels,
 6693        window: &mut Window,
 6694        cx: &mut App,
 6695    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6696        let target_line_end = DisplayPoint::new(
 6697            target_display_point.row(),
 6698            editor_snapshot.line_len(target_display_point.row()),
 6699        );
 6700
 6701        let mut element = self
 6702            .render_edit_prediction_line_popover(label, None, window, cx)?
 6703            .into_any();
 6704
 6705        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6706
 6707        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 6708
 6709        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 6710        let mut origin = start_point
 6711            + line_origin
 6712            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 6713        origin.x = origin.x.max(content_origin.x);
 6714
 6715        let max_x = content_origin.x + editor_width - size.width;
 6716
 6717        if origin.x > max_x {
 6718            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 6719
 6720            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 6721                origin.y += offset;
 6722                IconName::ArrowUp
 6723            } else {
 6724                origin.y -= offset;
 6725                IconName::ArrowDown
 6726            };
 6727
 6728            element = self
 6729                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 6730                .into_any();
 6731
 6732            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6733
 6734            origin.x = content_origin.x + editor_width - size.width - px(2.);
 6735        }
 6736
 6737        element.prepaint_at(origin, window, cx);
 6738        Some((element, origin))
 6739    }
 6740
 6741    fn render_edit_prediction_diff_popover(
 6742        self: &Editor,
 6743        text_bounds: &Bounds<Pixels>,
 6744        content_origin: gpui::Point<Pixels>,
 6745        editor_snapshot: &EditorSnapshot,
 6746        visible_row_range: Range<DisplayRow>,
 6747        line_layouts: &[LineWithInvisibles],
 6748        line_height: Pixels,
 6749        scroll_pixel_position: gpui::Point<Pixels>,
 6750        newest_selection_head: Option<DisplayPoint>,
 6751        editor_width: Pixels,
 6752        style: &EditorStyle,
 6753        edits: &Vec<(Range<Anchor>, String)>,
 6754        edit_preview: &Option<language::EditPreview>,
 6755        snapshot: &language::BufferSnapshot,
 6756        window: &mut Window,
 6757        cx: &mut App,
 6758    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6759        let edit_start = edits
 6760            .first()
 6761            .unwrap()
 6762            .0
 6763            .start
 6764            .to_display_point(editor_snapshot);
 6765        let edit_end = edits
 6766            .last()
 6767            .unwrap()
 6768            .0
 6769            .end
 6770            .to_display_point(editor_snapshot);
 6771
 6772        let is_visible = visible_row_range.contains(&edit_start.row())
 6773            || visible_row_range.contains(&edit_end.row());
 6774        if !is_visible {
 6775            return None;
 6776        }
 6777
 6778        let highlighted_edits =
 6779            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 6780
 6781        let styled_text = highlighted_edits.to_styled_text(&style.text);
 6782        let line_count = highlighted_edits.text.lines().count();
 6783
 6784        const BORDER_WIDTH: Pixels = px(1.);
 6785
 6786        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 6787        let has_keybind = keybind.is_some();
 6788
 6789        let mut element = h_flex()
 6790            .items_start()
 6791            .child(
 6792                h_flex()
 6793                    .bg(cx.theme().colors().editor_background)
 6794                    .border(BORDER_WIDTH)
 6795                    .shadow_sm()
 6796                    .border_color(cx.theme().colors().border)
 6797                    .rounded_l_lg()
 6798                    .when(line_count > 1, |el| el.rounded_br_lg())
 6799                    .pr_1()
 6800                    .child(styled_text),
 6801            )
 6802            .child(
 6803                h_flex()
 6804                    .h(line_height + BORDER_WIDTH * px(2.))
 6805                    .px_1p5()
 6806                    .gap_1()
 6807                    // Workaround: For some reason, there's a gap if we don't do this
 6808                    .ml(-BORDER_WIDTH)
 6809                    .shadow(smallvec![gpui::BoxShadow {
 6810                        color: gpui::black().opacity(0.05),
 6811                        offset: point(px(1.), px(1.)),
 6812                        blur_radius: px(2.),
 6813                        spread_radius: px(0.),
 6814                    }])
 6815                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 6816                    .border(BORDER_WIDTH)
 6817                    .border_color(cx.theme().colors().border)
 6818                    .rounded_r_lg()
 6819                    .id("edit_prediction_diff_popover_keybind")
 6820                    .when(!has_keybind, |el| {
 6821                        let status_colors = cx.theme().status();
 6822
 6823                        el.bg(status_colors.error_background)
 6824                            .border_color(status_colors.error.opacity(0.6))
 6825                            .child(Icon::new(IconName::Info).color(Color::Error))
 6826                            .cursor_default()
 6827                            .hoverable_tooltip(move |_window, cx| {
 6828                                cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 6829                            })
 6830                    })
 6831                    .children(keybind),
 6832            )
 6833            .into_any();
 6834
 6835        let longest_row =
 6836            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 6837        let longest_line_width = if visible_row_range.contains(&longest_row) {
 6838            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 6839        } else {
 6840            layout_line(
 6841                longest_row,
 6842                editor_snapshot,
 6843                style,
 6844                editor_width,
 6845                |_| false,
 6846                window,
 6847                cx,
 6848            )
 6849            .width
 6850        };
 6851
 6852        let viewport_bounds =
 6853            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 6854                right: -EditorElement::SCROLLBAR_WIDTH,
 6855                ..Default::default()
 6856            });
 6857
 6858        let x_after_longest =
 6859            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 6860                - scroll_pixel_position.x;
 6861
 6862        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6863
 6864        // Fully visible if it can be displayed within the window (allow overlapping other
 6865        // panes). However, this is only allowed if the popover starts within text_bounds.
 6866        let can_position_to_the_right = x_after_longest < text_bounds.right()
 6867            && x_after_longest + element_bounds.width < viewport_bounds.right();
 6868
 6869        let mut origin = if can_position_to_the_right {
 6870            point(
 6871                x_after_longest,
 6872                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 6873                    - scroll_pixel_position.y,
 6874            )
 6875        } else {
 6876            let cursor_row = newest_selection_head.map(|head| head.row());
 6877            let above_edit = edit_start
 6878                .row()
 6879                .0
 6880                .checked_sub(line_count as u32)
 6881                .map(DisplayRow);
 6882            let below_edit = Some(edit_end.row() + 1);
 6883            let above_cursor =
 6884                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 6885            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 6886
 6887            // Place the edit popover adjacent to the edit if there is a location
 6888            // available that is onscreen and does not obscure the cursor. Otherwise,
 6889            // place it adjacent to the cursor.
 6890            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 6891                .into_iter()
 6892                .flatten()
 6893                .find(|&start_row| {
 6894                    let end_row = start_row + line_count as u32;
 6895                    visible_row_range.contains(&start_row)
 6896                        && visible_row_range.contains(&end_row)
 6897                        && cursor_row.map_or(true, |cursor_row| {
 6898                            !((start_row..end_row).contains(&cursor_row))
 6899                        })
 6900                })?;
 6901
 6902            content_origin
 6903                + point(
 6904                    -scroll_pixel_position.x,
 6905                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 6906                )
 6907        };
 6908
 6909        origin.x -= BORDER_WIDTH;
 6910
 6911        window.defer_draw(element, origin, 1);
 6912
 6913        // Do not return an element, since it will already be drawn due to defer_draw.
 6914        None
 6915    }
 6916
 6917    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 6918        px(30.)
 6919    }
 6920
 6921    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 6922        if self.read_only(cx) {
 6923            cx.theme().players().read_only()
 6924        } else {
 6925            self.style.as_ref().unwrap().local_player
 6926        }
 6927    }
 6928
 6929    fn render_edit_prediction_accept_keybind(
 6930        &self,
 6931        window: &mut Window,
 6932        cx: &App,
 6933    ) -> Option<AnyElement> {
 6934        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 6935        let accept_keystroke = accept_binding.keystroke()?;
 6936
 6937        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6938
 6939        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 6940            Color::Accent
 6941        } else {
 6942            Color::Muted
 6943        };
 6944
 6945        h_flex()
 6946            .px_0p5()
 6947            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 6948            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6949            .text_size(TextSize::XSmall.rems(cx))
 6950            .child(h_flex().children(ui::render_modifiers(
 6951                &accept_keystroke.modifiers,
 6952                PlatformStyle::platform(),
 6953                Some(modifiers_color),
 6954                Some(IconSize::XSmall.rems().into()),
 6955                true,
 6956            )))
 6957            .when(is_platform_style_mac, |parent| {
 6958                parent.child(accept_keystroke.key.clone())
 6959            })
 6960            .when(!is_platform_style_mac, |parent| {
 6961                parent.child(
 6962                    Key::new(
 6963                        util::capitalize(&accept_keystroke.key),
 6964                        Some(Color::Default),
 6965                    )
 6966                    .size(Some(IconSize::XSmall.rems().into())),
 6967                )
 6968            })
 6969            .into_any()
 6970            .into()
 6971    }
 6972
 6973    fn render_edit_prediction_line_popover(
 6974        &self,
 6975        label: impl Into<SharedString>,
 6976        icon: Option<IconName>,
 6977        window: &mut Window,
 6978        cx: &App,
 6979    ) -> Option<Stateful<Div>> {
 6980        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 6981
 6982        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 6983        let has_keybind = keybind.is_some();
 6984
 6985        let result = h_flex()
 6986            .id("ep-line-popover")
 6987            .py_0p5()
 6988            .pl_1()
 6989            .pr(padding_right)
 6990            .gap_1()
 6991            .rounded_md()
 6992            .border_1()
 6993            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6994            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 6995            .shadow_sm()
 6996            .when(!has_keybind, |el| {
 6997                let status_colors = cx.theme().status();
 6998
 6999                el.bg(status_colors.error_background)
 7000                    .border_color(status_colors.error.opacity(0.6))
 7001                    .pl_2()
 7002                    .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
 7003                    .cursor_default()
 7004                    .hoverable_tooltip(move |_window, cx| {
 7005                        cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7006                    })
 7007            })
 7008            .children(keybind)
 7009            .child(
 7010                Label::new(label)
 7011                    .size(LabelSize::Small)
 7012                    .when(!has_keybind, |el| {
 7013                        el.color(cx.theme().status().error.into()).strikethrough()
 7014                    }),
 7015            )
 7016            .when(!has_keybind, |el| {
 7017                el.child(
 7018                    h_flex().ml_1().child(
 7019                        Icon::new(IconName::Info)
 7020                            .size(IconSize::Small)
 7021                            .color(cx.theme().status().error.into()),
 7022                    ),
 7023                )
 7024            })
 7025            .when_some(icon, |element, icon| {
 7026                element.child(
 7027                    div()
 7028                        .mt(px(1.5))
 7029                        .child(Icon::new(icon).size(IconSize::Small)),
 7030                )
 7031            });
 7032
 7033        Some(result)
 7034    }
 7035
 7036    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 7037        let accent_color = cx.theme().colors().text_accent;
 7038        let editor_bg_color = cx.theme().colors().editor_background;
 7039        editor_bg_color.blend(accent_color.opacity(0.1))
 7040    }
 7041
 7042    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 7043        let accent_color = cx.theme().colors().text_accent;
 7044        let editor_bg_color = cx.theme().colors().editor_background;
 7045        editor_bg_color.blend(accent_color.opacity(0.6))
 7046    }
 7047
 7048    fn render_edit_prediction_cursor_popover(
 7049        &self,
 7050        min_width: Pixels,
 7051        max_width: Pixels,
 7052        cursor_point: Point,
 7053        style: &EditorStyle,
 7054        accept_keystroke: Option<&gpui::Keystroke>,
 7055        _window: &Window,
 7056        cx: &mut Context<Editor>,
 7057    ) -> Option<AnyElement> {
 7058        let provider = self.edit_prediction_provider.as_ref()?;
 7059
 7060        if provider.provider.needs_terms_acceptance(cx) {
 7061            return Some(
 7062                h_flex()
 7063                    .min_w(min_width)
 7064                    .flex_1()
 7065                    .px_2()
 7066                    .py_1()
 7067                    .gap_3()
 7068                    .elevation_2(cx)
 7069                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 7070                    .id("accept-terms")
 7071                    .cursor_pointer()
 7072                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 7073                    .on_click(cx.listener(|this, _event, window, cx| {
 7074                        cx.stop_propagation();
 7075                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 7076                        window.dispatch_action(
 7077                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 7078                            cx,
 7079                        );
 7080                    }))
 7081                    .child(
 7082                        h_flex()
 7083                            .flex_1()
 7084                            .gap_2()
 7085                            .child(Icon::new(IconName::ZedPredict))
 7086                            .child(Label::new("Accept Terms of Service"))
 7087                            .child(div().w_full())
 7088                            .child(
 7089                                Icon::new(IconName::ArrowUpRight)
 7090                                    .color(Color::Muted)
 7091                                    .size(IconSize::Small),
 7092                            )
 7093                            .into_any_element(),
 7094                    )
 7095                    .into_any(),
 7096            );
 7097        }
 7098
 7099        let is_refreshing = provider.provider.is_refreshing(cx);
 7100
 7101        fn pending_completion_container() -> Div {
 7102            h_flex()
 7103                .h_full()
 7104                .flex_1()
 7105                .gap_2()
 7106                .child(Icon::new(IconName::ZedPredict))
 7107        }
 7108
 7109        let completion = match &self.active_inline_completion {
 7110            Some(prediction) => {
 7111                if !self.has_visible_completions_menu() {
 7112                    const RADIUS: Pixels = px(6.);
 7113                    const BORDER_WIDTH: Pixels = px(1.);
 7114
 7115                    return Some(
 7116                        h_flex()
 7117                            .elevation_2(cx)
 7118                            .border(BORDER_WIDTH)
 7119                            .border_color(cx.theme().colors().border)
 7120                            .when(accept_keystroke.is_none(), |el| {
 7121                                el.border_color(cx.theme().status().error)
 7122                            })
 7123                            .rounded(RADIUS)
 7124                            .rounded_tl(px(0.))
 7125                            .overflow_hidden()
 7126                            .child(div().px_1p5().child(match &prediction.completion {
 7127                                InlineCompletion::Move { target, snapshot } => {
 7128                                    use text::ToPoint as _;
 7129                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 7130                                    {
 7131                                        Icon::new(IconName::ZedPredictDown)
 7132                                    } else {
 7133                                        Icon::new(IconName::ZedPredictUp)
 7134                                    }
 7135                                }
 7136                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 7137                            }))
 7138                            .child(
 7139                                h_flex()
 7140                                    .gap_1()
 7141                                    .py_1()
 7142                                    .px_2()
 7143                                    .rounded_r(RADIUS - BORDER_WIDTH)
 7144                                    .border_l_1()
 7145                                    .border_color(cx.theme().colors().border)
 7146                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7147                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 7148                                        el.child(
 7149                                            Label::new("Hold")
 7150                                                .size(LabelSize::Small)
 7151                                                .when(accept_keystroke.is_none(), |el| {
 7152                                                    el.strikethrough()
 7153                                                })
 7154                                                .line_height_style(LineHeightStyle::UiLabel),
 7155                                        )
 7156                                    })
 7157                                    .id("edit_prediction_cursor_popover_keybind")
 7158                                    .when(accept_keystroke.is_none(), |el| {
 7159                                        let status_colors = cx.theme().status();
 7160
 7161                                        el.bg(status_colors.error_background)
 7162                                            .border_color(status_colors.error.opacity(0.6))
 7163                                            .child(Icon::new(IconName::Info).color(Color::Error))
 7164                                            .cursor_default()
 7165                                            .hoverable_tooltip(move |_window, cx| {
 7166                                                cx.new(|_| MissingEditPredictionKeybindingTooltip)
 7167                                                    .into()
 7168                                            })
 7169                                    })
 7170                                    .when_some(
 7171                                        accept_keystroke.as_ref(),
 7172                                        |el, accept_keystroke| {
 7173                                            el.child(h_flex().children(ui::render_modifiers(
 7174                                                &accept_keystroke.modifiers,
 7175                                                PlatformStyle::platform(),
 7176                                                Some(Color::Default),
 7177                                                Some(IconSize::XSmall.rems().into()),
 7178                                                false,
 7179                                            )))
 7180                                        },
 7181                                    ),
 7182                            )
 7183                            .into_any(),
 7184                    );
 7185                }
 7186
 7187                self.render_edit_prediction_cursor_popover_preview(
 7188                    prediction,
 7189                    cursor_point,
 7190                    style,
 7191                    cx,
 7192                )?
 7193            }
 7194
 7195            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 7196                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 7197                    stale_completion,
 7198                    cursor_point,
 7199                    style,
 7200                    cx,
 7201                )?,
 7202
 7203                None => {
 7204                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 7205                }
 7206            },
 7207
 7208            None => pending_completion_container().child(Label::new("No Prediction")),
 7209        };
 7210
 7211        let completion = if is_refreshing {
 7212            completion
 7213                .with_animation(
 7214                    "loading-completion",
 7215                    Animation::new(Duration::from_secs(2))
 7216                        .repeat()
 7217                        .with_easing(pulsating_between(0.4, 0.8)),
 7218                    |label, delta| label.opacity(delta),
 7219                )
 7220                .into_any_element()
 7221        } else {
 7222            completion.into_any_element()
 7223        };
 7224
 7225        let has_completion = self.active_inline_completion.is_some();
 7226
 7227        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7228        Some(
 7229            h_flex()
 7230                .min_w(min_width)
 7231                .max_w(max_width)
 7232                .flex_1()
 7233                .elevation_2(cx)
 7234                .border_color(cx.theme().colors().border)
 7235                .child(
 7236                    div()
 7237                        .flex_1()
 7238                        .py_1()
 7239                        .px_2()
 7240                        .overflow_hidden()
 7241                        .child(completion),
 7242                )
 7243                .when_some(accept_keystroke, |el, accept_keystroke| {
 7244                    if !accept_keystroke.modifiers.modified() {
 7245                        return el;
 7246                    }
 7247
 7248                    el.child(
 7249                        h_flex()
 7250                            .h_full()
 7251                            .border_l_1()
 7252                            .rounded_r_lg()
 7253                            .border_color(cx.theme().colors().border)
 7254                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7255                            .gap_1()
 7256                            .py_1()
 7257                            .px_2()
 7258                            .child(
 7259                                h_flex()
 7260                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7261                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 7262                                    .child(h_flex().children(ui::render_modifiers(
 7263                                        &accept_keystroke.modifiers,
 7264                                        PlatformStyle::platform(),
 7265                                        Some(if !has_completion {
 7266                                            Color::Muted
 7267                                        } else {
 7268                                            Color::Default
 7269                                        }),
 7270                                        None,
 7271                                        false,
 7272                                    ))),
 7273                            )
 7274                            .child(Label::new("Preview").into_any_element())
 7275                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 7276                    )
 7277                })
 7278                .into_any(),
 7279        )
 7280    }
 7281
 7282    fn render_edit_prediction_cursor_popover_preview(
 7283        &self,
 7284        completion: &InlineCompletionState,
 7285        cursor_point: Point,
 7286        style: &EditorStyle,
 7287        cx: &mut Context<Editor>,
 7288    ) -> Option<Div> {
 7289        use text::ToPoint as _;
 7290
 7291        fn render_relative_row_jump(
 7292            prefix: impl Into<String>,
 7293            current_row: u32,
 7294            target_row: u32,
 7295        ) -> Div {
 7296            let (row_diff, arrow) = if target_row < current_row {
 7297                (current_row - target_row, IconName::ArrowUp)
 7298            } else {
 7299                (target_row - current_row, IconName::ArrowDown)
 7300            };
 7301
 7302            h_flex()
 7303                .child(
 7304                    Label::new(format!("{}{}", prefix.into(), row_diff))
 7305                        .color(Color::Muted)
 7306                        .size(LabelSize::Small),
 7307                )
 7308                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 7309        }
 7310
 7311        match &completion.completion {
 7312            InlineCompletion::Move {
 7313                target, snapshot, ..
 7314            } => Some(
 7315                h_flex()
 7316                    .px_2()
 7317                    .gap_2()
 7318                    .flex_1()
 7319                    .child(
 7320                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 7321                            Icon::new(IconName::ZedPredictDown)
 7322                        } else {
 7323                            Icon::new(IconName::ZedPredictUp)
 7324                        },
 7325                    )
 7326                    .child(Label::new("Jump to Edit")),
 7327            ),
 7328
 7329            InlineCompletion::Edit {
 7330                edits,
 7331                edit_preview,
 7332                snapshot,
 7333                display_mode: _,
 7334            } => {
 7335                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 7336
 7337                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 7338                    &snapshot,
 7339                    &edits,
 7340                    edit_preview.as_ref()?,
 7341                    true,
 7342                    cx,
 7343                )
 7344                .first_line_preview();
 7345
 7346                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 7347                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 7348
 7349                let preview = h_flex()
 7350                    .gap_1()
 7351                    .min_w_16()
 7352                    .child(styled_text)
 7353                    .when(has_more_lines, |parent| parent.child(""));
 7354
 7355                let left = if first_edit_row != cursor_point.row {
 7356                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 7357                        .into_any_element()
 7358                } else {
 7359                    Icon::new(IconName::ZedPredict).into_any_element()
 7360                };
 7361
 7362                Some(
 7363                    h_flex()
 7364                        .h_full()
 7365                        .flex_1()
 7366                        .gap_2()
 7367                        .pr_1()
 7368                        .overflow_x_hidden()
 7369                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7370                        .child(left)
 7371                        .child(preview),
 7372                )
 7373            }
 7374        }
 7375    }
 7376
 7377    fn render_context_menu(
 7378        &self,
 7379        style: &EditorStyle,
 7380        max_height_in_lines: u32,
 7381        y_flipped: bool,
 7382        window: &mut Window,
 7383        cx: &mut Context<Editor>,
 7384    ) -> Option<AnyElement> {
 7385        let menu = self.context_menu.borrow();
 7386        let menu = menu.as_ref()?;
 7387        if !menu.visible() {
 7388            return None;
 7389        };
 7390        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 7391    }
 7392
 7393    fn render_context_menu_aside(
 7394        &mut self,
 7395        max_size: Size<Pixels>,
 7396        window: &mut Window,
 7397        cx: &mut Context<Editor>,
 7398    ) -> Option<AnyElement> {
 7399        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 7400            if menu.visible() {
 7401                menu.render_aside(self, max_size, window, cx)
 7402            } else {
 7403                None
 7404            }
 7405        })
 7406    }
 7407
 7408    fn hide_context_menu(
 7409        &mut self,
 7410        window: &mut Window,
 7411        cx: &mut Context<Self>,
 7412    ) -> Option<CodeContextMenu> {
 7413        cx.notify();
 7414        self.completion_tasks.clear();
 7415        let context_menu = self.context_menu.borrow_mut().take();
 7416        self.stale_inline_completion_in_menu.take();
 7417        self.update_visible_inline_completion(window, cx);
 7418        context_menu
 7419    }
 7420
 7421    fn show_snippet_choices(
 7422        &mut self,
 7423        choices: &Vec<String>,
 7424        selection: Range<Anchor>,
 7425        cx: &mut Context<Self>,
 7426    ) {
 7427        if selection.start.buffer_id.is_none() {
 7428            return;
 7429        }
 7430        let buffer_id = selection.start.buffer_id.unwrap();
 7431        let buffer = self.buffer().read(cx).buffer(buffer_id);
 7432        let id = post_inc(&mut self.next_completion_id);
 7433
 7434        if let Some(buffer) = buffer {
 7435            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 7436                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 7437            ));
 7438        }
 7439    }
 7440
 7441    pub fn insert_snippet(
 7442        &mut self,
 7443        insertion_ranges: &[Range<usize>],
 7444        snippet: Snippet,
 7445        window: &mut Window,
 7446        cx: &mut Context<Self>,
 7447    ) -> Result<()> {
 7448        struct Tabstop<T> {
 7449            is_end_tabstop: bool,
 7450            ranges: Vec<Range<T>>,
 7451            choices: Option<Vec<String>>,
 7452        }
 7453
 7454        let tabstops = self.buffer.update(cx, |buffer, cx| {
 7455            let snippet_text: Arc<str> = snippet.text.clone().into();
 7456            buffer.edit(
 7457                insertion_ranges
 7458                    .iter()
 7459                    .cloned()
 7460                    .map(|range| (range, snippet_text.clone())),
 7461                Some(AutoindentMode::EachLine),
 7462                cx,
 7463            );
 7464
 7465            let snapshot = &*buffer.read(cx);
 7466            let snippet = &snippet;
 7467            snippet
 7468                .tabstops
 7469                .iter()
 7470                .map(|tabstop| {
 7471                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 7472                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 7473                    });
 7474                    let mut tabstop_ranges = tabstop
 7475                        .ranges
 7476                        .iter()
 7477                        .flat_map(|tabstop_range| {
 7478                            let mut delta = 0_isize;
 7479                            insertion_ranges.iter().map(move |insertion_range| {
 7480                                let insertion_start = insertion_range.start as isize + delta;
 7481                                delta +=
 7482                                    snippet.text.len() as isize - insertion_range.len() as isize;
 7483
 7484                                let start = ((insertion_start + tabstop_range.start) as usize)
 7485                                    .min(snapshot.len());
 7486                                let end = ((insertion_start + tabstop_range.end) as usize)
 7487                                    .min(snapshot.len());
 7488                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 7489                            })
 7490                        })
 7491                        .collect::<Vec<_>>();
 7492                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 7493
 7494                    Tabstop {
 7495                        is_end_tabstop,
 7496                        ranges: tabstop_ranges,
 7497                        choices: tabstop.choices.clone(),
 7498                    }
 7499                })
 7500                .collect::<Vec<_>>()
 7501        });
 7502        if let Some(tabstop) = tabstops.first() {
 7503            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7504                s.select_ranges(tabstop.ranges.iter().cloned());
 7505            });
 7506
 7507            if let Some(choices) = &tabstop.choices {
 7508                if let Some(selection) = tabstop.ranges.first() {
 7509                    self.show_snippet_choices(choices, selection.clone(), cx)
 7510                }
 7511            }
 7512
 7513            // If we're already at the last tabstop and it's at the end of the snippet,
 7514            // we're done, we don't need to keep the state around.
 7515            if !tabstop.is_end_tabstop {
 7516                let choices = tabstops
 7517                    .iter()
 7518                    .map(|tabstop| tabstop.choices.clone())
 7519                    .collect();
 7520
 7521                let ranges = tabstops
 7522                    .into_iter()
 7523                    .map(|tabstop| tabstop.ranges)
 7524                    .collect::<Vec<_>>();
 7525
 7526                self.snippet_stack.push(SnippetState {
 7527                    active_index: 0,
 7528                    ranges,
 7529                    choices,
 7530                });
 7531            }
 7532
 7533            // Check whether the just-entered snippet ends with an auto-closable bracket.
 7534            if self.autoclose_regions.is_empty() {
 7535                let snapshot = self.buffer.read(cx).snapshot(cx);
 7536                for selection in &mut self.selections.all::<Point>(cx) {
 7537                    let selection_head = selection.head();
 7538                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 7539                        continue;
 7540                    };
 7541
 7542                    let mut bracket_pair = None;
 7543                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 7544                    let prev_chars = snapshot
 7545                        .reversed_chars_at(selection_head)
 7546                        .collect::<String>();
 7547                    for (pair, enabled) in scope.brackets() {
 7548                        if enabled
 7549                            && pair.close
 7550                            && prev_chars.starts_with(pair.start.as_str())
 7551                            && next_chars.starts_with(pair.end.as_str())
 7552                        {
 7553                            bracket_pair = Some(pair.clone());
 7554                            break;
 7555                        }
 7556                    }
 7557                    if let Some(pair) = bracket_pair {
 7558                        let start = snapshot.anchor_after(selection_head);
 7559                        let end = snapshot.anchor_after(selection_head);
 7560                        self.autoclose_regions.push(AutocloseRegion {
 7561                            selection_id: selection.id,
 7562                            range: start..end,
 7563                            pair,
 7564                        });
 7565                    }
 7566                }
 7567            }
 7568        }
 7569        Ok(())
 7570    }
 7571
 7572    pub fn move_to_next_snippet_tabstop(
 7573        &mut self,
 7574        window: &mut Window,
 7575        cx: &mut Context<Self>,
 7576    ) -> bool {
 7577        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 7578    }
 7579
 7580    pub fn move_to_prev_snippet_tabstop(
 7581        &mut self,
 7582        window: &mut Window,
 7583        cx: &mut Context<Self>,
 7584    ) -> bool {
 7585        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 7586    }
 7587
 7588    pub fn move_to_snippet_tabstop(
 7589        &mut self,
 7590        bias: Bias,
 7591        window: &mut Window,
 7592        cx: &mut Context<Self>,
 7593    ) -> bool {
 7594        if let Some(mut snippet) = self.snippet_stack.pop() {
 7595            match bias {
 7596                Bias::Left => {
 7597                    if snippet.active_index > 0 {
 7598                        snippet.active_index -= 1;
 7599                    } else {
 7600                        self.snippet_stack.push(snippet);
 7601                        return false;
 7602                    }
 7603                }
 7604                Bias::Right => {
 7605                    if snippet.active_index + 1 < snippet.ranges.len() {
 7606                        snippet.active_index += 1;
 7607                    } else {
 7608                        self.snippet_stack.push(snippet);
 7609                        return false;
 7610                    }
 7611                }
 7612            }
 7613            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 7614                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7615                    s.select_anchor_ranges(current_ranges.iter().cloned())
 7616                });
 7617
 7618                if let Some(choices) = &snippet.choices[snippet.active_index] {
 7619                    if let Some(selection) = current_ranges.first() {
 7620                        self.show_snippet_choices(&choices, selection.clone(), cx);
 7621                    }
 7622                }
 7623
 7624                // If snippet state is not at the last tabstop, push it back on the stack
 7625                if snippet.active_index + 1 < snippet.ranges.len() {
 7626                    self.snippet_stack.push(snippet);
 7627                }
 7628                return true;
 7629            }
 7630        }
 7631
 7632        false
 7633    }
 7634
 7635    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 7636        self.transact(window, cx, |this, window, cx| {
 7637            this.select_all(&SelectAll, window, cx);
 7638            this.insert("", window, cx);
 7639        });
 7640    }
 7641
 7642    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 7643        self.transact(window, cx, |this, window, cx| {
 7644            this.select_autoclose_pair(window, cx);
 7645            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 7646            if !this.linked_edit_ranges.is_empty() {
 7647                let selections = this.selections.all::<MultiBufferPoint>(cx);
 7648                let snapshot = this.buffer.read(cx).snapshot(cx);
 7649
 7650                for selection in selections.iter() {
 7651                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 7652                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 7653                    if selection_start.buffer_id != selection_end.buffer_id {
 7654                        continue;
 7655                    }
 7656                    if let Some(ranges) =
 7657                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 7658                    {
 7659                        for (buffer, entries) in ranges {
 7660                            linked_ranges.entry(buffer).or_default().extend(entries);
 7661                        }
 7662                    }
 7663                }
 7664            }
 7665
 7666            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 7667            if !this.selections.line_mode {
 7668                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 7669                for selection in &mut selections {
 7670                    if selection.is_empty() {
 7671                        let old_head = selection.head();
 7672                        let mut new_head =
 7673                            movement::left(&display_map, old_head.to_display_point(&display_map))
 7674                                .to_point(&display_map);
 7675                        if let Some((buffer, line_buffer_range)) = display_map
 7676                            .buffer_snapshot
 7677                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 7678                        {
 7679                            let indent_size =
 7680                                buffer.indent_size_for_line(line_buffer_range.start.row);
 7681                            let indent_len = match indent_size.kind {
 7682                                IndentKind::Space => {
 7683                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 7684                                }
 7685                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 7686                            };
 7687                            if old_head.column <= indent_size.len && old_head.column > 0 {
 7688                                let indent_len = indent_len.get();
 7689                                new_head = cmp::min(
 7690                                    new_head,
 7691                                    MultiBufferPoint::new(
 7692                                        old_head.row,
 7693                                        ((old_head.column - 1) / indent_len) * indent_len,
 7694                                    ),
 7695                                );
 7696                            }
 7697                        }
 7698
 7699                        selection.set_head(new_head, SelectionGoal::None);
 7700                    }
 7701                }
 7702            }
 7703
 7704            this.signature_help_state.set_backspace_pressed(true);
 7705            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7706                s.select(selections)
 7707            });
 7708            this.insert("", window, cx);
 7709            let empty_str: Arc<str> = Arc::from("");
 7710            for (buffer, edits) in linked_ranges {
 7711                let snapshot = buffer.read(cx).snapshot();
 7712                use text::ToPoint as TP;
 7713
 7714                let edits = edits
 7715                    .into_iter()
 7716                    .map(|range| {
 7717                        let end_point = TP::to_point(&range.end, &snapshot);
 7718                        let mut start_point = TP::to_point(&range.start, &snapshot);
 7719
 7720                        if end_point == start_point {
 7721                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 7722                                .saturating_sub(1);
 7723                            start_point =
 7724                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 7725                        };
 7726
 7727                        (start_point..end_point, empty_str.clone())
 7728                    })
 7729                    .sorted_by_key(|(range, _)| range.start)
 7730                    .collect::<Vec<_>>();
 7731                buffer.update(cx, |this, cx| {
 7732                    this.edit(edits, None, cx);
 7733                })
 7734            }
 7735            this.refresh_inline_completion(true, false, window, cx);
 7736            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 7737        });
 7738    }
 7739
 7740    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 7741        self.transact(window, cx, |this, window, cx| {
 7742            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7743                let line_mode = s.line_mode;
 7744                s.move_with(|map, selection| {
 7745                    if selection.is_empty() && !line_mode {
 7746                        let cursor = movement::right(map, selection.head());
 7747                        selection.end = cursor;
 7748                        selection.reversed = true;
 7749                        selection.goal = SelectionGoal::None;
 7750                    }
 7751                })
 7752            });
 7753            this.insert("", window, cx);
 7754            this.refresh_inline_completion(true, false, window, cx);
 7755        });
 7756    }
 7757
 7758    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 7759        if self.move_to_prev_snippet_tabstop(window, cx) {
 7760            return;
 7761        }
 7762
 7763        self.outdent(&Outdent, window, cx);
 7764    }
 7765
 7766    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 7767        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 7768            return;
 7769        }
 7770
 7771        let mut selections = self.selections.all_adjusted(cx);
 7772        let buffer = self.buffer.read(cx);
 7773        let snapshot = buffer.snapshot(cx);
 7774        let rows_iter = selections.iter().map(|s| s.head().row);
 7775        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 7776
 7777        let mut edits = Vec::new();
 7778        let mut prev_edited_row = 0;
 7779        let mut row_delta = 0;
 7780        for selection in &mut selections {
 7781            if selection.start.row != prev_edited_row {
 7782                row_delta = 0;
 7783            }
 7784            prev_edited_row = selection.end.row;
 7785
 7786            // If the selection is non-empty, then increase the indentation of the selected lines.
 7787            if !selection.is_empty() {
 7788                row_delta =
 7789                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7790                continue;
 7791            }
 7792
 7793            // If the selection is empty and the cursor is in the leading whitespace before the
 7794            // suggested indentation, then auto-indent the line.
 7795            let cursor = selection.head();
 7796            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 7797            if let Some(suggested_indent) =
 7798                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 7799            {
 7800                if cursor.column < suggested_indent.len
 7801                    && cursor.column <= current_indent.len
 7802                    && current_indent.len <= suggested_indent.len
 7803                {
 7804                    selection.start = Point::new(cursor.row, suggested_indent.len);
 7805                    selection.end = selection.start;
 7806                    if row_delta == 0 {
 7807                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 7808                            cursor.row,
 7809                            current_indent,
 7810                            suggested_indent,
 7811                        ));
 7812                        row_delta = suggested_indent.len - current_indent.len;
 7813                    }
 7814                    continue;
 7815                }
 7816            }
 7817
 7818            // Otherwise, insert a hard or soft tab.
 7819            let settings = buffer.language_settings_at(cursor, cx);
 7820            let tab_size = if settings.hard_tabs {
 7821                IndentSize::tab()
 7822            } else {
 7823                let tab_size = settings.tab_size.get();
 7824                let char_column = snapshot
 7825                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 7826                    .flat_map(str::chars)
 7827                    .count()
 7828                    + row_delta as usize;
 7829                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 7830                IndentSize::spaces(chars_to_next_tab_stop)
 7831            };
 7832            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 7833            selection.end = selection.start;
 7834            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 7835            row_delta += tab_size.len;
 7836        }
 7837
 7838        self.transact(window, cx, |this, window, cx| {
 7839            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7840            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7841                s.select(selections)
 7842            });
 7843            this.refresh_inline_completion(true, false, window, cx);
 7844        });
 7845    }
 7846
 7847    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 7848        if self.read_only(cx) {
 7849            return;
 7850        }
 7851        let mut selections = self.selections.all::<Point>(cx);
 7852        let mut prev_edited_row = 0;
 7853        let mut row_delta = 0;
 7854        let mut edits = Vec::new();
 7855        let buffer = self.buffer.read(cx);
 7856        let snapshot = buffer.snapshot(cx);
 7857        for selection in &mut selections {
 7858            if selection.start.row != prev_edited_row {
 7859                row_delta = 0;
 7860            }
 7861            prev_edited_row = selection.end.row;
 7862
 7863            row_delta =
 7864                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7865        }
 7866
 7867        self.transact(window, cx, |this, window, cx| {
 7868            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7869            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7870                s.select(selections)
 7871            });
 7872        });
 7873    }
 7874
 7875    fn indent_selection(
 7876        buffer: &MultiBuffer,
 7877        snapshot: &MultiBufferSnapshot,
 7878        selection: &mut Selection<Point>,
 7879        edits: &mut Vec<(Range<Point>, String)>,
 7880        delta_for_start_row: u32,
 7881        cx: &App,
 7882    ) -> u32 {
 7883        let settings = buffer.language_settings_at(selection.start, cx);
 7884        let tab_size = settings.tab_size.get();
 7885        let indent_kind = if settings.hard_tabs {
 7886            IndentKind::Tab
 7887        } else {
 7888            IndentKind::Space
 7889        };
 7890        let mut start_row = selection.start.row;
 7891        let mut end_row = selection.end.row + 1;
 7892
 7893        // If a selection ends at the beginning of a line, don't indent
 7894        // that last line.
 7895        if selection.end.column == 0 && selection.end.row > selection.start.row {
 7896            end_row -= 1;
 7897        }
 7898
 7899        // Avoid re-indenting a row that has already been indented by a
 7900        // previous selection, but still update this selection's column
 7901        // to reflect that indentation.
 7902        if delta_for_start_row > 0 {
 7903            start_row += 1;
 7904            selection.start.column += delta_for_start_row;
 7905            if selection.end.row == selection.start.row {
 7906                selection.end.column += delta_for_start_row;
 7907            }
 7908        }
 7909
 7910        let mut delta_for_end_row = 0;
 7911        let has_multiple_rows = start_row + 1 != end_row;
 7912        for row in start_row..end_row {
 7913            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 7914            let indent_delta = match (current_indent.kind, indent_kind) {
 7915                (IndentKind::Space, IndentKind::Space) => {
 7916                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 7917                    IndentSize::spaces(columns_to_next_tab_stop)
 7918                }
 7919                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 7920                (_, IndentKind::Tab) => IndentSize::tab(),
 7921            };
 7922
 7923            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 7924                0
 7925            } else {
 7926                selection.start.column
 7927            };
 7928            let row_start = Point::new(row, start);
 7929            edits.push((
 7930                row_start..row_start,
 7931                indent_delta.chars().collect::<String>(),
 7932            ));
 7933
 7934            // Update this selection's endpoints to reflect the indentation.
 7935            if row == selection.start.row {
 7936                selection.start.column += indent_delta.len;
 7937            }
 7938            if row == selection.end.row {
 7939                selection.end.column += indent_delta.len;
 7940                delta_for_end_row = indent_delta.len;
 7941            }
 7942        }
 7943
 7944        if selection.start.row == selection.end.row {
 7945            delta_for_start_row + delta_for_end_row
 7946        } else {
 7947            delta_for_end_row
 7948        }
 7949    }
 7950
 7951    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 7952        if self.read_only(cx) {
 7953            return;
 7954        }
 7955        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7956        let selections = self.selections.all::<Point>(cx);
 7957        let mut deletion_ranges = Vec::new();
 7958        let mut last_outdent = None;
 7959        {
 7960            let buffer = self.buffer.read(cx);
 7961            let snapshot = buffer.snapshot(cx);
 7962            for selection in &selections {
 7963                let settings = buffer.language_settings_at(selection.start, cx);
 7964                let tab_size = settings.tab_size.get();
 7965                let mut rows = selection.spanned_rows(false, &display_map);
 7966
 7967                // Avoid re-outdenting a row that has already been outdented by a
 7968                // previous selection.
 7969                if let Some(last_row) = last_outdent {
 7970                    if last_row == rows.start {
 7971                        rows.start = rows.start.next_row();
 7972                    }
 7973                }
 7974                let has_multiple_rows = rows.len() > 1;
 7975                for row in rows.iter_rows() {
 7976                    let indent_size = snapshot.indent_size_for_line(row);
 7977                    if indent_size.len > 0 {
 7978                        let deletion_len = match indent_size.kind {
 7979                            IndentKind::Space => {
 7980                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 7981                                if columns_to_prev_tab_stop == 0 {
 7982                                    tab_size
 7983                                } else {
 7984                                    columns_to_prev_tab_stop
 7985                                }
 7986                            }
 7987                            IndentKind::Tab => 1,
 7988                        };
 7989                        let start = if has_multiple_rows
 7990                            || deletion_len > selection.start.column
 7991                            || indent_size.len < selection.start.column
 7992                        {
 7993                            0
 7994                        } else {
 7995                            selection.start.column - deletion_len
 7996                        };
 7997                        deletion_ranges.push(
 7998                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 7999                        );
 8000                        last_outdent = Some(row);
 8001                    }
 8002                }
 8003            }
 8004        }
 8005
 8006        self.transact(window, cx, |this, window, cx| {
 8007            this.buffer.update(cx, |buffer, cx| {
 8008                let empty_str: Arc<str> = Arc::default();
 8009                buffer.edit(
 8010                    deletion_ranges
 8011                        .into_iter()
 8012                        .map(|range| (range, empty_str.clone())),
 8013                    None,
 8014                    cx,
 8015                );
 8016            });
 8017            let selections = this.selections.all::<usize>(cx);
 8018            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8019                s.select(selections)
 8020            });
 8021        });
 8022    }
 8023
 8024    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 8025        if self.read_only(cx) {
 8026            return;
 8027        }
 8028        let selections = self
 8029            .selections
 8030            .all::<usize>(cx)
 8031            .into_iter()
 8032            .map(|s| s.range());
 8033
 8034        self.transact(window, cx, |this, window, cx| {
 8035            this.buffer.update(cx, |buffer, cx| {
 8036                buffer.autoindent_ranges(selections, cx);
 8037            });
 8038            let selections = this.selections.all::<usize>(cx);
 8039            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8040                s.select(selections)
 8041            });
 8042        });
 8043    }
 8044
 8045    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 8046        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8047        let selections = self.selections.all::<Point>(cx);
 8048
 8049        let mut new_cursors = Vec::new();
 8050        let mut edit_ranges = Vec::new();
 8051        let mut selections = selections.iter().peekable();
 8052        while let Some(selection) = selections.next() {
 8053            let mut rows = selection.spanned_rows(false, &display_map);
 8054            let goal_display_column = selection.head().to_display_point(&display_map).column();
 8055
 8056            // Accumulate contiguous regions of rows that we want to delete.
 8057            while let Some(next_selection) = selections.peek() {
 8058                let next_rows = next_selection.spanned_rows(false, &display_map);
 8059                if next_rows.start <= rows.end {
 8060                    rows.end = next_rows.end;
 8061                    selections.next().unwrap();
 8062                } else {
 8063                    break;
 8064                }
 8065            }
 8066
 8067            let buffer = &display_map.buffer_snapshot;
 8068            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 8069            let edit_end;
 8070            let cursor_buffer_row;
 8071            if buffer.max_point().row >= rows.end.0 {
 8072                // If there's a line after the range, delete the \n from the end of the row range
 8073                // and position the cursor on the next line.
 8074                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 8075                cursor_buffer_row = rows.end;
 8076            } else {
 8077                // If there isn't a line after the range, delete the \n from the line before the
 8078                // start of the row range and position the cursor there.
 8079                edit_start = edit_start.saturating_sub(1);
 8080                edit_end = buffer.len();
 8081                cursor_buffer_row = rows.start.previous_row();
 8082            }
 8083
 8084            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 8085            *cursor.column_mut() =
 8086                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 8087
 8088            new_cursors.push((
 8089                selection.id,
 8090                buffer.anchor_after(cursor.to_point(&display_map)),
 8091            ));
 8092            edit_ranges.push(edit_start..edit_end);
 8093        }
 8094
 8095        self.transact(window, cx, |this, window, cx| {
 8096            let buffer = this.buffer.update(cx, |buffer, cx| {
 8097                let empty_str: Arc<str> = Arc::default();
 8098                buffer.edit(
 8099                    edit_ranges
 8100                        .into_iter()
 8101                        .map(|range| (range, empty_str.clone())),
 8102                    None,
 8103                    cx,
 8104                );
 8105                buffer.snapshot(cx)
 8106            });
 8107            let new_selections = new_cursors
 8108                .into_iter()
 8109                .map(|(id, cursor)| {
 8110                    let cursor = cursor.to_point(&buffer);
 8111                    Selection {
 8112                        id,
 8113                        start: cursor,
 8114                        end: cursor,
 8115                        reversed: false,
 8116                        goal: SelectionGoal::None,
 8117                    }
 8118                })
 8119                .collect();
 8120
 8121            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8122                s.select(new_selections);
 8123            });
 8124        });
 8125    }
 8126
 8127    pub fn join_lines_impl(
 8128        &mut self,
 8129        insert_whitespace: bool,
 8130        window: &mut Window,
 8131        cx: &mut Context<Self>,
 8132    ) {
 8133        if self.read_only(cx) {
 8134            return;
 8135        }
 8136        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 8137        for selection in self.selections.all::<Point>(cx) {
 8138            let start = MultiBufferRow(selection.start.row);
 8139            // Treat single line selections as if they include the next line. Otherwise this action
 8140            // would do nothing for single line selections individual cursors.
 8141            let end = if selection.start.row == selection.end.row {
 8142                MultiBufferRow(selection.start.row + 1)
 8143            } else {
 8144                MultiBufferRow(selection.end.row)
 8145            };
 8146
 8147            if let Some(last_row_range) = row_ranges.last_mut() {
 8148                if start <= last_row_range.end {
 8149                    last_row_range.end = end;
 8150                    continue;
 8151                }
 8152            }
 8153            row_ranges.push(start..end);
 8154        }
 8155
 8156        let snapshot = self.buffer.read(cx).snapshot(cx);
 8157        let mut cursor_positions = Vec::new();
 8158        for row_range in &row_ranges {
 8159            let anchor = snapshot.anchor_before(Point::new(
 8160                row_range.end.previous_row().0,
 8161                snapshot.line_len(row_range.end.previous_row()),
 8162            ));
 8163            cursor_positions.push(anchor..anchor);
 8164        }
 8165
 8166        self.transact(window, cx, |this, window, cx| {
 8167            for row_range in row_ranges.into_iter().rev() {
 8168                for row in row_range.iter_rows().rev() {
 8169                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 8170                    let next_line_row = row.next_row();
 8171                    let indent = snapshot.indent_size_for_line(next_line_row);
 8172                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 8173
 8174                    let replace =
 8175                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 8176                            " "
 8177                        } else {
 8178                            ""
 8179                        };
 8180
 8181                    this.buffer.update(cx, |buffer, cx| {
 8182                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 8183                    });
 8184                }
 8185            }
 8186
 8187            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8188                s.select_anchor_ranges(cursor_positions)
 8189            });
 8190        });
 8191    }
 8192
 8193    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 8194        self.join_lines_impl(true, window, cx);
 8195    }
 8196
 8197    pub fn sort_lines_case_sensitive(
 8198        &mut self,
 8199        _: &SortLinesCaseSensitive,
 8200        window: &mut Window,
 8201        cx: &mut Context<Self>,
 8202    ) {
 8203        self.manipulate_lines(window, cx, |lines| lines.sort())
 8204    }
 8205
 8206    pub fn sort_lines_case_insensitive(
 8207        &mut self,
 8208        _: &SortLinesCaseInsensitive,
 8209        window: &mut Window,
 8210        cx: &mut Context<Self>,
 8211    ) {
 8212        self.manipulate_lines(window, cx, |lines| {
 8213            lines.sort_by_key(|line| line.to_lowercase())
 8214        })
 8215    }
 8216
 8217    pub fn unique_lines_case_insensitive(
 8218        &mut self,
 8219        _: &UniqueLinesCaseInsensitive,
 8220        window: &mut Window,
 8221        cx: &mut Context<Self>,
 8222    ) {
 8223        self.manipulate_lines(window, cx, |lines| {
 8224            let mut seen = HashSet::default();
 8225            lines.retain(|line| seen.insert(line.to_lowercase()));
 8226        })
 8227    }
 8228
 8229    pub fn unique_lines_case_sensitive(
 8230        &mut self,
 8231        _: &UniqueLinesCaseSensitive,
 8232        window: &mut Window,
 8233        cx: &mut Context<Self>,
 8234    ) {
 8235        self.manipulate_lines(window, cx, |lines| {
 8236            let mut seen = HashSet::default();
 8237            lines.retain(|line| seen.insert(*line));
 8238        })
 8239    }
 8240
 8241    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 8242        let Some(project) = self.project.clone() else {
 8243            return;
 8244        };
 8245        self.reload(project, window, cx)
 8246            .detach_and_notify_err(window, cx);
 8247    }
 8248
 8249    pub fn restore_file(
 8250        &mut self,
 8251        _: &::git::RestoreFile,
 8252        window: &mut Window,
 8253        cx: &mut Context<Self>,
 8254    ) {
 8255        let mut buffer_ids = HashSet::default();
 8256        let snapshot = self.buffer().read(cx).snapshot(cx);
 8257        for selection in self.selections.all::<usize>(cx) {
 8258            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 8259        }
 8260
 8261        let buffer = self.buffer().read(cx);
 8262        let ranges = buffer_ids
 8263            .into_iter()
 8264            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 8265            .collect::<Vec<_>>();
 8266
 8267        self.restore_hunks_in_ranges(ranges, window, cx);
 8268    }
 8269
 8270    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 8271        let selections = self
 8272            .selections
 8273            .all(cx)
 8274            .into_iter()
 8275            .map(|s| s.range())
 8276            .collect();
 8277        self.restore_hunks_in_ranges(selections, window, cx);
 8278    }
 8279
 8280    fn restore_hunks_in_ranges(
 8281        &mut self,
 8282        ranges: Vec<Range<Point>>,
 8283        window: &mut Window,
 8284        cx: &mut Context<Editor>,
 8285    ) {
 8286        let mut revert_changes = HashMap::default();
 8287        let chunk_by = self
 8288            .snapshot(window, cx)
 8289            .hunks_for_ranges(ranges)
 8290            .into_iter()
 8291            .chunk_by(|hunk| hunk.buffer_id);
 8292        for (buffer_id, hunks) in &chunk_by {
 8293            let hunks = hunks.collect::<Vec<_>>();
 8294            for hunk in &hunks {
 8295                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 8296            }
 8297            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
 8298        }
 8299        drop(chunk_by);
 8300        if !revert_changes.is_empty() {
 8301            self.transact(window, cx, |editor, window, cx| {
 8302                editor.restore(revert_changes, window, cx);
 8303            });
 8304        }
 8305    }
 8306
 8307    pub fn open_active_item_in_terminal(
 8308        &mut self,
 8309        _: &OpenInTerminal,
 8310        window: &mut Window,
 8311        cx: &mut Context<Self>,
 8312    ) {
 8313        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 8314            let project_path = buffer.read(cx).project_path(cx)?;
 8315            let project = self.project.as_ref()?.read(cx);
 8316            let entry = project.entry_for_path(&project_path, cx)?;
 8317            let parent = match &entry.canonical_path {
 8318                Some(canonical_path) => canonical_path.to_path_buf(),
 8319                None => project.absolute_path(&project_path, cx)?,
 8320            }
 8321            .parent()?
 8322            .to_path_buf();
 8323            Some(parent)
 8324        }) {
 8325            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 8326        }
 8327    }
 8328
 8329    fn set_breakpoint_context_menu(
 8330        &mut self,
 8331        row: DisplayRow,
 8332        position: Option<Anchor>,
 8333        kind: Arc<BreakpointKind>,
 8334        clicked_point: gpui::Point<Pixels>,
 8335        window: &mut Window,
 8336        cx: &mut Context<Self>,
 8337    ) {
 8338        if !cx.has_flag::<Debugger>() {
 8339            return;
 8340        }
 8341        let source = self
 8342            .buffer
 8343            .read(cx)
 8344            .snapshot(cx)
 8345            .anchor_before(Point::new(row.0, 0u32));
 8346
 8347        let context_menu =
 8348            self.breakpoint_context_menu(position.unwrap_or(source), kind, window, cx);
 8349
 8350        self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
 8351            self,
 8352            source,
 8353            clicked_point,
 8354            context_menu,
 8355            window,
 8356            cx,
 8357        );
 8358    }
 8359
 8360    fn add_edit_breakpoint_block(
 8361        &mut self,
 8362        anchor: Anchor,
 8363        kind: &BreakpointKind,
 8364        window: &mut Window,
 8365        cx: &mut Context<Self>,
 8366    ) {
 8367        let weak_editor = cx.weak_entity();
 8368        let bp_prompt =
 8369            cx.new(|cx| BreakpointPromptEditor::new(weak_editor, anchor, kind.clone(), window, cx));
 8370
 8371        let height = bp_prompt.update(cx, |this, cx| {
 8372            this.prompt
 8373                .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
 8374        });
 8375        let cloned_prompt = bp_prompt.clone();
 8376        let blocks = vec![BlockProperties {
 8377            style: BlockStyle::Sticky,
 8378            placement: BlockPlacement::Above(anchor),
 8379            height,
 8380            render: Arc::new(move |cx| {
 8381                *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
 8382                cloned_prompt.clone().into_any_element()
 8383            }),
 8384            priority: 0,
 8385        }];
 8386
 8387        let focus_handle = bp_prompt.focus_handle(cx);
 8388        window.focus(&focus_handle);
 8389
 8390        let block_ids = self.insert_blocks(blocks, None, cx);
 8391        bp_prompt.update(cx, |prompt, _| {
 8392            prompt.add_block_ids(block_ids);
 8393        });
 8394    }
 8395
 8396    pub(crate) fn breakpoint_at_cursor_head(
 8397        &self,
 8398        window: &mut Window,
 8399        cx: &mut Context<Self>,
 8400    ) -> Option<(Anchor, Breakpoint)> {
 8401        let cursor_position: Point = self.selections.newest(cx).head();
 8402        let snapshot = self.snapshot(window, cx);
 8403        // We Set the column position to zero so this function interacts correctly
 8404        // between calls by clicking on the gutter & using an action to toggle a
 8405        // breakpoint. Otherwise, toggling a breakpoint through an action wouldn't
 8406        // untoggle a breakpoint that was added through clicking on the gutter
 8407        let cursor_position = snapshot
 8408            .display_snapshot
 8409            .buffer_snapshot
 8410            .anchor_before(Point::new(cursor_position.row, 0));
 8411
 8412        let project = self.project.clone();
 8413
 8414        let buffer_id = cursor_position.text_anchor.buffer_id?;
 8415        let enclosing_excerpt = snapshot
 8416            .buffer_snapshot
 8417            .excerpt_ids_for_range(cursor_position..cursor_position)
 8418            .next()?;
 8419        let buffer = project?.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
 8420        let buffer_snapshot = buffer.read(cx).snapshot();
 8421
 8422        let row = buffer_snapshot
 8423            .summary_for_anchor::<text::PointUtf16>(&cursor_position.text_anchor)
 8424            .row;
 8425
 8426        let bp = self
 8427            .breakpoint_store
 8428            .as_ref()?
 8429            .read_with(cx, |breakpoint_store, cx| {
 8430                breakpoint_store
 8431                    .breakpoints(
 8432                        &buffer,
 8433                        Some(cursor_position.text_anchor..(text::Anchor::MAX)),
 8434                        buffer_snapshot.clone(),
 8435                        cx,
 8436                    )
 8437                    .next()
 8438                    .and_then(move |(anchor, bp)| {
 8439                        let breakpoint_row = buffer_snapshot
 8440                            .summary_for_anchor::<text::PointUtf16>(anchor)
 8441                            .row;
 8442
 8443                        if breakpoint_row == row {
 8444                            snapshot
 8445                                .buffer_snapshot
 8446                                .anchor_in_excerpt(enclosing_excerpt, *anchor)
 8447                                .map(|anchor| (anchor, bp.clone()))
 8448                        } else {
 8449                            None
 8450                        }
 8451                    })
 8452            });
 8453        bp
 8454    }
 8455
 8456    pub fn edit_log_breakpoint(
 8457        &mut self,
 8458        _: &EditLogBreakpoint,
 8459        window: &mut Window,
 8460        cx: &mut Context<Self>,
 8461    ) {
 8462        let (anchor, bp) = self
 8463            .breakpoint_at_cursor_head(window, cx)
 8464            .unwrap_or_else(|| {
 8465                let cursor_position: Point = self.selections.newest(cx).head();
 8466
 8467                let breakpoint_position = self
 8468                    .snapshot(window, cx)
 8469                    .display_snapshot
 8470                    .buffer_snapshot
 8471                    .anchor_before(Point::new(cursor_position.row, 0));
 8472
 8473                (
 8474                    breakpoint_position,
 8475                    Breakpoint {
 8476                        kind: BreakpointKind::Standard,
 8477                    },
 8478                )
 8479            });
 8480
 8481        self.add_edit_breakpoint_block(anchor, &bp.kind, window, cx);
 8482    }
 8483
 8484    pub fn toggle_breakpoint(
 8485        &mut self,
 8486        _: &crate::actions::ToggleBreakpoint,
 8487        window: &mut Window,
 8488        cx: &mut Context<Self>,
 8489    ) {
 8490        let edit_action = BreakpointEditAction::Toggle;
 8491
 8492        if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
 8493            self.edit_breakpoint_at_anchor(anchor, breakpoint.kind, edit_action, cx);
 8494        } else {
 8495            let cursor_position: Point = self.selections.newest(cx).head();
 8496
 8497            let breakpoint_position = self
 8498                .snapshot(window, cx)
 8499                .display_snapshot
 8500                .buffer_snapshot
 8501                .anchor_before(Point::new(cursor_position.row, 0));
 8502
 8503            self.edit_breakpoint_at_anchor(
 8504                breakpoint_position,
 8505                BreakpointKind::Standard,
 8506                edit_action,
 8507                cx,
 8508            );
 8509        }
 8510    }
 8511
 8512    pub fn edit_breakpoint_at_anchor(
 8513        &mut self,
 8514        breakpoint_position: Anchor,
 8515        kind: BreakpointKind,
 8516        edit_action: BreakpointEditAction,
 8517        cx: &mut Context<Self>,
 8518    ) {
 8519        let Some(breakpoint_store) = &self.breakpoint_store else {
 8520            return;
 8521        };
 8522
 8523        let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
 8524            if breakpoint_position == Anchor::min() {
 8525                self.buffer()
 8526                    .read(cx)
 8527                    .excerpt_buffer_ids()
 8528                    .into_iter()
 8529                    .next()
 8530            } else {
 8531                None
 8532            }
 8533        }) else {
 8534            return;
 8535        };
 8536
 8537        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
 8538            return;
 8539        };
 8540
 8541        breakpoint_store.update(cx, |breakpoint_store, cx| {
 8542            breakpoint_store.toggle_breakpoint(
 8543                buffer,
 8544                (breakpoint_position.text_anchor, Breakpoint { kind }),
 8545                edit_action,
 8546                cx,
 8547            );
 8548        });
 8549
 8550        cx.notify();
 8551    }
 8552
 8553    #[cfg(any(test, feature = "test-support"))]
 8554    pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
 8555        self.breakpoint_store.clone()
 8556    }
 8557
 8558    pub fn prepare_restore_change(
 8559        &self,
 8560        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 8561        hunk: &MultiBufferDiffHunk,
 8562        cx: &mut App,
 8563    ) -> Option<()> {
 8564        if hunk.is_created_file() {
 8565            return None;
 8566        }
 8567        let buffer = self.buffer.read(cx);
 8568        let diff = buffer.diff_for(hunk.buffer_id)?;
 8569        let buffer = buffer.buffer(hunk.buffer_id)?;
 8570        let buffer = buffer.read(cx);
 8571        let original_text = diff
 8572            .read(cx)
 8573            .base_text()
 8574            .as_rope()
 8575            .slice(hunk.diff_base_byte_range.clone());
 8576        let buffer_snapshot = buffer.snapshot();
 8577        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 8578        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 8579            probe
 8580                .0
 8581                .start
 8582                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 8583                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 8584        }) {
 8585            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 8586            Some(())
 8587        } else {
 8588            None
 8589        }
 8590    }
 8591
 8592    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 8593        self.manipulate_lines(window, cx, |lines| lines.reverse())
 8594    }
 8595
 8596    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 8597        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 8598    }
 8599
 8600    fn manipulate_lines<Fn>(
 8601        &mut self,
 8602        window: &mut Window,
 8603        cx: &mut Context<Self>,
 8604        mut callback: Fn,
 8605    ) where
 8606        Fn: FnMut(&mut Vec<&str>),
 8607    {
 8608        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8609        let buffer = self.buffer.read(cx).snapshot(cx);
 8610
 8611        let mut edits = Vec::new();
 8612
 8613        let selections = self.selections.all::<Point>(cx);
 8614        let mut selections = selections.iter().peekable();
 8615        let mut contiguous_row_selections = Vec::new();
 8616        let mut new_selections = Vec::new();
 8617        let mut added_lines = 0;
 8618        let mut removed_lines = 0;
 8619
 8620        while let Some(selection) = selections.next() {
 8621            let (start_row, end_row) = consume_contiguous_rows(
 8622                &mut contiguous_row_selections,
 8623                selection,
 8624                &display_map,
 8625                &mut selections,
 8626            );
 8627
 8628            let start_point = Point::new(start_row.0, 0);
 8629            let end_point = Point::new(
 8630                end_row.previous_row().0,
 8631                buffer.line_len(end_row.previous_row()),
 8632            );
 8633            let text = buffer
 8634                .text_for_range(start_point..end_point)
 8635                .collect::<String>();
 8636
 8637            let mut lines = text.split('\n').collect_vec();
 8638
 8639            let lines_before = lines.len();
 8640            callback(&mut lines);
 8641            let lines_after = lines.len();
 8642
 8643            edits.push((start_point..end_point, lines.join("\n")));
 8644
 8645            // Selections must change based on added and removed line count
 8646            let start_row =
 8647                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 8648            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 8649            new_selections.push(Selection {
 8650                id: selection.id,
 8651                start: start_row,
 8652                end: end_row,
 8653                goal: SelectionGoal::None,
 8654                reversed: selection.reversed,
 8655            });
 8656
 8657            if lines_after > lines_before {
 8658                added_lines += lines_after - lines_before;
 8659            } else if lines_before > lines_after {
 8660                removed_lines += lines_before - lines_after;
 8661            }
 8662        }
 8663
 8664        self.transact(window, cx, |this, window, cx| {
 8665            let buffer = this.buffer.update(cx, |buffer, cx| {
 8666                buffer.edit(edits, None, cx);
 8667                buffer.snapshot(cx)
 8668            });
 8669
 8670            // Recalculate offsets on newly edited buffer
 8671            let new_selections = new_selections
 8672                .iter()
 8673                .map(|s| {
 8674                    let start_point = Point::new(s.start.0, 0);
 8675                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 8676                    Selection {
 8677                        id: s.id,
 8678                        start: buffer.point_to_offset(start_point),
 8679                        end: buffer.point_to_offset(end_point),
 8680                        goal: s.goal,
 8681                        reversed: s.reversed,
 8682                    }
 8683                })
 8684                .collect();
 8685
 8686            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8687                s.select(new_selections);
 8688            });
 8689
 8690            this.request_autoscroll(Autoscroll::fit(), cx);
 8691        });
 8692    }
 8693
 8694    pub fn convert_to_upper_case(
 8695        &mut self,
 8696        _: &ConvertToUpperCase,
 8697        window: &mut Window,
 8698        cx: &mut Context<Self>,
 8699    ) {
 8700        self.manipulate_text(window, cx, |text| text.to_uppercase())
 8701    }
 8702
 8703    pub fn convert_to_lower_case(
 8704        &mut self,
 8705        _: &ConvertToLowerCase,
 8706        window: &mut Window,
 8707        cx: &mut Context<Self>,
 8708    ) {
 8709        self.manipulate_text(window, cx, |text| text.to_lowercase())
 8710    }
 8711
 8712    pub fn convert_to_title_case(
 8713        &mut self,
 8714        _: &ConvertToTitleCase,
 8715        window: &mut Window,
 8716        cx: &mut Context<Self>,
 8717    ) {
 8718        self.manipulate_text(window, cx, |text| {
 8719            text.split('\n')
 8720                .map(|line| line.to_case(Case::Title))
 8721                .join("\n")
 8722        })
 8723    }
 8724
 8725    pub fn convert_to_snake_case(
 8726        &mut self,
 8727        _: &ConvertToSnakeCase,
 8728        window: &mut Window,
 8729        cx: &mut Context<Self>,
 8730    ) {
 8731        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 8732    }
 8733
 8734    pub fn convert_to_kebab_case(
 8735        &mut self,
 8736        _: &ConvertToKebabCase,
 8737        window: &mut Window,
 8738        cx: &mut Context<Self>,
 8739    ) {
 8740        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 8741    }
 8742
 8743    pub fn convert_to_upper_camel_case(
 8744        &mut self,
 8745        _: &ConvertToUpperCamelCase,
 8746        window: &mut Window,
 8747        cx: &mut Context<Self>,
 8748    ) {
 8749        self.manipulate_text(window, cx, |text| {
 8750            text.split('\n')
 8751                .map(|line| line.to_case(Case::UpperCamel))
 8752                .join("\n")
 8753        })
 8754    }
 8755
 8756    pub fn convert_to_lower_camel_case(
 8757        &mut self,
 8758        _: &ConvertToLowerCamelCase,
 8759        window: &mut Window,
 8760        cx: &mut Context<Self>,
 8761    ) {
 8762        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 8763    }
 8764
 8765    pub fn convert_to_opposite_case(
 8766        &mut self,
 8767        _: &ConvertToOppositeCase,
 8768        window: &mut Window,
 8769        cx: &mut Context<Self>,
 8770    ) {
 8771        self.manipulate_text(window, cx, |text| {
 8772            text.chars()
 8773                .fold(String::with_capacity(text.len()), |mut t, c| {
 8774                    if c.is_uppercase() {
 8775                        t.extend(c.to_lowercase());
 8776                    } else {
 8777                        t.extend(c.to_uppercase());
 8778                    }
 8779                    t
 8780                })
 8781        })
 8782    }
 8783
 8784    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 8785    where
 8786        Fn: FnMut(&str) -> String,
 8787    {
 8788        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8789        let buffer = self.buffer.read(cx).snapshot(cx);
 8790
 8791        let mut new_selections = Vec::new();
 8792        let mut edits = Vec::new();
 8793        let mut selection_adjustment = 0i32;
 8794
 8795        for selection in self.selections.all::<usize>(cx) {
 8796            let selection_is_empty = selection.is_empty();
 8797
 8798            let (start, end) = if selection_is_empty {
 8799                let word_range = movement::surrounding_word(
 8800                    &display_map,
 8801                    selection.start.to_display_point(&display_map),
 8802                );
 8803                let start = word_range.start.to_offset(&display_map, Bias::Left);
 8804                let end = word_range.end.to_offset(&display_map, Bias::Left);
 8805                (start, end)
 8806            } else {
 8807                (selection.start, selection.end)
 8808            };
 8809
 8810            let text = buffer.text_for_range(start..end).collect::<String>();
 8811            let old_length = text.len() as i32;
 8812            let text = callback(&text);
 8813
 8814            new_selections.push(Selection {
 8815                start: (start as i32 - selection_adjustment) as usize,
 8816                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 8817                goal: SelectionGoal::None,
 8818                ..selection
 8819            });
 8820
 8821            selection_adjustment += old_length - text.len() as i32;
 8822
 8823            edits.push((start..end, text));
 8824        }
 8825
 8826        self.transact(window, cx, |this, window, cx| {
 8827            this.buffer.update(cx, |buffer, cx| {
 8828                buffer.edit(edits, None, cx);
 8829            });
 8830
 8831            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8832                s.select(new_selections);
 8833            });
 8834
 8835            this.request_autoscroll(Autoscroll::fit(), cx);
 8836        });
 8837    }
 8838
 8839    pub fn duplicate(
 8840        &mut self,
 8841        upwards: bool,
 8842        whole_lines: bool,
 8843        window: &mut Window,
 8844        cx: &mut Context<Self>,
 8845    ) {
 8846        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8847        let buffer = &display_map.buffer_snapshot;
 8848        let selections = self.selections.all::<Point>(cx);
 8849
 8850        let mut edits = Vec::new();
 8851        let mut selections_iter = selections.iter().peekable();
 8852        while let Some(selection) = selections_iter.next() {
 8853            let mut rows = selection.spanned_rows(false, &display_map);
 8854            // duplicate line-wise
 8855            if whole_lines || selection.start == selection.end {
 8856                // Avoid duplicating the same lines twice.
 8857                while let Some(next_selection) = selections_iter.peek() {
 8858                    let next_rows = next_selection.spanned_rows(false, &display_map);
 8859                    if next_rows.start < rows.end {
 8860                        rows.end = next_rows.end;
 8861                        selections_iter.next().unwrap();
 8862                    } else {
 8863                        break;
 8864                    }
 8865                }
 8866
 8867                // Copy the text from the selected row region and splice it either at the start
 8868                // or end of the region.
 8869                let start = Point::new(rows.start.0, 0);
 8870                let end = Point::new(
 8871                    rows.end.previous_row().0,
 8872                    buffer.line_len(rows.end.previous_row()),
 8873                );
 8874                let text = buffer
 8875                    .text_for_range(start..end)
 8876                    .chain(Some("\n"))
 8877                    .collect::<String>();
 8878                let insert_location = if upwards {
 8879                    Point::new(rows.end.0, 0)
 8880                } else {
 8881                    start
 8882                };
 8883                edits.push((insert_location..insert_location, text));
 8884            } else {
 8885                // duplicate character-wise
 8886                let start = selection.start;
 8887                let end = selection.end;
 8888                let text = buffer.text_for_range(start..end).collect::<String>();
 8889                edits.push((selection.end..selection.end, text));
 8890            }
 8891        }
 8892
 8893        self.transact(window, cx, |this, _, cx| {
 8894            this.buffer.update(cx, |buffer, cx| {
 8895                buffer.edit(edits, None, cx);
 8896            });
 8897
 8898            this.request_autoscroll(Autoscroll::fit(), cx);
 8899        });
 8900    }
 8901
 8902    pub fn duplicate_line_up(
 8903        &mut self,
 8904        _: &DuplicateLineUp,
 8905        window: &mut Window,
 8906        cx: &mut Context<Self>,
 8907    ) {
 8908        self.duplicate(true, true, window, cx);
 8909    }
 8910
 8911    pub fn duplicate_line_down(
 8912        &mut self,
 8913        _: &DuplicateLineDown,
 8914        window: &mut Window,
 8915        cx: &mut Context<Self>,
 8916    ) {
 8917        self.duplicate(false, true, window, cx);
 8918    }
 8919
 8920    pub fn duplicate_selection(
 8921        &mut self,
 8922        _: &DuplicateSelection,
 8923        window: &mut Window,
 8924        cx: &mut Context<Self>,
 8925    ) {
 8926        self.duplicate(false, false, window, cx);
 8927    }
 8928
 8929    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 8930        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8931        let buffer = self.buffer.read(cx).snapshot(cx);
 8932
 8933        let mut edits = Vec::new();
 8934        let mut unfold_ranges = Vec::new();
 8935        let mut refold_creases = Vec::new();
 8936
 8937        let selections = self.selections.all::<Point>(cx);
 8938        let mut selections = selections.iter().peekable();
 8939        let mut contiguous_row_selections = Vec::new();
 8940        let mut new_selections = Vec::new();
 8941
 8942        while let Some(selection) = selections.next() {
 8943            // Find all the selections that span a contiguous row range
 8944            let (start_row, end_row) = consume_contiguous_rows(
 8945                &mut contiguous_row_selections,
 8946                selection,
 8947                &display_map,
 8948                &mut selections,
 8949            );
 8950
 8951            // Move the text spanned by the row range to be before the line preceding the row range
 8952            if start_row.0 > 0 {
 8953                let range_to_move = Point::new(
 8954                    start_row.previous_row().0,
 8955                    buffer.line_len(start_row.previous_row()),
 8956                )
 8957                    ..Point::new(
 8958                        end_row.previous_row().0,
 8959                        buffer.line_len(end_row.previous_row()),
 8960                    );
 8961                let insertion_point = display_map
 8962                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 8963                    .0;
 8964
 8965                // Don't move lines across excerpts
 8966                if buffer
 8967                    .excerpt_containing(insertion_point..range_to_move.end)
 8968                    .is_some()
 8969                {
 8970                    let text = buffer
 8971                        .text_for_range(range_to_move.clone())
 8972                        .flat_map(|s| s.chars())
 8973                        .skip(1)
 8974                        .chain(['\n'])
 8975                        .collect::<String>();
 8976
 8977                    edits.push((
 8978                        buffer.anchor_after(range_to_move.start)
 8979                            ..buffer.anchor_before(range_to_move.end),
 8980                        String::new(),
 8981                    ));
 8982                    let insertion_anchor = buffer.anchor_after(insertion_point);
 8983                    edits.push((insertion_anchor..insertion_anchor, text));
 8984
 8985                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 8986
 8987                    // Move selections up
 8988                    new_selections.extend(contiguous_row_selections.drain(..).map(
 8989                        |mut selection| {
 8990                            selection.start.row -= row_delta;
 8991                            selection.end.row -= row_delta;
 8992                            selection
 8993                        },
 8994                    ));
 8995
 8996                    // Move folds up
 8997                    unfold_ranges.push(range_to_move.clone());
 8998                    for fold in display_map.folds_in_range(
 8999                        buffer.anchor_before(range_to_move.start)
 9000                            ..buffer.anchor_after(range_to_move.end),
 9001                    ) {
 9002                        let mut start = fold.range.start.to_point(&buffer);
 9003                        let mut end = fold.range.end.to_point(&buffer);
 9004                        start.row -= row_delta;
 9005                        end.row -= row_delta;
 9006                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9007                    }
 9008                }
 9009            }
 9010
 9011            // If we didn't move line(s), preserve the existing selections
 9012            new_selections.append(&mut contiguous_row_selections);
 9013        }
 9014
 9015        self.transact(window, cx, |this, window, cx| {
 9016            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9017            this.buffer.update(cx, |buffer, cx| {
 9018                for (range, text) in edits {
 9019                    buffer.edit([(range, text)], None, cx);
 9020                }
 9021            });
 9022            this.fold_creases(refold_creases, true, window, cx);
 9023            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9024                s.select(new_selections);
 9025            })
 9026        });
 9027    }
 9028
 9029    pub fn move_line_down(
 9030        &mut self,
 9031        _: &MoveLineDown,
 9032        window: &mut Window,
 9033        cx: &mut Context<Self>,
 9034    ) {
 9035        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9036        let buffer = self.buffer.read(cx).snapshot(cx);
 9037
 9038        let mut edits = Vec::new();
 9039        let mut unfold_ranges = Vec::new();
 9040        let mut refold_creases = Vec::new();
 9041
 9042        let selections = self.selections.all::<Point>(cx);
 9043        let mut selections = selections.iter().peekable();
 9044        let mut contiguous_row_selections = Vec::new();
 9045        let mut new_selections = Vec::new();
 9046
 9047        while let Some(selection) = selections.next() {
 9048            // Find all the selections that span a contiguous row range
 9049            let (start_row, end_row) = consume_contiguous_rows(
 9050                &mut contiguous_row_selections,
 9051                selection,
 9052                &display_map,
 9053                &mut selections,
 9054            );
 9055
 9056            // Move the text spanned by the row range to be after the last line of the row range
 9057            if end_row.0 <= buffer.max_point().row {
 9058                let range_to_move =
 9059                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 9060                let insertion_point = display_map
 9061                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 9062                    .0;
 9063
 9064                // Don't move lines across excerpt boundaries
 9065                if buffer
 9066                    .excerpt_containing(range_to_move.start..insertion_point)
 9067                    .is_some()
 9068                {
 9069                    let mut text = String::from("\n");
 9070                    text.extend(buffer.text_for_range(range_to_move.clone()));
 9071                    text.pop(); // Drop trailing newline
 9072                    edits.push((
 9073                        buffer.anchor_after(range_to_move.start)
 9074                            ..buffer.anchor_before(range_to_move.end),
 9075                        String::new(),
 9076                    ));
 9077                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9078                    edits.push((insertion_anchor..insertion_anchor, text));
 9079
 9080                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 9081
 9082                    // Move selections down
 9083                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9084                        |mut selection| {
 9085                            selection.start.row += row_delta;
 9086                            selection.end.row += row_delta;
 9087                            selection
 9088                        },
 9089                    ));
 9090
 9091                    // Move folds down
 9092                    unfold_ranges.push(range_to_move.clone());
 9093                    for fold in display_map.folds_in_range(
 9094                        buffer.anchor_before(range_to_move.start)
 9095                            ..buffer.anchor_after(range_to_move.end),
 9096                    ) {
 9097                        let mut start = fold.range.start.to_point(&buffer);
 9098                        let mut end = fold.range.end.to_point(&buffer);
 9099                        start.row += row_delta;
 9100                        end.row += row_delta;
 9101                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9102                    }
 9103                }
 9104            }
 9105
 9106            // If we didn't move line(s), preserve the existing selections
 9107            new_selections.append(&mut contiguous_row_selections);
 9108        }
 9109
 9110        self.transact(window, cx, |this, window, cx| {
 9111            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9112            this.buffer.update(cx, |buffer, cx| {
 9113                for (range, text) in edits {
 9114                    buffer.edit([(range, text)], None, cx);
 9115                }
 9116            });
 9117            this.fold_creases(refold_creases, true, window, cx);
 9118            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9119                s.select(new_selections)
 9120            });
 9121        });
 9122    }
 9123
 9124    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 9125        let text_layout_details = &self.text_layout_details(window);
 9126        self.transact(window, cx, |this, window, cx| {
 9127            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9128                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 9129                let line_mode = s.line_mode;
 9130                s.move_with(|display_map, selection| {
 9131                    if !selection.is_empty() || line_mode {
 9132                        return;
 9133                    }
 9134
 9135                    let mut head = selection.head();
 9136                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 9137                    if head.column() == display_map.line_len(head.row()) {
 9138                        transpose_offset = display_map
 9139                            .buffer_snapshot
 9140                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9141                    }
 9142
 9143                    if transpose_offset == 0 {
 9144                        return;
 9145                    }
 9146
 9147                    *head.column_mut() += 1;
 9148                    head = display_map.clip_point(head, Bias::Right);
 9149                    let goal = SelectionGoal::HorizontalPosition(
 9150                        display_map
 9151                            .x_for_display_point(head, text_layout_details)
 9152                            .into(),
 9153                    );
 9154                    selection.collapse_to(head, goal);
 9155
 9156                    let transpose_start = display_map
 9157                        .buffer_snapshot
 9158                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9159                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 9160                        let transpose_end = display_map
 9161                            .buffer_snapshot
 9162                            .clip_offset(transpose_offset + 1, Bias::Right);
 9163                        if let Some(ch) =
 9164                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 9165                        {
 9166                            edits.push((transpose_start..transpose_offset, String::new()));
 9167                            edits.push((transpose_end..transpose_end, ch.to_string()));
 9168                        }
 9169                    }
 9170                });
 9171                edits
 9172            });
 9173            this.buffer
 9174                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 9175            let selections = this.selections.all::<usize>(cx);
 9176            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9177                s.select(selections);
 9178            });
 9179        });
 9180    }
 9181
 9182    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 9183        self.rewrap_impl(RewrapOptions::default(), cx)
 9184    }
 9185
 9186    pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
 9187        let buffer = self.buffer.read(cx).snapshot(cx);
 9188        let selections = self.selections.all::<Point>(cx);
 9189        let mut selections = selections.iter().peekable();
 9190
 9191        let mut edits = Vec::new();
 9192        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 9193
 9194        while let Some(selection) = selections.next() {
 9195            let mut start_row = selection.start.row;
 9196            let mut end_row = selection.end.row;
 9197
 9198            // Skip selections that overlap with a range that has already been rewrapped.
 9199            let selection_range = start_row..end_row;
 9200            if rewrapped_row_ranges
 9201                .iter()
 9202                .any(|range| range.overlaps(&selection_range))
 9203            {
 9204                continue;
 9205            }
 9206
 9207            let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
 9208
 9209            // Since not all lines in the selection may be at the same indent
 9210            // level, choose the indent size that is the most common between all
 9211            // of the lines.
 9212            //
 9213            // If there is a tie, we use the deepest indent.
 9214            let (indent_size, indent_end) = {
 9215                let mut indent_size_occurrences = HashMap::default();
 9216                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 9217
 9218                for row in start_row..=end_row {
 9219                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 9220                    rows_by_indent_size.entry(indent).or_default().push(row);
 9221                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 9222                }
 9223
 9224                let indent_size = indent_size_occurrences
 9225                    .into_iter()
 9226                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 9227                    .map(|(indent, _)| indent)
 9228                    .unwrap_or_default();
 9229                let row = rows_by_indent_size[&indent_size][0];
 9230                let indent_end = Point::new(row, indent_size.len);
 9231
 9232                (indent_size, indent_end)
 9233            };
 9234
 9235            let mut line_prefix = indent_size.chars().collect::<String>();
 9236
 9237            let mut inside_comment = false;
 9238            if let Some(comment_prefix) =
 9239                buffer
 9240                    .language_scope_at(selection.head())
 9241                    .and_then(|language| {
 9242                        language
 9243                            .line_comment_prefixes()
 9244                            .iter()
 9245                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 9246                            .cloned()
 9247                    })
 9248            {
 9249                line_prefix.push_str(&comment_prefix);
 9250                inside_comment = true;
 9251            }
 9252
 9253            let language_settings = buffer.language_settings_at(selection.head(), cx);
 9254            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 9255                RewrapBehavior::InComments => inside_comment,
 9256                RewrapBehavior::InSelections => !selection.is_empty(),
 9257                RewrapBehavior::Anywhere => true,
 9258            };
 9259
 9260            let should_rewrap = options.override_language_settings
 9261                || allow_rewrap_based_on_language
 9262                || self.hard_wrap.is_some();
 9263            if !should_rewrap {
 9264                continue;
 9265            }
 9266
 9267            if selection.is_empty() {
 9268                'expand_upwards: while start_row > 0 {
 9269                    let prev_row = start_row - 1;
 9270                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 9271                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 9272                    {
 9273                        start_row = prev_row;
 9274                    } else {
 9275                        break 'expand_upwards;
 9276                    }
 9277                }
 9278
 9279                'expand_downwards: while end_row < buffer.max_point().row {
 9280                    let next_row = end_row + 1;
 9281                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 9282                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 9283                    {
 9284                        end_row = next_row;
 9285                    } else {
 9286                        break 'expand_downwards;
 9287                    }
 9288                }
 9289            }
 9290
 9291            let start = Point::new(start_row, 0);
 9292            let start_offset = start.to_offset(&buffer);
 9293            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 9294            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 9295            let Some(lines_without_prefixes) = selection_text
 9296                .lines()
 9297                .map(|line| {
 9298                    line.strip_prefix(&line_prefix)
 9299                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 9300                        .ok_or_else(|| {
 9301                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 9302                        })
 9303                })
 9304                .collect::<Result<Vec<_>, _>>()
 9305                .log_err()
 9306            else {
 9307                continue;
 9308            };
 9309
 9310            let wrap_column = self.hard_wrap.unwrap_or_else(|| {
 9311                buffer
 9312                    .language_settings_at(Point::new(start_row, 0), cx)
 9313                    .preferred_line_length as usize
 9314            });
 9315            let wrapped_text = wrap_with_prefix(
 9316                line_prefix,
 9317                lines_without_prefixes.join("\n"),
 9318                wrap_column,
 9319                tab_size,
 9320                options.preserve_existing_whitespace,
 9321            );
 9322
 9323            // TODO: should always use char-based diff while still supporting cursor behavior that
 9324            // matches vim.
 9325            let mut diff_options = DiffOptions::default();
 9326            if options.override_language_settings {
 9327                diff_options.max_word_diff_len = 0;
 9328                diff_options.max_word_diff_line_count = 0;
 9329            } else {
 9330                diff_options.max_word_diff_len = usize::MAX;
 9331                diff_options.max_word_diff_line_count = usize::MAX;
 9332            }
 9333
 9334            for (old_range, new_text) in
 9335                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
 9336            {
 9337                let edit_start = buffer.anchor_after(start_offset + old_range.start);
 9338                let edit_end = buffer.anchor_after(start_offset + old_range.end);
 9339                edits.push((edit_start..edit_end, new_text));
 9340            }
 9341
 9342            rewrapped_row_ranges.push(start_row..=end_row);
 9343        }
 9344
 9345        self.buffer
 9346            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 9347    }
 9348
 9349    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 9350        let mut text = String::new();
 9351        let buffer = self.buffer.read(cx).snapshot(cx);
 9352        let mut selections = self.selections.all::<Point>(cx);
 9353        let mut clipboard_selections = Vec::with_capacity(selections.len());
 9354        {
 9355            let max_point = buffer.max_point();
 9356            let mut is_first = true;
 9357            for selection in &mut selections {
 9358                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 9359                if is_entire_line {
 9360                    selection.start = Point::new(selection.start.row, 0);
 9361                    if !selection.is_empty() && selection.end.column == 0 {
 9362                        selection.end = cmp::min(max_point, selection.end);
 9363                    } else {
 9364                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 9365                    }
 9366                    selection.goal = SelectionGoal::None;
 9367                }
 9368                if is_first {
 9369                    is_first = false;
 9370                } else {
 9371                    text += "\n";
 9372                }
 9373                let mut len = 0;
 9374                for chunk in buffer.text_for_range(selection.start..selection.end) {
 9375                    text.push_str(chunk);
 9376                    len += chunk.len();
 9377                }
 9378                clipboard_selections.push(ClipboardSelection {
 9379                    len,
 9380                    is_entire_line,
 9381                    first_line_indent: buffer
 9382                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 9383                        .len,
 9384                });
 9385            }
 9386        }
 9387
 9388        self.transact(window, cx, |this, window, cx| {
 9389            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9390                s.select(selections);
 9391            });
 9392            this.insert("", window, cx);
 9393        });
 9394        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 9395    }
 9396
 9397    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 9398        let item = self.cut_common(window, cx);
 9399        cx.write_to_clipboard(item);
 9400    }
 9401
 9402    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 9403        self.change_selections(None, window, cx, |s| {
 9404            s.move_with(|snapshot, sel| {
 9405                if sel.is_empty() {
 9406                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 9407                }
 9408            });
 9409        });
 9410        let item = self.cut_common(window, cx);
 9411        cx.set_global(KillRing(item))
 9412    }
 9413
 9414    pub fn kill_ring_yank(
 9415        &mut self,
 9416        _: &KillRingYank,
 9417        window: &mut Window,
 9418        cx: &mut Context<Self>,
 9419    ) {
 9420        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 9421            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 9422                (kill_ring.text().to_string(), kill_ring.metadata_json())
 9423            } else {
 9424                return;
 9425            }
 9426        } else {
 9427            return;
 9428        };
 9429        self.do_paste(&text, metadata, false, window, cx);
 9430    }
 9431
 9432    pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
 9433        self.do_copy(true, cx);
 9434    }
 9435
 9436    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 9437        self.do_copy(false, cx);
 9438    }
 9439
 9440    fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
 9441        let selections = self.selections.all::<Point>(cx);
 9442        let buffer = self.buffer.read(cx).read(cx);
 9443        let mut text = String::new();
 9444
 9445        let mut clipboard_selections = Vec::with_capacity(selections.len());
 9446        {
 9447            let max_point = buffer.max_point();
 9448            let mut is_first = true;
 9449            for selection in &selections {
 9450                let mut start = selection.start;
 9451                let mut end = selection.end;
 9452                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 9453                if is_entire_line {
 9454                    start = Point::new(start.row, 0);
 9455                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 9456                }
 9457
 9458                let mut trimmed_selections = Vec::new();
 9459                if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
 9460                    let row = MultiBufferRow(start.row);
 9461                    let first_indent = buffer.indent_size_for_line(row);
 9462                    if first_indent.len == 0 || start.column > first_indent.len {
 9463                        trimmed_selections.push(start..end);
 9464                    } else {
 9465                        trimmed_selections.push(
 9466                            Point::new(row.0, first_indent.len)
 9467                                ..Point::new(row.0, buffer.line_len(row)),
 9468                        );
 9469                        for row in start.row + 1..=end.row {
 9470                            let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
 9471                            if row_indent_size.len >= first_indent.len {
 9472                                trimmed_selections.push(
 9473                                    Point::new(row, first_indent.len)
 9474                                        ..Point::new(row, buffer.line_len(MultiBufferRow(row))),
 9475                                );
 9476                            } else {
 9477                                trimmed_selections.clear();
 9478                                trimmed_selections.push(start..end);
 9479                                break;
 9480                            }
 9481                        }
 9482                    }
 9483                } else {
 9484                    trimmed_selections.push(start..end);
 9485                }
 9486
 9487                for trimmed_range in trimmed_selections {
 9488                    if is_first {
 9489                        is_first = false;
 9490                    } else {
 9491                        text += "\n";
 9492                    }
 9493                    let mut len = 0;
 9494                    for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
 9495                        text.push_str(chunk);
 9496                        len += chunk.len();
 9497                    }
 9498                    clipboard_selections.push(ClipboardSelection {
 9499                        len,
 9500                        is_entire_line,
 9501                        first_line_indent: buffer
 9502                            .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
 9503                            .len,
 9504                    });
 9505                }
 9506            }
 9507        }
 9508
 9509        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 9510            text,
 9511            clipboard_selections,
 9512        ));
 9513    }
 9514
 9515    pub fn do_paste(
 9516        &mut self,
 9517        text: &String,
 9518        clipboard_selections: Option<Vec<ClipboardSelection>>,
 9519        handle_entire_lines: bool,
 9520        window: &mut Window,
 9521        cx: &mut Context<Self>,
 9522    ) {
 9523        if self.read_only(cx) {
 9524            return;
 9525        }
 9526
 9527        let clipboard_text = Cow::Borrowed(text);
 9528
 9529        self.transact(window, cx, |this, window, cx| {
 9530            if let Some(mut clipboard_selections) = clipboard_selections {
 9531                let old_selections = this.selections.all::<usize>(cx);
 9532                let all_selections_were_entire_line =
 9533                    clipboard_selections.iter().all(|s| s.is_entire_line);
 9534                let first_selection_indent_column =
 9535                    clipboard_selections.first().map(|s| s.first_line_indent);
 9536                if clipboard_selections.len() != old_selections.len() {
 9537                    clipboard_selections.drain(..);
 9538                }
 9539                let cursor_offset = this.selections.last::<usize>(cx).head();
 9540                let mut auto_indent_on_paste = true;
 9541
 9542                this.buffer.update(cx, |buffer, cx| {
 9543                    let snapshot = buffer.read(cx);
 9544                    auto_indent_on_paste = snapshot
 9545                        .language_settings_at(cursor_offset, cx)
 9546                        .auto_indent_on_paste;
 9547
 9548                    let mut start_offset = 0;
 9549                    let mut edits = Vec::new();
 9550                    let mut original_indent_columns = Vec::new();
 9551                    for (ix, selection) in old_selections.iter().enumerate() {
 9552                        let to_insert;
 9553                        let entire_line;
 9554                        let original_indent_column;
 9555                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 9556                            let end_offset = start_offset + clipboard_selection.len;
 9557                            to_insert = &clipboard_text[start_offset..end_offset];
 9558                            entire_line = clipboard_selection.is_entire_line;
 9559                            start_offset = end_offset + 1;
 9560                            original_indent_column = Some(clipboard_selection.first_line_indent);
 9561                        } else {
 9562                            to_insert = clipboard_text.as_str();
 9563                            entire_line = all_selections_were_entire_line;
 9564                            original_indent_column = first_selection_indent_column
 9565                        }
 9566
 9567                        // If the corresponding selection was empty when this slice of the
 9568                        // clipboard text was written, then the entire line containing the
 9569                        // selection was copied. If this selection is also currently empty,
 9570                        // then paste the line before the current line of the buffer.
 9571                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 9572                            let column = selection.start.to_point(&snapshot).column as usize;
 9573                            let line_start = selection.start - column;
 9574                            line_start..line_start
 9575                        } else {
 9576                            selection.range()
 9577                        };
 9578
 9579                        edits.push((range, to_insert));
 9580                        original_indent_columns.push(original_indent_column);
 9581                    }
 9582                    drop(snapshot);
 9583
 9584                    buffer.edit(
 9585                        edits,
 9586                        if auto_indent_on_paste {
 9587                            Some(AutoindentMode::Block {
 9588                                original_indent_columns,
 9589                            })
 9590                        } else {
 9591                            None
 9592                        },
 9593                        cx,
 9594                    );
 9595                });
 9596
 9597                let selections = this.selections.all::<usize>(cx);
 9598                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9599                    s.select(selections)
 9600                });
 9601            } else {
 9602                this.insert(&clipboard_text, window, cx);
 9603            }
 9604        });
 9605    }
 9606
 9607    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 9608        if let Some(item) = cx.read_from_clipboard() {
 9609            let entries = item.entries();
 9610
 9611            match entries.first() {
 9612                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 9613                // of all the pasted entries.
 9614                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 9615                    .do_paste(
 9616                        clipboard_string.text(),
 9617                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 9618                        true,
 9619                        window,
 9620                        cx,
 9621                    ),
 9622                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 9623            }
 9624        }
 9625    }
 9626
 9627    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 9628        if self.read_only(cx) {
 9629            return;
 9630        }
 9631
 9632        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 9633            if let Some((selections, _)) =
 9634                self.selection_history.transaction(transaction_id).cloned()
 9635            {
 9636                self.change_selections(None, window, cx, |s| {
 9637                    s.select_anchors(selections.to_vec());
 9638                });
 9639            } else {
 9640                log::error!(
 9641                    "No entry in selection_history found for undo. \
 9642                     This may correspond to a bug where undo does not update the selection. \
 9643                     If this is occurring, please add details to \
 9644                     https://github.com/zed-industries/zed/issues/22692"
 9645                );
 9646            }
 9647            self.request_autoscroll(Autoscroll::fit(), cx);
 9648            self.unmark_text(window, cx);
 9649            self.refresh_inline_completion(true, false, window, cx);
 9650            cx.emit(EditorEvent::Edited { transaction_id });
 9651            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 9652        }
 9653    }
 9654
 9655    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 9656        if self.read_only(cx) {
 9657            return;
 9658        }
 9659
 9660        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 9661            if let Some((_, Some(selections))) =
 9662                self.selection_history.transaction(transaction_id).cloned()
 9663            {
 9664                self.change_selections(None, window, cx, |s| {
 9665                    s.select_anchors(selections.to_vec());
 9666                });
 9667            } else {
 9668                log::error!(
 9669                    "No entry in selection_history found for redo. \
 9670                     This may correspond to a bug where undo does not update the selection. \
 9671                     If this is occurring, please add details to \
 9672                     https://github.com/zed-industries/zed/issues/22692"
 9673                );
 9674            }
 9675            self.request_autoscroll(Autoscroll::fit(), cx);
 9676            self.unmark_text(window, cx);
 9677            self.refresh_inline_completion(true, false, window, cx);
 9678            cx.emit(EditorEvent::Edited { transaction_id });
 9679        }
 9680    }
 9681
 9682    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 9683        self.buffer
 9684            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 9685    }
 9686
 9687    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 9688        self.buffer
 9689            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 9690    }
 9691
 9692    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 9693        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9694            let line_mode = s.line_mode;
 9695            s.move_with(|map, selection| {
 9696                let cursor = if selection.is_empty() && !line_mode {
 9697                    movement::left(map, selection.start)
 9698                } else {
 9699                    selection.start
 9700                };
 9701                selection.collapse_to(cursor, SelectionGoal::None);
 9702            });
 9703        })
 9704    }
 9705
 9706    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 9707        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9708            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 9709        })
 9710    }
 9711
 9712    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 9713        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9714            let line_mode = s.line_mode;
 9715            s.move_with(|map, selection| {
 9716                let cursor = if selection.is_empty() && !line_mode {
 9717                    movement::right(map, selection.end)
 9718                } else {
 9719                    selection.end
 9720                };
 9721                selection.collapse_to(cursor, SelectionGoal::None)
 9722            });
 9723        })
 9724    }
 9725
 9726    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 9727        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9728            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 9729        })
 9730    }
 9731
 9732    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 9733        if self.take_rename(true, window, cx).is_some() {
 9734            return;
 9735        }
 9736
 9737        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9738            cx.propagate();
 9739            return;
 9740        }
 9741
 9742        let text_layout_details = &self.text_layout_details(window);
 9743        let selection_count = self.selections.count();
 9744        let first_selection = self.selections.first_anchor();
 9745
 9746        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9747            let line_mode = s.line_mode;
 9748            s.move_with(|map, selection| {
 9749                if !selection.is_empty() && !line_mode {
 9750                    selection.goal = SelectionGoal::None;
 9751                }
 9752                let (cursor, goal) = movement::up(
 9753                    map,
 9754                    selection.start,
 9755                    selection.goal,
 9756                    false,
 9757                    text_layout_details,
 9758                );
 9759                selection.collapse_to(cursor, goal);
 9760            });
 9761        });
 9762
 9763        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 9764        {
 9765            cx.propagate();
 9766        }
 9767    }
 9768
 9769    pub fn move_up_by_lines(
 9770        &mut self,
 9771        action: &MoveUpByLines,
 9772        window: &mut Window,
 9773        cx: &mut Context<Self>,
 9774    ) {
 9775        if self.take_rename(true, window, cx).is_some() {
 9776            return;
 9777        }
 9778
 9779        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9780            cx.propagate();
 9781            return;
 9782        }
 9783
 9784        let text_layout_details = &self.text_layout_details(window);
 9785
 9786        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9787            let line_mode = s.line_mode;
 9788            s.move_with(|map, selection| {
 9789                if !selection.is_empty() && !line_mode {
 9790                    selection.goal = SelectionGoal::None;
 9791                }
 9792                let (cursor, goal) = movement::up_by_rows(
 9793                    map,
 9794                    selection.start,
 9795                    action.lines,
 9796                    selection.goal,
 9797                    false,
 9798                    text_layout_details,
 9799                );
 9800                selection.collapse_to(cursor, goal);
 9801            });
 9802        })
 9803    }
 9804
 9805    pub fn move_down_by_lines(
 9806        &mut self,
 9807        action: &MoveDownByLines,
 9808        window: &mut Window,
 9809        cx: &mut Context<Self>,
 9810    ) {
 9811        if self.take_rename(true, window, cx).is_some() {
 9812            return;
 9813        }
 9814
 9815        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9816            cx.propagate();
 9817            return;
 9818        }
 9819
 9820        let text_layout_details = &self.text_layout_details(window);
 9821
 9822        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9823            let line_mode = s.line_mode;
 9824            s.move_with(|map, selection| {
 9825                if !selection.is_empty() && !line_mode {
 9826                    selection.goal = SelectionGoal::None;
 9827                }
 9828                let (cursor, goal) = movement::down_by_rows(
 9829                    map,
 9830                    selection.start,
 9831                    action.lines,
 9832                    selection.goal,
 9833                    false,
 9834                    text_layout_details,
 9835                );
 9836                selection.collapse_to(cursor, goal);
 9837            });
 9838        })
 9839    }
 9840
 9841    pub fn select_down_by_lines(
 9842        &mut self,
 9843        action: &SelectDownByLines,
 9844        window: &mut Window,
 9845        cx: &mut Context<Self>,
 9846    ) {
 9847        let text_layout_details = &self.text_layout_details(window);
 9848        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9849            s.move_heads_with(|map, head, goal| {
 9850                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 9851            })
 9852        })
 9853    }
 9854
 9855    pub fn select_up_by_lines(
 9856        &mut self,
 9857        action: &SelectUpByLines,
 9858        window: &mut Window,
 9859        cx: &mut Context<Self>,
 9860    ) {
 9861        let text_layout_details = &self.text_layout_details(window);
 9862        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9863            s.move_heads_with(|map, head, goal| {
 9864                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 9865            })
 9866        })
 9867    }
 9868
 9869    pub fn select_page_up(
 9870        &mut self,
 9871        _: &SelectPageUp,
 9872        window: &mut Window,
 9873        cx: &mut Context<Self>,
 9874    ) {
 9875        let Some(row_count) = self.visible_row_count() else {
 9876            return;
 9877        };
 9878
 9879        let text_layout_details = &self.text_layout_details(window);
 9880
 9881        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9882            s.move_heads_with(|map, head, goal| {
 9883                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 9884            })
 9885        })
 9886    }
 9887
 9888    pub fn move_page_up(
 9889        &mut self,
 9890        action: &MovePageUp,
 9891        window: &mut Window,
 9892        cx: &mut Context<Self>,
 9893    ) {
 9894        if self.take_rename(true, window, cx).is_some() {
 9895            return;
 9896        }
 9897
 9898        if self
 9899            .context_menu
 9900            .borrow_mut()
 9901            .as_mut()
 9902            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 9903            .unwrap_or(false)
 9904        {
 9905            return;
 9906        }
 9907
 9908        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9909            cx.propagate();
 9910            return;
 9911        }
 9912
 9913        let Some(row_count) = self.visible_row_count() else {
 9914            return;
 9915        };
 9916
 9917        let autoscroll = if action.center_cursor {
 9918            Autoscroll::center()
 9919        } else {
 9920            Autoscroll::fit()
 9921        };
 9922
 9923        let text_layout_details = &self.text_layout_details(window);
 9924
 9925        self.change_selections(Some(autoscroll), window, cx, |s| {
 9926            let line_mode = s.line_mode;
 9927            s.move_with(|map, selection| {
 9928                if !selection.is_empty() && !line_mode {
 9929                    selection.goal = SelectionGoal::None;
 9930                }
 9931                let (cursor, goal) = movement::up_by_rows(
 9932                    map,
 9933                    selection.end,
 9934                    row_count,
 9935                    selection.goal,
 9936                    false,
 9937                    text_layout_details,
 9938                );
 9939                selection.collapse_to(cursor, goal);
 9940            });
 9941        });
 9942    }
 9943
 9944    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 9945        let text_layout_details = &self.text_layout_details(window);
 9946        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9947            s.move_heads_with(|map, head, goal| {
 9948                movement::up(map, head, goal, false, text_layout_details)
 9949            })
 9950        })
 9951    }
 9952
 9953    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 9954        self.take_rename(true, window, cx);
 9955
 9956        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9957            cx.propagate();
 9958            return;
 9959        }
 9960
 9961        let text_layout_details = &self.text_layout_details(window);
 9962        let selection_count = self.selections.count();
 9963        let first_selection = self.selections.first_anchor();
 9964
 9965        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9966            let line_mode = s.line_mode;
 9967            s.move_with(|map, selection| {
 9968                if !selection.is_empty() && !line_mode {
 9969                    selection.goal = SelectionGoal::None;
 9970                }
 9971                let (cursor, goal) = movement::down(
 9972                    map,
 9973                    selection.end,
 9974                    selection.goal,
 9975                    false,
 9976                    text_layout_details,
 9977                );
 9978                selection.collapse_to(cursor, goal);
 9979            });
 9980        });
 9981
 9982        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 9983        {
 9984            cx.propagate();
 9985        }
 9986    }
 9987
 9988    pub fn select_page_down(
 9989        &mut self,
 9990        _: &SelectPageDown,
 9991        window: &mut Window,
 9992        cx: &mut Context<Self>,
 9993    ) {
 9994        let Some(row_count) = self.visible_row_count() else {
 9995            return;
 9996        };
 9997
 9998        let text_layout_details = &self.text_layout_details(window);
 9999
10000        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10001            s.move_heads_with(|map, head, goal| {
10002                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10003            })
10004        })
10005    }
10006
10007    pub fn move_page_down(
10008        &mut self,
10009        action: &MovePageDown,
10010        window: &mut Window,
10011        cx: &mut Context<Self>,
10012    ) {
10013        if self.take_rename(true, window, cx).is_some() {
10014            return;
10015        }
10016
10017        if self
10018            .context_menu
10019            .borrow_mut()
10020            .as_mut()
10021            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10022            .unwrap_or(false)
10023        {
10024            return;
10025        }
10026
10027        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10028            cx.propagate();
10029            return;
10030        }
10031
10032        let Some(row_count) = self.visible_row_count() else {
10033            return;
10034        };
10035
10036        let autoscroll = if action.center_cursor {
10037            Autoscroll::center()
10038        } else {
10039            Autoscroll::fit()
10040        };
10041
10042        let text_layout_details = &self.text_layout_details(window);
10043        self.change_selections(Some(autoscroll), window, cx, |s| {
10044            let line_mode = s.line_mode;
10045            s.move_with(|map, selection| {
10046                if !selection.is_empty() && !line_mode {
10047                    selection.goal = SelectionGoal::None;
10048                }
10049                let (cursor, goal) = movement::down_by_rows(
10050                    map,
10051                    selection.end,
10052                    row_count,
10053                    selection.goal,
10054                    false,
10055                    text_layout_details,
10056                );
10057                selection.collapse_to(cursor, goal);
10058            });
10059        });
10060    }
10061
10062    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10063        let text_layout_details = &self.text_layout_details(window);
10064        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10065            s.move_heads_with(|map, head, goal| {
10066                movement::down(map, head, goal, false, text_layout_details)
10067            })
10068        });
10069    }
10070
10071    pub fn context_menu_first(
10072        &mut self,
10073        _: &ContextMenuFirst,
10074        _window: &mut Window,
10075        cx: &mut Context<Self>,
10076    ) {
10077        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10078            context_menu.select_first(self.completion_provider.as_deref(), cx);
10079        }
10080    }
10081
10082    pub fn context_menu_prev(
10083        &mut self,
10084        _: &ContextMenuPrevious,
10085        _window: &mut Window,
10086        cx: &mut Context<Self>,
10087    ) {
10088        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10089            context_menu.select_prev(self.completion_provider.as_deref(), cx);
10090        }
10091    }
10092
10093    pub fn context_menu_next(
10094        &mut self,
10095        _: &ContextMenuNext,
10096        _window: &mut Window,
10097        cx: &mut Context<Self>,
10098    ) {
10099        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10100            context_menu.select_next(self.completion_provider.as_deref(), cx);
10101        }
10102    }
10103
10104    pub fn context_menu_last(
10105        &mut self,
10106        _: &ContextMenuLast,
10107        _window: &mut Window,
10108        cx: &mut Context<Self>,
10109    ) {
10110        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10111            context_menu.select_last(self.completion_provider.as_deref(), cx);
10112        }
10113    }
10114
10115    pub fn move_to_previous_word_start(
10116        &mut self,
10117        _: &MoveToPreviousWordStart,
10118        window: &mut Window,
10119        cx: &mut Context<Self>,
10120    ) {
10121        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10122            s.move_cursors_with(|map, head, _| {
10123                (
10124                    movement::previous_word_start(map, head),
10125                    SelectionGoal::None,
10126                )
10127            });
10128        })
10129    }
10130
10131    pub fn move_to_previous_subword_start(
10132        &mut self,
10133        _: &MoveToPreviousSubwordStart,
10134        window: &mut Window,
10135        cx: &mut Context<Self>,
10136    ) {
10137        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10138            s.move_cursors_with(|map, head, _| {
10139                (
10140                    movement::previous_subword_start(map, head),
10141                    SelectionGoal::None,
10142                )
10143            });
10144        })
10145    }
10146
10147    pub fn select_to_previous_word_start(
10148        &mut self,
10149        _: &SelectToPreviousWordStart,
10150        window: &mut Window,
10151        cx: &mut Context<Self>,
10152    ) {
10153        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10154            s.move_heads_with(|map, head, _| {
10155                (
10156                    movement::previous_word_start(map, head),
10157                    SelectionGoal::None,
10158                )
10159            });
10160        })
10161    }
10162
10163    pub fn select_to_previous_subword_start(
10164        &mut self,
10165        _: &SelectToPreviousSubwordStart,
10166        window: &mut Window,
10167        cx: &mut Context<Self>,
10168    ) {
10169        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10170            s.move_heads_with(|map, head, _| {
10171                (
10172                    movement::previous_subword_start(map, head),
10173                    SelectionGoal::None,
10174                )
10175            });
10176        })
10177    }
10178
10179    pub fn delete_to_previous_word_start(
10180        &mut self,
10181        action: &DeleteToPreviousWordStart,
10182        window: &mut Window,
10183        cx: &mut Context<Self>,
10184    ) {
10185        self.transact(window, cx, |this, window, cx| {
10186            this.select_autoclose_pair(window, cx);
10187            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10188                let line_mode = s.line_mode;
10189                s.move_with(|map, selection| {
10190                    if selection.is_empty() && !line_mode {
10191                        let cursor = if action.ignore_newlines {
10192                            movement::previous_word_start(map, selection.head())
10193                        } else {
10194                            movement::previous_word_start_or_newline(map, selection.head())
10195                        };
10196                        selection.set_head(cursor, SelectionGoal::None);
10197                    }
10198                });
10199            });
10200            this.insert("", window, cx);
10201        });
10202    }
10203
10204    pub fn delete_to_previous_subword_start(
10205        &mut self,
10206        _: &DeleteToPreviousSubwordStart,
10207        window: &mut Window,
10208        cx: &mut Context<Self>,
10209    ) {
10210        self.transact(window, cx, |this, window, cx| {
10211            this.select_autoclose_pair(window, cx);
10212            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10213                let line_mode = s.line_mode;
10214                s.move_with(|map, selection| {
10215                    if selection.is_empty() && !line_mode {
10216                        let cursor = movement::previous_subword_start(map, selection.head());
10217                        selection.set_head(cursor, SelectionGoal::None);
10218                    }
10219                });
10220            });
10221            this.insert("", window, cx);
10222        });
10223    }
10224
10225    pub fn move_to_next_word_end(
10226        &mut self,
10227        _: &MoveToNextWordEnd,
10228        window: &mut Window,
10229        cx: &mut Context<Self>,
10230    ) {
10231        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10232            s.move_cursors_with(|map, head, _| {
10233                (movement::next_word_end(map, head), SelectionGoal::None)
10234            });
10235        })
10236    }
10237
10238    pub fn move_to_next_subword_end(
10239        &mut self,
10240        _: &MoveToNextSubwordEnd,
10241        window: &mut Window,
10242        cx: &mut Context<Self>,
10243    ) {
10244        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10245            s.move_cursors_with(|map, head, _| {
10246                (movement::next_subword_end(map, head), SelectionGoal::None)
10247            });
10248        })
10249    }
10250
10251    pub fn select_to_next_word_end(
10252        &mut self,
10253        _: &SelectToNextWordEnd,
10254        window: &mut Window,
10255        cx: &mut Context<Self>,
10256    ) {
10257        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10258            s.move_heads_with(|map, head, _| {
10259                (movement::next_word_end(map, head), SelectionGoal::None)
10260            });
10261        })
10262    }
10263
10264    pub fn select_to_next_subword_end(
10265        &mut self,
10266        _: &SelectToNextSubwordEnd,
10267        window: &mut Window,
10268        cx: &mut Context<Self>,
10269    ) {
10270        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10271            s.move_heads_with(|map, head, _| {
10272                (movement::next_subword_end(map, head), SelectionGoal::None)
10273            });
10274        })
10275    }
10276
10277    pub fn delete_to_next_word_end(
10278        &mut self,
10279        action: &DeleteToNextWordEnd,
10280        window: &mut Window,
10281        cx: &mut Context<Self>,
10282    ) {
10283        self.transact(window, cx, |this, window, cx| {
10284            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10285                let line_mode = s.line_mode;
10286                s.move_with(|map, selection| {
10287                    if selection.is_empty() && !line_mode {
10288                        let cursor = if action.ignore_newlines {
10289                            movement::next_word_end(map, selection.head())
10290                        } else {
10291                            movement::next_word_end_or_newline(map, selection.head())
10292                        };
10293                        selection.set_head(cursor, SelectionGoal::None);
10294                    }
10295                });
10296            });
10297            this.insert("", window, cx);
10298        });
10299    }
10300
10301    pub fn delete_to_next_subword_end(
10302        &mut self,
10303        _: &DeleteToNextSubwordEnd,
10304        window: &mut Window,
10305        cx: &mut Context<Self>,
10306    ) {
10307        self.transact(window, cx, |this, window, cx| {
10308            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10309                s.move_with(|map, selection| {
10310                    if selection.is_empty() {
10311                        let cursor = movement::next_subword_end(map, selection.head());
10312                        selection.set_head(cursor, SelectionGoal::None);
10313                    }
10314                });
10315            });
10316            this.insert("", window, cx);
10317        });
10318    }
10319
10320    pub fn move_to_beginning_of_line(
10321        &mut self,
10322        action: &MoveToBeginningOfLine,
10323        window: &mut Window,
10324        cx: &mut Context<Self>,
10325    ) {
10326        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10327            s.move_cursors_with(|map, head, _| {
10328                (
10329                    movement::indented_line_beginning(
10330                        map,
10331                        head,
10332                        action.stop_at_soft_wraps,
10333                        action.stop_at_indent,
10334                    ),
10335                    SelectionGoal::None,
10336                )
10337            });
10338        })
10339    }
10340
10341    pub fn select_to_beginning_of_line(
10342        &mut self,
10343        action: &SelectToBeginningOfLine,
10344        window: &mut Window,
10345        cx: &mut Context<Self>,
10346    ) {
10347        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10348            s.move_heads_with(|map, head, _| {
10349                (
10350                    movement::indented_line_beginning(
10351                        map,
10352                        head,
10353                        action.stop_at_soft_wraps,
10354                        action.stop_at_indent,
10355                    ),
10356                    SelectionGoal::None,
10357                )
10358            });
10359        });
10360    }
10361
10362    pub fn delete_to_beginning_of_line(
10363        &mut self,
10364        action: &DeleteToBeginningOfLine,
10365        window: &mut Window,
10366        cx: &mut Context<Self>,
10367    ) {
10368        self.transact(window, cx, |this, window, cx| {
10369            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10370                s.move_with(|_, selection| {
10371                    selection.reversed = true;
10372                });
10373            });
10374
10375            this.select_to_beginning_of_line(
10376                &SelectToBeginningOfLine {
10377                    stop_at_soft_wraps: false,
10378                    stop_at_indent: action.stop_at_indent,
10379                },
10380                window,
10381                cx,
10382            );
10383            this.backspace(&Backspace, window, cx);
10384        });
10385    }
10386
10387    pub fn move_to_end_of_line(
10388        &mut self,
10389        action: &MoveToEndOfLine,
10390        window: &mut Window,
10391        cx: &mut Context<Self>,
10392    ) {
10393        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10394            s.move_cursors_with(|map, head, _| {
10395                (
10396                    movement::line_end(map, head, action.stop_at_soft_wraps),
10397                    SelectionGoal::None,
10398                )
10399            });
10400        })
10401    }
10402
10403    pub fn select_to_end_of_line(
10404        &mut self,
10405        action: &SelectToEndOfLine,
10406        window: &mut Window,
10407        cx: &mut Context<Self>,
10408    ) {
10409        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10410            s.move_heads_with(|map, head, _| {
10411                (
10412                    movement::line_end(map, head, action.stop_at_soft_wraps),
10413                    SelectionGoal::None,
10414                )
10415            });
10416        })
10417    }
10418
10419    pub fn delete_to_end_of_line(
10420        &mut self,
10421        _: &DeleteToEndOfLine,
10422        window: &mut Window,
10423        cx: &mut Context<Self>,
10424    ) {
10425        self.transact(window, cx, |this, window, cx| {
10426            this.select_to_end_of_line(
10427                &SelectToEndOfLine {
10428                    stop_at_soft_wraps: false,
10429                },
10430                window,
10431                cx,
10432            );
10433            this.delete(&Delete, window, cx);
10434        });
10435    }
10436
10437    pub fn cut_to_end_of_line(
10438        &mut self,
10439        _: &CutToEndOfLine,
10440        window: &mut Window,
10441        cx: &mut Context<Self>,
10442    ) {
10443        self.transact(window, cx, |this, window, cx| {
10444            this.select_to_end_of_line(
10445                &SelectToEndOfLine {
10446                    stop_at_soft_wraps: false,
10447                },
10448                window,
10449                cx,
10450            );
10451            this.cut(&Cut, window, cx);
10452        });
10453    }
10454
10455    pub fn move_to_start_of_paragraph(
10456        &mut self,
10457        _: &MoveToStartOfParagraph,
10458        window: &mut Window,
10459        cx: &mut Context<Self>,
10460    ) {
10461        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10462            cx.propagate();
10463            return;
10464        }
10465
10466        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10467            s.move_with(|map, selection| {
10468                selection.collapse_to(
10469                    movement::start_of_paragraph(map, selection.head(), 1),
10470                    SelectionGoal::None,
10471                )
10472            });
10473        })
10474    }
10475
10476    pub fn move_to_end_of_paragraph(
10477        &mut self,
10478        _: &MoveToEndOfParagraph,
10479        window: &mut Window,
10480        cx: &mut Context<Self>,
10481    ) {
10482        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10483            cx.propagate();
10484            return;
10485        }
10486
10487        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10488            s.move_with(|map, selection| {
10489                selection.collapse_to(
10490                    movement::end_of_paragraph(map, selection.head(), 1),
10491                    SelectionGoal::None,
10492                )
10493            });
10494        })
10495    }
10496
10497    pub fn select_to_start_of_paragraph(
10498        &mut self,
10499        _: &SelectToStartOfParagraph,
10500        window: &mut Window,
10501        cx: &mut Context<Self>,
10502    ) {
10503        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10504            cx.propagate();
10505            return;
10506        }
10507
10508        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10509            s.move_heads_with(|map, head, _| {
10510                (
10511                    movement::start_of_paragraph(map, head, 1),
10512                    SelectionGoal::None,
10513                )
10514            });
10515        })
10516    }
10517
10518    pub fn select_to_end_of_paragraph(
10519        &mut self,
10520        _: &SelectToEndOfParagraph,
10521        window: &mut Window,
10522        cx: &mut Context<Self>,
10523    ) {
10524        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10525            cx.propagate();
10526            return;
10527        }
10528
10529        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10530            s.move_heads_with(|map, head, _| {
10531                (
10532                    movement::end_of_paragraph(map, head, 1),
10533                    SelectionGoal::None,
10534                )
10535            });
10536        })
10537    }
10538
10539    pub fn move_to_start_of_excerpt(
10540        &mut self,
10541        _: &MoveToStartOfExcerpt,
10542        window: &mut Window,
10543        cx: &mut Context<Self>,
10544    ) {
10545        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10546            cx.propagate();
10547            return;
10548        }
10549
10550        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10551            s.move_with(|map, selection| {
10552                selection.collapse_to(
10553                    movement::start_of_excerpt(
10554                        map,
10555                        selection.head(),
10556                        workspace::searchable::Direction::Prev,
10557                    ),
10558                    SelectionGoal::None,
10559                )
10560            });
10561        })
10562    }
10563
10564    pub fn move_to_start_of_next_excerpt(
10565        &mut self,
10566        _: &MoveToStartOfNextExcerpt,
10567        window: &mut Window,
10568        cx: &mut Context<Self>,
10569    ) {
10570        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10571            cx.propagate();
10572            return;
10573        }
10574
10575        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10576            s.move_with(|map, selection| {
10577                selection.collapse_to(
10578                    movement::start_of_excerpt(
10579                        map,
10580                        selection.head(),
10581                        workspace::searchable::Direction::Next,
10582                    ),
10583                    SelectionGoal::None,
10584                )
10585            });
10586        })
10587    }
10588
10589    pub fn move_to_end_of_excerpt(
10590        &mut self,
10591        _: &MoveToEndOfExcerpt,
10592        window: &mut Window,
10593        cx: &mut Context<Self>,
10594    ) {
10595        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10596            cx.propagate();
10597            return;
10598        }
10599
10600        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10601            s.move_with(|map, selection| {
10602                selection.collapse_to(
10603                    movement::end_of_excerpt(
10604                        map,
10605                        selection.head(),
10606                        workspace::searchable::Direction::Next,
10607                    ),
10608                    SelectionGoal::None,
10609                )
10610            });
10611        })
10612    }
10613
10614    pub fn move_to_end_of_previous_excerpt(
10615        &mut self,
10616        _: &MoveToEndOfPreviousExcerpt,
10617        window: &mut Window,
10618        cx: &mut Context<Self>,
10619    ) {
10620        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10621            cx.propagate();
10622            return;
10623        }
10624
10625        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10626            s.move_with(|map, selection| {
10627                selection.collapse_to(
10628                    movement::end_of_excerpt(
10629                        map,
10630                        selection.head(),
10631                        workspace::searchable::Direction::Prev,
10632                    ),
10633                    SelectionGoal::None,
10634                )
10635            });
10636        })
10637    }
10638
10639    pub fn select_to_start_of_excerpt(
10640        &mut self,
10641        _: &SelectToStartOfExcerpt,
10642        window: &mut Window,
10643        cx: &mut Context<Self>,
10644    ) {
10645        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10646            cx.propagate();
10647            return;
10648        }
10649
10650        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10651            s.move_heads_with(|map, head, _| {
10652                (
10653                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
10654                    SelectionGoal::None,
10655                )
10656            });
10657        })
10658    }
10659
10660    pub fn select_to_start_of_next_excerpt(
10661        &mut self,
10662        _: &SelectToStartOfNextExcerpt,
10663        window: &mut Window,
10664        cx: &mut Context<Self>,
10665    ) {
10666        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10667            cx.propagate();
10668            return;
10669        }
10670
10671        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10672            s.move_heads_with(|map, head, _| {
10673                (
10674                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
10675                    SelectionGoal::None,
10676                )
10677            });
10678        })
10679    }
10680
10681    pub fn select_to_end_of_excerpt(
10682        &mut self,
10683        _: &SelectToEndOfExcerpt,
10684        window: &mut Window,
10685        cx: &mut Context<Self>,
10686    ) {
10687        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10688            cx.propagate();
10689            return;
10690        }
10691
10692        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10693            s.move_heads_with(|map, head, _| {
10694                (
10695                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
10696                    SelectionGoal::None,
10697                )
10698            });
10699        })
10700    }
10701
10702    pub fn select_to_end_of_previous_excerpt(
10703        &mut self,
10704        _: &SelectToEndOfPreviousExcerpt,
10705        window: &mut Window,
10706        cx: &mut Context<Self>,
10707    ) {
10708        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10709            cx.propagate();
10710            return;
10711        }
10712
10713        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10714            s.move_heads_with(|map, head, _| {
10715                (
10716                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
10717                    SelectionGoal::None,
10718                )
10719            });
10720        })
10721    }
10722
10723    pub fn move_to_beginning(
10724        &mut self,
10725        _: &MoveToBeginning,
10726        window: &mut Window,
10727        cx: &mut Context<Self>,
10728    ) {
10729        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10730            cx.propagate();
10731            return;
10732        }
10733
10734        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10735            s.select_ranges(vec![0..0]);
10736        });
10737    }
10738
10739    pub fn select_to_beginning(
10740        &mut self,
10741        _: &SelectToBeginning,
10742        window: &mut Window,
10743        cx: &mut Context<Self>,
10744    ) {
10745        let mut selection = self.selections.last::<Point>(cx);
10746        selection.set_head(Point::zero(), SelectionGoal::None);
10747
10748        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10749            s.select(vec![selection]);
10750        });
10751    }
10752
10753    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
10754        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10755            cx.propagate();
10756            return;
10757        }
10758
10759        let cursor = self.buffer.read(cx).read(cx).len();
10760        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10761            s.select_ranges(vec![cursor..cursor])
10762        });
10763    }
10764
10765    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
10766        self.nav_history = nav_history;
10767    }
10768
10769    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
10770        self.nav_history.as_ref()
10771    }
10772
10773    fn push_to_nav_history(
10774        &mut self,
10775        cursor_anchor: Anchor,
10776        new_position: Option<Point>,
10777        cx: &mut Context<Self>,
10778    ) {
10779        if let Some(nav_history) = self.nav_history.as_mut() {
10780            let buffer = self.buffer.read(cx).read(cx);
10781            let cursor_position = cursor_anchor.to_point(&buffer);
10782            let scroll_state = self.scroll_manager.anchor();
10783            let scroll_top_row = scroll_state.top_row(&buffer);
10784            drop(buffer);
10785
10786            if let Some(new_position) = new_position {
10787                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
10788                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
10789                    return;
10790                }
10791            }
10792
10793            nav_history.push(
10794                Some(NavigationData {
10795                    cursor_anchor,
10796                    cursor_position,
10797                    scroll_anchor: scroll_state,
10798                    scroll_top_row,
10799                }),
10800                cx,
10801            );
10802        }
10803    }
10804
10805    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
10806        let buffer = self.buffer.read(cx).snapshot(cx);
10807        let mut selection = self.selections.first::<usize>(cx);
10808        selection.set_head(buffer.len(), SelectionGoal::None);
10809        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10810            s.select(vec![selection]);
10811        });
10812    }
10813
10814    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
10815        let end = self.buffer.read(cx).read(cx).len();
10816        self.change_selections(None, window, cx, |s| {
10817            s.select_ranges(vec![0..end]);
10818        });
10819    }
10820
10821    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
10822        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10823        let mut selections = self.selections.all::<Point>(cx);
10824        let max_point = display_map.buffer_snapshot.max_point();
10825        for selection in &mut selections {
10826            let rows = selection.spanned_rows(true, &display_map);
10827            selection.start = Point::new(rows.start.0, 0);
10828            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
10829            selection.reversed = false;
10830        }
10831        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10832            s.select(selections);
10833        });
10834    }
10835
10836    pub fn split_selection_into_lines(
10837        &mut self,
10838        _: &SplitSelectionIntoLines,
10839        window: &mut Window,
10840        cx: &mut Context<Self>,
10841    ) {
10842        let selections = self
10843            .selections
10844            .all::<Point>(cx)
10845            .into_iter()
10846            .map(|selection| selection.start..selection.end)
10847            .collect::<Vec<_>>();
10848        self.unfold_ranges(&selections, true, true, cx);
10849
10850        let mut new_selection_ranges = Vec::new();
10851        {
10852            let buffer = self.buffer.read(cx).read(cx);
10853            for selection in selections {
10854                for row in selection.start.row..selection.end.row {
10855                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
10856                    new_selection_ranges.push(cursor..cursor);
10857                }
10858
10859                let is_multiline_selection = selection.start.row != selection.end.row;
10860                // Don't insert last one if it's a multi-line selection ending at the start of a line,
10861                // so this action feels more ergonomic when paired with other selection operations
10862                let should_skip_last = is_multiline_selection && selection.end.column == 0;
10863                if !should_skip_last {
10864                    new_selection_ranges.push(selection.end..selection.end);
10865                }
10866            }
10867        }
10868        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10869            s.select_ranges(new_selection_ranges);
10870        });
10871    }
10872
10873    pub fn add_selection_above(
10874        &mut self,
10875        _: &AddSelectionAbove,
10876        window: &mut Window,
10877        cx: &mut Context<Self>,
10878    ) {
10879        self.add_selection(true, window, cx);
10880    }
10881
10882    pub fn add_selection_below(
10883        &mut self,
10884        _: &AddSelectionBelow,
10885        window: &mut Window,
10886        cx: &mut Context<Self>,
10887    ) {
10888        self.add_selection(false, window, cx);
10889    }
10890
10891    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
10892        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10893        let mut selections = self.selections.all::<Point>(cx);
10894        let text_layout_details = self.text_layout_details(window);
10895        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
10896            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
10897            let range = oldest_selection.display_range(&display_map).sorted();
10898
10899            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
10900            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
10901            let positions = start_x.min(end_x)..start_x.max(end_x);
10902
10903            selections.clear();
10904            let mut stack = Vec::new();
10905            for row in range.start.row().0..=range.end.row().0 {
10906                if let Some(selection) = self.selections.build_columnar_selection(
10907                    &display_map,
10908                    DisplayRow(row),
10909                    &positions,
10910                    oldest_selection.reversed,
10911                    &text_layout_details,
10912                ) {
10913                    stack.push(selection.id);
10914                    selections.push(selection);
10915                }
10916            }
10917
10918            if above {
10919                stack.reverse();
10920            }
10921
10922            AddSelectionsState { above, stack }
10923        });
10924
10925        let last_added_selection = *state.stack.last().unwrap();
10926        let mut new_selections = Vec::new();
10927        if above == state.above {
10928            let end_row = if above {
10929                DisplayRow(0)
10930            } else {
10931                display_map.max_point().row()
10932            };
10933
10934            'outer: for selection in selections {
10935                if selection.id == last_added_selection {
10936                    let range = selection.display_range(&display_map).sorted();
10937                    debug_assert_eq!(range.start.row(), range.end.row());
10938                    let mut row = range.start.row();
10939                    let positions =
10940                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
10941                            px(start)..px(end)
10942                        } else {
10943                            let start_x =
10944                                display_map.x_for_display_point(range.start, &text_layout_details);
10945                            let end_x =
10946                                display_map.x_for_display_point(range.end, &text_layout_details);
10947                            start_x.min(end_x)..start_x.max(end_x)
10948                        };
10949
10950                    while row != end_row {
10951                        if above {
10952                            row.0 -= 1;
10953                        } else {
10954                            row.0 += 1;
10955                        }
10956
10957                        if let Some(new_selection) = self.selections.build_columnar_selection(
10958                            &display_map,
10959                            row,
10960                            &positions,
10961                            selection.reversed,
10962                            &text_layout_details,
10963                        ) {
10964                            state.stack.push(new_selection.id);
10965                            if above {
10966                                new_selections.push(new_selection);
10967                                new_selections.push(selection);
10968                            } else {
10969                                new_selections.push(selection);
10970                                new_selections.push(new_selection);
10971                            }
10972
10973                            continue 'outer;
10974                        }
10975                    }
10976                }
10977
10978                new_selections.push(selection);
10979            }
10980        } else {
10981            new_selections = selections;
10982            new_selections.retain(|s| s.id != last_added_selection);
10983            state.stack.pop();
10984        }
10985
10986        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10987            s.select(new_selections);
10988        });
10989        if state.stack.len() > 1 {
10990            self.add_selections_state = Some(state);
10991        }
10992    }
10993
10994    pub fn select_next_match_internal(
10995        &mut self,
10996        display_map: &DisplaySnapshot,
10997        replace_newest: bool,
10998        autoscroll: Option<Autoscroll>,
10999        window: &mut Window,
11000        cx: &mut Context<Self>,
11001    ) -> Result<()> {
11002        fn select_next_match_ranges(
11003            this: &mut Editor,
11004            range: Range<usize>,
11005            replace_newest: bool,
11006            auto_scroll: Option<Autoscroll>,
11007            window: &mut Window,
11008            cx: &mut Context<Editor>,
11009        ) {
11010            this.unfold_ranges(&[range.clone()], false, true, cx);
11011            this.change_selections(auto_scroll, window, cx, |s| {
11012                if replace_newest {
11013                    s.delete(s.newest_anchor().id);
11014                }
11015                s.insert_range(range.clone());
11016            });
11017        }
11018
11019        let buffer = &display_map.buffer_snapshot;
11020        let mut selections = self.selections.all::<usize>(cx);
11021        if let Some(mut select_next_state) = self.select_next_state.take() {
11022            let query = &select_next_state.query;
11023            if !select_next_state.done {
11024                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11025                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11026                let mut next_selected_range = None;
11027
11028                let bytes_after_last_selection =
11029                    buffer.bytes_in_range(last_selection.end..buffer.len());
11030                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11031                let query_matches = query
11032                    .stream_find_iter(bytes_after_last_selection)
11033                    .map(|result| (last_selection.end, result))
11034                    .chain(
11035                        query
11036                            .stream_find_iter(bytes_before_first_selection)
11037                            .map(|result| (0, result)),
11038                    );
11039
11040                for (start_offset, query_match) in query_matches {
11041                    let query_match = query_match.unwrap(); // can only fail due to I/O
11042                    let offset_range =
11043                        start_offset + query_match.start()..start_offset + query_match.end();
11044                    let display_range = offset_range.start.to_display_point(display_map)
11045                        ..offset_range.end.to_display_point(display_map);
11046
11047                    if !select_next_state.wordwise
11048                        || (!movement::is_inside_word(display_map, display_range.start)
11049                            && !movement::is_inside_word(display_map, display_range.end))
11050                    {
11051                        // TODO: This is n^2, because we might check all the selections
11052                        if !selections
11053                            .iter()
11054                            .any(|selection| selection.range().overlaps(&offset_range))
11055                        {
11056                            next_selected_range = Some(offset_range);
11057                            break;
11058                        }
11059                    }
11060                }
11061
11062                if let Some(next_selected_range) = next_selected_range {
11063                    select_next_match_ranges(
11064                        self,
11065                        next_selected_range,
11066                        replace_newest,
11067                        autoscroll,
11068                        window,
11069                        cx,
11070                    );
11071                } else {
11072                    select_next_state.done = true;
11073                }
11074            }
11075
11076            self.select_next_state = Some(select_next_state);
11077        } else {
11078            let mut only_carets = true;
11079            let mut same_text_selected = true;
11080            let mut selected_text = None;
11081
11082            let mut selections_iter = selections.iter().peekable();
11083            while let Some(selection) = selections_iter.next() {
11084                if selection.start != selection.end {
11085                    only_carets = false;
11086                }
11087
11088                if same_text_selected {
11089                    if selected_text.is_none() {
11090                        selected_text =
11091                            Some(buffer.text_for_range(selection.range()).collect::<String>());
11092                    }
11093
11094                    if let Some(next_selection) = selections_iter.peek() {
11095                        if next_selection.range().len() == selection.range().len() {
11096                            let next_selected_text = buffer
11097                                .text_for_range(next_selection.range())
11098                                .collect::<String>();
11099                            if Some(next_selected_text) != selected_text {
11100                                same_text_selected = false;
11101                                selected_text = None;
11102                            }
11103                        } else {
11104                            same_text_selected = false;
11105                            selected_text = None;
11106                        }
11107                    }
11108                }
11109            }
11110
11111            if only_carets {
11112                for selection in &mut selections {
11113                    let word_range = movement::surrounding_word(
11114                        display_map,
11115                        selection.start.to_display_point(display_map),
11116                    );
11117                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
11118                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
11119                    selection.goal = SelectionGoal::None;
11120                    selection.reversed = false;
11121                    select_next_match_ranges(
11122                        self,
11123                        selection.start..selection.end,
11124                        replace_newest,
11125                        autoscroll,
11126                        window,
11127                        cx,
11128                    );
11129                }
11130
11131                if selections.len() == 1 {
11132                    let selection = selections
11133                        .last()
11134                        .expect("ensured that there's only one selection");
11135                    let query = buffer
11136                        .text_for_range(selection.start..selection.end)
11137                        .collect::<String>();
11138                    let is_empty = query.is_empty();
11139                    let select_state = SelectNextState {
11140                        query: AhoCorasick::new(&[query])?,
11141                        wordwise: true,
11142                        done: is_empty,
11143                    };
11144                    self.select_next_state = Some(select_state);
11145                } else {
11146                    self.select_next_state = None;
11147                }
11148            } else if let Some(selected_text) = selected_text {
11149                self.select_next_state = Some(SelectNextState {
11150                    query: AhoCorasick::new(&[selected_text])?,
11151                    wordwise: false,
11152                    done: false,
11153                });
11154                self.select_next_match_internal(
11155                    display_map,
11156                    replace_newest,
11157                    autoscroll,
11158                    window,
11159                    cx,
11160                )?;
11161            }
11162        }
11163        Ok(())
11164    }
11165
11166    pub fn select_all_matches(
11167        &mut self,
11168        _action: &SelectAllMatches,
11169        window: &mut Window,
11170        cx: &mut Context<Self>,
11171    ) -> Result<()> {
11172        self.push_to_selection_history();
11173        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11174
11175        self.select_next_match_internal(&display_map, false, None, window, cx)?;
11176        let Some(select_next_state) = self.select_next_state.as_mut() else {
11177            return Ok(());
11178        };
11179        if select_next_state.done {
11180            return Ok(());
11181        }
11182
11183        let mut new_selections = self.selections.all::<usize>(cx);
11184
11185        let buffer = &display_map.buffer_snapshot;
11186        let query_matches = select_next_state
11187            .query
11188            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11189
11190        for query_match in query_matches {
11191            let query_match = query_match.unwrap(); // can only fail due to I/O
11192            let offset_range = query_match.start()..query_match.end();
11193            let display_range = offset_range.start.to_display_point(&display_map)
11194                ..offset_range.end.to_display_point(&display_map);
11195
11196            if !select_next_state.wordwise
11197                || (!movement::is_inside_word(&display_map, display_range.start)
11198                    && !movement::is_inside_word(&display_map, display_range.end))
11199            {
11200                self.selections.change_with(cx, |selections| {
11201                    new_selections.push(Selection {
11202                        id: selections.new_selection_id(),
11203                        start: offset_range.start,
11204                        end: offset_range.end,
11205                        reversed: false,
11206                        goal: SelectionGoal::None,
11207                    });
11208                });
11209            }
11210        }
11211
11212        new_selections.sort_by_key(|selection| selection.start);
11213        let mut ix = 0;
11214        while ix + 1 < new_selections.len() {
11215            let current_selection = &new_selections[ix];
11216            let next_selection = &new_selections[ix + 1];
11217            if current_selection.range().overlaps(&next_selection.range()) {
11218                if current_selection.id < next_selection.id {
11219                    new_selections.remove(ix + 1);
11220                } else {
11221                    new_selections.remove(ix);
11222                }
11223            } else {
11224                ix += 1;
11225            }
11226        }
11227
11228        let reversed = self.selections.oldest::<usize>(cx).reversed;
11229
11230        for selection in new_selections.iter_mut() {
11231            selection.reversed = reversed;
11232        }
11233
11234        select_next_state.done = true;
11235        self.unfold_ranges(
11236            &new_selections
11237                .iter()
11238                .map(|selection| selection.range())
11239                .collect::<Vec<_>>(),
11240            false,
11241            false,
11242            cx,
11243        );
11244        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
11245            selections.select(new_selections)
11246        });
11247
11248        Ok(())
11249    }
11250
11251    pub fn select_next(
11252        &mut self,
11253        action: &SelectNext,
11254        window: &mut Window,
11255        cx: &mut Context<Self>,
11256    ) -> Result<()> {
11257        self.push_to_selection_history();
11258        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11259        self.select_next_match_internal(
11260            &display_map,
11261            action.replace_newest,
11262            Some(Autoscroll::newest()),
11263            window,
11264            cx,
11265        )?;
11266        Ok(())
11267    }
11268
11269    pub fn select_previous(
11270        &mut self,
11271        action: &SelectPrevious,
11272        window: &mut Window,
11273        cx: &mut Context<Self>,
11274    ) -> Result<()> {
11275        self.push_to_selection_history();
11276        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11277        let buffer = &display_map.buffer_snapshot;
11278        let mut selections = self.selections.all::<usize>(cx);
11279        if let Some(mut select_prev_state) = self.select_prev_state.take() {
11280            let query = &select_prev_state.query;
11281            if !select_prev_state.done {
11282                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11283                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11284                let mut next_selected_range = None;
11285                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
11286                let bytes_before_last_selection =
11287                    buffer.reversed_bytes_in_range(0..last_selection.start);
11288                let bytes_after_first_selection =
11289                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
11290                let query_matches = query
11291                    .stream_find_iter(bytes_before_last_selection)
11292                    .map(|result| (last_selection.start, result))
11293                    .chain(
11294                        query
11295                            .stream_find_iter(bytes_after_first_selection)
11296                            .map(|result| (buffer.len(), result)),
11297                    );
11298                for (end_offset, query_match) in query_matches {
11299                    let query_match = query_match.unwrap(); // can only fail due to I/O
11300                    let offset_range =
11301                        end_offset - query_match.end()..end_offset - query_match.start();
11302                    let display_range = offset_range.start.to_display_point(&display_map)
11303                        ..offset_range.end.to_display_point(&display_map);
11304
11305                    if !select_prev_state.wordwise
11306                        || (!movement::is_inside_word(&display_map, display_range.start)
11307                            && !movement::is_inside_word(&display_map, display_range.end))
11308                    {
11309                        next_selected_range = Some(offset_range);
11310                        break;
11311                    }
11312                }
11313
11314                if let Some(next_selected_range) = next_selected_range {
11315                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
11316                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11317                        if action.replace_newest {
11318                            s.delete(s.newest_anchor().id);
11319                        }
11320                        s.insert_range(next_selected_range);
11321                    });
11322                } else {
11323                    select_prev_state.done = true;
11324                }
11325            }
11326
11327            self.select_prev_state = Some(select_prev_state);
11328        } else {
11329            let mut only_carets = true;
11330            let mut same_text_selected = true;
11331            let mut selected_text = None;
11332
11333            let mut selections_iter = selections.iter().peekable();
11334            while let Some(selection) = selections_iter.next() {
11335                if selection.start != selection.end {
11336                    only_carets = false;
11337                }
11338
11339                if same_text_selected {
11340                    if selected_text.is_none() {
11341                        selected_text =
11342                            Some(buffer.text_for_range(selection.range()).collect::<String>());
11343                    }
11344
11345                    if let Some(next_selection) = selections_iter.peek() {
11346                        if next_selection.range().len() == selection.range().len() {
11347                            let next_selected_text = buffer
11348                                .text_for_range(next_selection.range())
11349                                .collect::<String>();
11350                            if Some(next_selected_text) != selected_text {
11351                                same_text_selected = false;
11352                                selected_text = None;
11353                            }
11354                        } else {
11355                            same_text_selected = false;
11356                            selected_text = None;
11357                        }
11358                    }
11359                }
11360            }
11361
11362            if only_carets {
11363                for selection in &mut selections {
11364                    let word_range = movement::surrounding_word(
11365                        &display_map,
11366                        selection.start.to_display_point(&display_map),
11367                    );
11368                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
11369                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
11370                    selection.goal = SelectionGoal::None;
11371                    selection.reversed = false;
11372                }
11373                if selections.len() == 1 {
11374                    let selection = selections
11375                        .last()
11376                        .expect("ensured that there's only one selection");
11377                    let query = buffer
11378                        .text_for_range(selection.start..selection.end)
11379                        .collect::<String>();
11380                    let is_empty = query.is_empty();
11381                    let select_state = SelectNextState {
11382                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
11383                        wordwise: true,
11384                        done: is_empty,
11385                    };
11386                    self.select_prev_state = Some(select_state);
11387                } else {
11388                    self.select_prev_state = None;
11389                }
11390
11391                self.unfold_ranges(
11392                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
11393                    false,
11394                    true,
11395                    cx,
11396                );
11397                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11398                    s.select(selections);
11399                });
11400            } else if let Some(selected_text) = selected_text {
11401                self.select_prev_state = Some(SelectNextState {
11402                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
11403                    wordwise: false,
11404                    done: false,
11405                });
11406                self.select_previous(action, window, cx)?;
11407            }
11408        }
11409        Ok(())
11410    }
11411
11412    pub fn toggle_comments(
11413        &mut self,
11414        action: &ToggleComments,
11415        window: &mut Window,
11416        cx: &mut Context<Self>,
11417    ) {
11418        if self.read_only(cx) {
11419            return;
11420        }
11421        let text_layout_details = &self.text_layout_details(window);
11422        self.transact(window, cx, |this, window, cx| {
11423            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
11424            let mut edits = Vec::new();
11425            let mut selection_edit_ranges = Vec::new();
11426            let mut last_toggled_row = None;
11427            let snapshot = this.buffer.read(cx).read(cx);
11428            let empty_str: Arc<str> = Arc::default();
11429            let mut suffixes_inserted = Vec::new();
11430            let ignore_indent = action.ignore_indent;
11431
11432            fn comment_prefix_range(
11433                snapshot: &MultiBufferSnapshot,
11434                row: MultiBufferRow,
11435                comment_prefix: &str,
11436                comment_prefix_whitespace: &str,
11437                ignore_indent: bool,
11438            ) -> Range<Point> {
11439                let indent_size = if ignore_indent {
11440                    0
11441                } else {
11442                    snapshot.indent_size_for_line(row).len
11443                };
11444
11445                let start = Point::new(row.0, indent_size);
11446
11447                let mut line_bytes = snapshot
11448                    .bytes_in_range(start..snapshot.max_point())
11449                    .flatten()
11450                    .copied();
11451
11452                // If this line currently begins with the line comment prefix, then record
11453                // the range containing the prefix.
11454                if line_bytes
11455                    .by_ref()
11456                    .take(comment_prefix.len())
11457                    .eq(comment_prefix.bytes())
11458                {
11459                    // Include any whitespace that matches the comment prefix.
11460                    let matching_whitespace_len = line_bytes
11461                        .zip(comment_prefix_whitespace.bytes())
11462                        .take_while(|(a, b)| a == b)
11463                        .count() as u32;
11464                    let end = Point::new(
11465                        start.row,
11466                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
11467                    );
11468                    start..end
11469                } else {
11470                    start..start
11471                }
11472            }
11473
11474            fn comment_suffix_range(
11475                snapshot: &MultiBufferSnapshot,
11476                row: MultiBufferRow,
11477                comment_suffix: &str,
11478                comment_suffix_has_leading_space: bool,
11479            ) -> Range<Point> {
11480                let end = Point::new(row.0, snapshot.line_len(row));
11481                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
11482
11483                let mut line_end_bytes = snapshot
11484                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
11485                    .flatten()
11486                    .copied();
11487
11488                let leading_space_len = if suffix_start_column > 0
11489                    && line_end_bytes.next() == Some(b' ')
11490                    && comment_suffix_has_leading_space
11491                {
11492                    1
11493                } else {
11494                    0
11495                };
11496
11497                // If this line currently begins with the line comment prefix, then record
11498                // the range containing the prefix.
11499                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
11500                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
11501                    start..end
11502                } else {
11503                    end..end
11504                }
11505            }
11506
11507            // TODO: Handle selections that cross excerpts
11508            for selection in &mut selections {
11509                let start_column = snapshot
11510                    .indent_size_for_line(MultiBufferRow(selection.start.row))
11511                    .len;
11512                let language = if let Some(language) =
11513                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
11514                {
11515                    language
11516                } else {
11517                    continue;
11518                };
11519
11520                selection_edit_ranges.clear();
11521
11522                // If multiple selections contain a given row, avoid processing that
11523                // row more than once.
11524                let mut start_row = MultiBufferRow(selection.start.row);
11525                if last_toggled_row == Some(start_row) {
11526                    start_row = start_row.next_row();
11527                }
11528                let end_row =
11529                    if selection.end.row > selection.start.row && selection.end.column == 0 {
11530                        MultiBufferRow(selection.end.row - 1)
11531                    } else {
11532                        MultiBufferRow(selection.end.row)
11533                    };
11534                last_toggled_row = Some(end_row);
11535
11536                if start_row > end_row {
11537                    continue;
11538                }
11539
11540                // If the language has line comments, toggle those.
11541                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
11542
11543                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
11544                if ignore_indent {
11545                    full_comment_prefixes = full_comment_prefixes
11546                        .into_iter()
11547                        .map(|s| Arc::from(s.trim_end()))
11548                        .collect();
11549                }
11550
11551                if !full_comment_prefixes.is_empty() {
11552                    let first_prefix = full_comment_prefixes
11553                        .first()
11554                        .expect("prefixes is non-empty");
11555                    let prefix_trimmed_lengths = full_comment_prefixes
11556                        .iter()
11557                        .map(|p| p.trim_end_matches(' ').len())
11558                        .collect::<SmallVec<[usize; 4]>>();
11559
11560                    let mut all_selection_lines_are_comments = true;
11561
11562                    for row in start_row.0..=end_row.0 {
11563                        let row = MultiBufferRow(row);
11564                        if start_row < end_row && snapshot.is_line_blank(row) {
11565                            continue;
11566                        }
11567
11568                        let prefix_range = full_comment_prefixes
11569                            .iter()
11570                            .zip(prefix_trimmed_lengths.iter().copied())
11571                            .map(|(prefix, trimmed_prefix_len)| {
11572                                comment_prefix_range(
11573                                    snapshot.deref(),
11574                                    row,
11575                                    &prefix[..trimmed_prefix_len],
11576                                    &prefix[trimmed_prefix_len..],
11577                                    ignore_indent,
11578                                )
11579                            })
11580                            .max_by_key(|range| range.end.column - range.start.column)
11581                            .expect("prefixes is non-empty");
11582
11583                        if prefix_range.is_empty() {
11584                            all_selection_lines_are_comments = false;
11585                        }
11586
11587                        selection_edit_ranges.push(prefix_range);
11588                    }
11589
11590                    if all_selection_lines_are_comments {
11591                        edits.extend(
11592                            selection_edit_ranges
11593                                .iter()
11594                                .cloned()
11595                                .map(|range| (range, empty_str.clone())),
11596                        );
11597                    } else {
11598                        let min_column = selection_edit_ranges
11599                            .iter()
11600                            .map(|range| range.start.column)
11601                            .min()
11602                            .unwrap_or(0);
11603                        edits.extend(selection_edit_ranges.iter().map(|range| {
11604                            let position = Point::new(range.start.row, min_column);
11605                            (position..position, first_prefix.clone())
11606                        }));
11607                    }
11608                } else if let Some((full_comment_prefix, comment_suffix)) =
11609                    language.block_comment_delimiters()
11610                {
11611                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
11612                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
11613                    let prefix_range = comment_prefix_range(
11614                        snapshot.deref(),
11615                        start_row,
11616                        comment_prefix,
11617                        comment_prefix_whitespace,
11618                        ignore_indent,
11619                    );
11620                    let suffix_range = comment_suffix_range(
11621                        snapshot.deref(),
11622                        end_row,
11623                        comment_suffix.trim_start_matches(' '),
11624                        comment_suffix.starts_with(' '),
11625                    );
11626
11627                    if prefix_range.is_empty() || suffix_range.is_empty() {
11628                        edits.push((
11629                            prefix_range.start..prefix_range.start,
11630                            full_comment_prefix.clone(),
11631                        ));
11632                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
11633                        suffixes_inserted.push((end_row, comment_suffix.len()));
11634                    } else {
11635                        edits.push((prefix_range, empty_str.clone()));
11636                        edits.push((suffix_range, empty_str.clone()));
11637                    }
11638                } else {
11639                    continue;
11640                }
11641            }
11642
11643            drop(snapshot);
11644            this.buffer.update(cx, |buffer, cx| {
11645                buffer.edit(edits, None, cx);
11646            });
11647
11648            // Adjust selections so that they end before any comment suffixes that
11649            // were inserted.
11650            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
11651            let mut selections = this.selections.all::<Point>(cx);
11652            let snapshot = this.buffer.read(cx).read(cx);
11653            for selection in &mut selections {
11654                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
11655                    match row.cmp(&MultiBufferRow(selection.end.row)) {
11656                        Ordering::Less => {
11657                            suffixes_inserted.next();
11658                            continue;
11659                        }
11660                        Ordering::Greater => break,
11661                        Ordering::Equal => {
11662                            if selection.end.column == snapshot.line_len(row) {
11663                                if selection.is_empty() {
11664                                    selection.start.column -= suffix_len as u32;
11665                                }
11666                                selection.end.column -= suffix_len as u32;
11667                            }
11668                            break;
11669                        }
11670                    }
11671                }
11672            }
11673
11674            drop(snapshot);
11675            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11676                s.select(selections)
11677            });
11678
11679            let selections = this.selections.all::<Point>(cx);
11680            let selections_on_single_row = selections.windows(2).all(|selections| {
11681                selections[0].start.row == selections[1].start.row
11682                    && selections[0].end.row == selections[1].end.row
11683                    && selections[0].start.row == selections[0].end.row
11684            });
11685            let selections_selecting = selections
11686                .iter()
11687                .any(|selection| selection.start != selection.end);
11688            let advance_downwards = action.advance_downwards
11689                && selections_on_single_row
11690                && !selections_selecting
11691                && !matches!(this.mode, EditorMode::SingleLine { .. });
11692
11693            if advance_downwards {
11694                let snapshot = this.buffer.read(cx).snapshot(cx);
11695
11696                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11697                    s.move_cursors_with(|display_snapshot, display_point, _| {
11698                        let mut point = display_point.to_point(display_snapshot);
11699                        point.row += 1;
11700                        point = snapshot.clip_point(point, Bias::Left);
11701                        let display_point = point.to_display_point(display_snapshot);
11702                        let goal = SelectionGoal::HorizontalPosition(
11703                            display_snapshot
11704                                .x_for_display_point(display_point, text_layout_details)
11705                                .into(),
11706                        );
11707                        (display_point, goal)
11708                    })
11709                });
11710            }
11711        });
11712    }
11713
11714    pub fn select_enclosing_symbol(
11715        &mut self,
11716        _: &SelectEnclosingSymbol,
11717        window: &mut Window,
11718        cx: &mut Context<Self>,
11719    ) {
11720        let buffer = self.buffer.read(cx).snapshot(cx);
11721        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
11722
11723        fn update_selection(
11724            selection: &Selection<usize>,
11725            buffer_snap: &MultiBufferSnapshot,
11726        ) -> Option<Selection<usize>> {
11727            let cursor = selection.head();
11728            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
11729            for symbol in symbols.iter().rev() {
11730                let start = symbol.range.start.to_offset(buffer_snap);
11731                let end = symbol.range.end.to_offset(buffer_snap);
11732                let new_range = start..end;
11733                if start < selection.start || end > selection.end {
11734                    return Some(Selection {
11735                        id: selection.id,
11736                        start: new_range.start,
11737                        end: new_range.end,
11738                        goal: SelectionGoal::None,
11739                        reversed: selection.reversed,
11740                    });
11741                }
11742            }
11743            None
11744        }
11745
11746        let mut selected_larger_symbol = false;
11747        let new_selections = old_selections
11748            .iter()
11749            .map(|selection| match update_selection(selection, &buffer) {
11750                Some(new_selection) => {
11751                    if new_selection.range() != selection.range() {
11752                        selected_larger_symbol = true;
11753                    }
11754                    new_selection
11755                }
11756                None => selection.clone(),
11757            })
11758            .collect::<Vec<_>>();
11759
11760        if selected_larger_symbol {
11761            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11762                s.select(new_selections);
11763            });
11764        }
11765    }
11766
11767    pub fn select_larger_syntax_node(
11768        &mut self,
11769        _: &SelectLargerSyntaxNode,
11770        window: &mut Window,
11771        cx: &mut Context<Self>,
11772    ) {
11773        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11774        let buffer = self.buffer.read(cx).snapshot(cx);
11775        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
11776
11777        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
11778        let mut selected_larger_node = false;
11779        let new_selections = old_selections
11780            .iter()
11781            .map(|selection| {
11782                let old_range = selection.start..selection.end;
11783                let mut new_range = old_range.clone();
11784                let mut new_node = None;
11785                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
11786                {
11787                    new_node = Some(node);
11788                    new_range = match containing_range {
11789                        MultiOrSingleBufferOffsetRange::Single(_) => break,
11790                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
11791                    };
11792                    if !display_map.intersects_fold(new_range.start)
11793                        && !display_map.intersects_fold(new_range.end)
11794                    {
11795                        break;
11796                    }
11797                }
11798
11799                if let Some(node) = new_node {
11800                    // Log the ancestor, to support using this action as a way to explore TreeSitter
11801                    // nodes. Parent and grandparent are also logged because this operation will not
11802                    // visit nodes that have the same range as their parent.
11803                    log::info!("Node: {node:?}");
11804                    let parent = node.parent();
11805                    log::info!("Parent: {parent:?}");
11806                    let grandparent = parent.and_then(|x| x.parent());
11807                    log::info!("Grandparent: {grandparent:?}");
11808                }
11809
11810                selected_larger_node |= new_range != old_range;
11811                Selection {
11812                    id: selection.id,
11813                    start: new_range.start,
11814                    end: new_range.end,
11815                    goal: SelectionGoal::None,
11816                    reversed: selection.reversed,
11817                }
11818            })
11819            .collect::<Vec<_>>();
11820
11821        if selected_larger_node {
11822            stack.push(old_selections);
11823            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11824                s.select(new_selections);
11825            });
11826        }
11827        self.select_larger_syntax_node_stack = stack;
11828    }
11829
11830    pub fn select_smaller_syntax_node(
11831        &mut self,
11832        _: &SelectSmallerSyntaxNode,
11833        window: &mut Window,
11834        cx: &mut Context<Self>,
11835    ) {
11836        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
11837        if let Some(selections) = stack.pop() {
11838            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11839                s.select(selections.to_vec());
11840            });
11841        }
11842        self.select_larger_syntax_node_stack = stack;
11843    }
11844
11845    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
11846        if !EditorSettings::get_global(cx).gutter.runnables {
11847            self.clear_tasks();
11848            return Task::ready(());
11849        }
11850        let project = self.project.as_ref().map(Entity::downgrade);
11851        cx.spawn_in(window, async move |this, cx| {
11852            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
11853            let Some(project) = project.and_then(|p| p.upgrade()) else {
11854                return;
11855            };
11856            let Ok(display_snapshot) = this.update(cx, |this, cx| {
11857                this.display_map.update(cx, |map, cx| map.snapshot(cx))
11858            }) else {
11859                return;
11860            };
11861
11862            let hide_runnables = project
11863                .update(cx, |project, cx| {
11864                    // Do not display any test indicators in non-dev server remote projects.
11865                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
11866                })
11867                .unwrap_or(true);
11868            if hide_runnables {
11869                return;
11870            }
11871            let new_rows =
11872                cx.background_spawn({
11873                    let snapshot = display_snapshot.clone();
11874                    async move {
11875                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
11876                    }
11877                })
11878                    .await;
11879
11880            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
11881            this.update(cx, |this, _| {
11882                this.clear_tasks();
11883                for (key, value) in rows {
11884                    this.insert_tasks(key, value);
11885                }
11886            })
11887            .ok();
11888        })
11889    }
11890    fn fetch_runnable_ranges(
11891        snapshot: &DisplaySnapshot,
11892        range: Range<Anchor>,
11893    ) -> Vec<language::RunnableRange> {
11894        snapshot.buffer_snapshot.runnable_ranges(range).collect()
11895    }
11896
11897    fn runnable_rows(
11898        project: Entity<Project>,
11899        snapshot: DisplaySnapshot,
11900        runnable_ranges: Vec<RunnableRange>,
11901        mut cx: AsyncWindowContext,
11902    ) -> Vec<((BufferId, u32), RunnableTasks)> {
11903        runnable_ranges
11904            .into_iter()
11905            .filter_map(|mut runnable| {
11906                let tasks = cx
11907                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
11908                    .ok()?;
11909                if tasks.is_empty() {
11910                    return None;
11911                }
11912
11913                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
11914
11915                let row = snapshot
11916                    .buffer_snapshot
11917                    .buffer_line_for_row(MultiBufferRow(point.row))?
11918                    .1
11919                    .start
11920                    .row;
11921
11922                let context_range =
11923                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
11924                Some((
11925                    (runnable.buffer_id, row),
11926                    RunnableTasks {
11927                        templates: tasks,
11928                        offset: snapshot
11929                            .buffer_snapshot
11930                            .anchor_before(runnable.run_range.start),
11931                        context_range,
11932                        column: point.column,
11933                        extra_variables: runnable.extra_captures,
11934                    },
11935                ))
11936            })
11937            .collect()
11938    }
11939
11940    fn templates_with_tags(
11941        project: &Entity<Project>,
11942        runnable: &mut Runnable,
11943        cx: &mut App,
11944    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
11945        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
11946            let (worktree_id, file) = project
11947                .buffer_for_id(runnable.buffer, cx)
11948                .and_then(|buffer| buffer.read(cx).file())
11949                .map(|file| (file.worktree_id(cx), file.clone()))
11950                .unzip();
11951
11952            (
11953                project.task_store().read(cx).task_inventory().cloned(),
11954                worktree_id,
11955                file,
11956            )
11957        });
11958
11959        let tags = mem::take(&mut runnable.tags);
11960        let mut tags: Vec<_> = tags
11961            .into_iter()
11962            .flat_map(|tag| {
11963                let tag = tag.0.clone();
11964                inventory
11965                    .as_ref()
11966                    .into_iter()
11967                    .flat_map(|inventory| {
11968                        inventory.read(cx).list_tasks(
11969                            file.clone(),
11970                            Some(runnable.language.clone()),
11971                            worktree_id,
11972                            cx,
11973                        )
11974                    })
11975                    .filter(move |(_, template)| {
11976                        template.tags.iter().any(|source_tag| source_tag == &tag)
11977                    })
11978            })
11979            .sorted_by_key(|(kind, _)| kind.to_owned())
11980            .collect();
11981        if let Some((leading_tag_source, _)) = tags.first() {
11982            // Strongest source wins; if we have worktree tag binding, prefer that to
11983            // global and language bindings;
11984            // if we have a global binding, prefer that to language binding.
11985            let first_mismatch = tags
11986                .iter()
11987                .position(|(tag_source, _)| tag_source != leading_tag_source);
11988            if let Some(index) = first_mismatch {
11989                tags.truncate(index);
11990            }
11991        }
11992
11993        tags
11994    }
11995
11996    pub fn move_to_enclosing_bracket(
11997        &mut self,
11998        _: &MoveToEnclosingBracket,
11999        window: &mut Window,
12000        cx: &mut Context<Self>,
12001    ) {
12002        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12003            s.move_offsets_with(|snapshot, selection| {
12004                let Some(enclosing_bracket_ranges) =
12005                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
12006                else {
12007                    return;
12008                };
12009
12010                let mut best_length = usize::MAX;
12011                let mut best_inside = false;
12012                let mut best_in_bracket_range = false;
12013                let mut best_destination = None;
12014                for (open, close) in enclosing_bracket_ranges {
12015                    let close = close.to_inclusive();
12016                    let length = close.end() - open.start;
12017                    let inside = selection.start >= open.end && selection.end <= *close.start();
12018                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
12019                        || close.contains(&selection.head());
12020
12021                    // If best is next to a bracket and current isn't, skip
12022                    if !in_bracket_range && best_in_bracket_range {
12023                        continue;
12024                    }
12025
12026                    // Prefer smaller lengths unless best is inside and current isn't
12027                    if length > best_length && (best_inside || !inside) {
12028                        continue;
12029                    }
12030
12031                    best_length = length;
12032                    best_inside = inside;
12033                    best_in_bracket_range = in_bracket_range;
12034                    best_destination = Some(
12035                        if close.contains(&selection.start) && close.contains(&selection.end) {
12036                            if inside {
12037                                open.end
12038                            } else {
12039                                open.start
12040                            }
12041                        } else if inside {
12042                            *close.start()
12043                        } else {
12044                            *close.end()
12045                        },
12046                    );
12047                }
12048
12049                if let Some(destination) = best_destination {
12050                    selection.collapse_to(destination, SelectionGoal::None);
12051                }
12052            })
12053        });
12054    }
12055
12056    pub fn undo_selection(
12057        &mut self,
12058        _: &UndoSelection,
12059        window: &mut Window,
12060        cx: &mut Context<Self>,
12061    ) {
12062        self.end_selection(window, cx);
12063        self.selection_history.mode = SelectionHistoryMode::Undoing;
12064        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
12065            self.change_selections(None, window, cx, |s| {
12066                s.select_anchors(entry.selections.to_vec())
12067            });
12068            self.select_next_state = entry.select_next_state;
12069            self.select_prev_state = entry.select_prev_state;
12070            self.add_selections_state = entry.add_selections_state;
12071            self.request_autoscroll(Autoscroll::newest(), cx);
12072        }
12073        self.selection_history.mode = SelectionHistoryMode::Normal;
12074    }
12075
12076    pub fn redo_selection(
12077        &mut self,
12078        _: &RedoSelection,
12079        window: &mut Window,
12080        cx: &mut Context<Self>,
12081    ) {
12082        self.end_selection(window, cx);
12083        self.selection_history.mode = SelectionHistoryMode::Redoing;
12084        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
12085            self.change_selections(None, window, cx, |s| {
12086                s.select_anchors(entry.selections.to_vec())
12087            });
12088            self.select_next_state = entry.select_next_state;
12089            self.select_prev_state = entry.select_prev_state;
12090            self.add_selections_state = entry.add_selections_state;
12091            self.request_autoscroll(Autoscroll::newest(), cx);
12092        }
12093        self.selection_history.mode = SelectionHistoryMode::Normal;
12094    }
12095
12096    pub fn expand_excerpts(
12097        &mut self,
12098        action: &ExpandExcerpts,
12099        _: &mut Window,
12100        cx: &mut Context<Self>,
12101    ) {
12102        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
12103    }
12104
12105    pub fn expand_excerpts_down(
12106        &mut self,
12107        action: &ExpandExcerptsDown,
12108        _: &mut Window,
12109        cx: &mut Context<Self>,
12110    ) {
12111        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
12112    }
12113
12114    pub fn expand_excerpts_up(
12115        &mut self,
12116        action: &ExpandExcerptsUp,
12117        _: &mut Window,
12118        cx: &mut Context<Self>,
12119    ) {
12120        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
12121    }
12122
12123    pub fn expand_excerpts_for_direction(
12124        &mut self,
12125        lines: u32,
12126        direction: ExpandExcerptDirection,
12127
12128        cx: &mut Context<Self>,
12129    ) {
12130        let selections = self.selections.disjoint_anchors();
12131
12132        let lines = if lines == 0 {
12133            EditorSettings::get_global(cx).expand_excerpt_lines
12134        } else {
12135            lines
12136        };
12137
12138        self.buffer.update(cx, |buffer, cx| {
12139            let snapshot = buffer.snapshot(cx);
12140            let mut excerpt_ids = selections
12141                .iter()
12142                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
12143                .collect::<Vec<_>>();
12144            excerpt_ids.sort();
12145            excerpt_ids.dedup();
12146            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
12147        })
12148    }
12149
12150    pub fn expand_excerpt(
12151        &mut self,
12152        excerpt: ExcerptId,
12153        direction: ExpandExcerptDirection,
12154        window: &mut Window,
12155        cx: &mut Context<Self>,
12156    ) {
12157        let current_scroll_position = self.scroll_position(cx);
12158        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
12159        self.buffer.update(cx, |buffer, cx| {
12160            buffer.expand_excerpts([excerpt], lines, direction, cx)
12161        });
12162        if direction == ExpandExcerptDirection::Down {
12163            let new_scroll_position = current_scroll_position + gpui::Point::new(0.0, lines as f32);
12164            self.set_scroll_position(new_scroll_position, window, cx);
12165        }
12166    }
12167
12168    pub fn go_to_singleton_buffer_point(
12169        &mut self,
12170        point: Point,
12171        window: &mut Window,
12172        cx: &mut Context<Self>,
12173    ) {
12174        self.go_to_singleton_buffer_range(point..point, window, cx);
12175    }
12176
12177    pub fn go_to_singleton_buffer_range(
12178        &mut self,
12179        range: Range<Point>,
12180        window: &mut Window,
12181        cx: &mut Context<Self>,
12182    ) {
12183        let multibuffer = self.buffer().read(cx);
12184        let Some(buffer) = multibuffer.as_singleton() else {
12185            return;
12186        };
12187        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
12188            return;
12189        };
12190        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
12191            return;
12192        };
12193        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
12194            s.select_anchor_ranges([start..end])
12195        });
12196    }
12197
12198    fn go_to_diagnostic(
12199        &mut self,
12200        _: &GoToDiagnostic,
12201        window: &mut Window,
12202        cx: &mut Context<Self>,
12203    ) {
12204        self.go_to_diagnostic_impl(Direction::Next, window, cx)
12205    }
12206
12207    fn go_to_prev_diagnostic(
12208        &mut self,
12209        _: &GoToPreviousDiagnostic,
12210        window: &mut Window,
12211        cx: &mut Context<Self>,
12212    ) {
12213        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
12214    }
12215
12216    pub fn go_to_diagnostic_impl(
12217        &mut self,
12218        direction: Direction,
12219        window: &mut Window,
12220        cx: &mut Context<Self>,
12221    ) {
12222        let buffer = self.buffer.read(cx).snapshot(cx);
12223        let selection = self.selections.newest::<usize>(cx);
12224
12225        // If there is an active Diagnostic Popover jump to its diagnostic instead.
12226        if direction == Direction::Next {
12227            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
12228                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
12229                    return;
12230                };
12231                self.activate_diagnostics(
12232                    buffer_id,
12233                    popover.local_diagnostic.diagnostic.group_id,
12234                    window,
12235                    cx,
12236                );
12237                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
12238                    let primary_range_start = active_diagnostics.primary_range.start;
12239                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12240                        let mut new_selection = s.newest_anchor().clone();
12241                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
12242                        s.select_anchors(vec![new_selection.clone()]);
12243                    });
12244                    self.refresh_inline_completion(false, true, window, cx);
12245                }
12246                return;
12247            }
12248        }
12249
12250        let active_group_id = self
12251            .active_diagnostics
12252            .as_ref()
12253            .map(|active_group| active_group.group_id);
12254        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
12255            active_diagnostics
12256                .primary_range
12257                .to_offset(&buffer)
12258                .to_inclusive()
12259        });
12260        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
12261            if active_primary_range.contains(&selection.head()) {
12262                *active_primary_range.start()
12263            } else {
12264                selection.head()
12265            }
12266        } else {
12267            selection.head()
12268        };
12269
12270        let snapshot = self.snapshot(window, cx);
12271        let primary_diagnostics_before = buffer
12272            .diagnostics_in_range::<usize>(0..search_start)
12273            .filter(|entry| entry.diagnostic.is_primary)
12274            .filter(|entry| entry.range.start != entry.range.end)
12275            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
12276            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
12277            .collect::<Vec<_>>();
12278        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
12279            primary_diagnostics_before
12280                .iter()
12281                .position(|entry| entry.diagnostic.group_id == active_group_id)
12282        });
12283
12284        let primary_diagnostics_after = buffer
12285            .diagnostics_in_range::<usize>(search_start..buffer.len())
12286            .filter(|entry| entry.diagnostic.is_primary)
12287            .filter(|entry| entry.range.start != entry.range.end)
12288            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
12289            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
12290            .collect::<Vec<_>>();
12291        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
12292            primary_diagnostics_after
12293                .iter()
12294                .enumerate()
12295                .rev()
12296                .find_map(|(i, entry)| {
12297                    if entry.diagnostic.group_id == active_group_id {
12298                        Some(i)
12299                    } else {
12300                        None
12301                    }
12302                })
12303        });
12304
12305        let next_primary_diagnostic = match direction {
12306            Direction::Prev => primary_diagnostics_before
12307                .iter()
12308                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
12309                .rev()
12310                .next(),
12311            Direction::Next => primary_diagnostics_after
12312                .iter()
12313                .skip(
12314                    last_same_group_diagnostic_after
12315                        .map(|index| index + 1)
12316                        .unwrap_or(0),
12317                )
12318                .next(),
12319        };
12320
12321        // Cycle around to the start of the buffer, potentially moving back to the start of
12322        // the currently active diagnostic.
12323        let cycle_around = || match direction {
12324            Direction::Prev => primary_diagnostics_after
12325                .iter()
12326                .rev()
12327                .chain(primary_diagnostics_before.iter().rev())
12328                .next(),
12329            Direction::Next => primary_diagnostics_before
12330                .iter()
12331                .chain(primary_diagnostics_after.iter())
12332                .next(),
12333        };
12334
12335        if let Some((primary_range, group_id)) = next_primary_diagnostic
12336            .or_else(cycle_around)
12337            .map(|entry| (&entry.range, entry.diagnostic.group_id))
12338        {
12339            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
12340                return;
12341            };
12342            self.activate_diagnostics(buffer_id, group_id, window, cx);
12343            if self.active_diagnostics.is_some() {
12344                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12345                    s.select(vec![Selection {
12346                        id: selection.id,
12347                        start: primary_range.start,
12348                        end: primary_range.start,
12349                        reversed: false,
12350                        goal: SelectionGoal::None,
12351                    }]);
12352                });
12353                self.refresh_inline_completion(false, true, window, cx);
12354            }
12355        }
12356    }
12357
12358    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
12359        let snapshot = self.snapshot(window, cx);
12360        let selection = self.selections.newest::<Point>(cx);
12361        self.go_to_hunk_before_or_after_position(
12362            &snapshot,
12363            selection.head(),
12364            Direction::Next,
12365            window,
12366            cx,
12367        );
12368    }
12369
12370    fn go_to_hunk_before_or_after_position(
12371        &mut self,
12372        snapshot: &EditorSnapshot,
12373        position: Point,
12374        direction: Direction,
12375        window: &mut Window,
12376        cx: &mut Context<Editor>,
12377    ) {
12378        let row = if direction == Direction::Next {
12379            self.hunk_after_position(snapshot, position)
12380                .map(|hunk| hunk.row_range.start)
12381        } else {
12382            self.hunk_before_position(snapshot, position)
12383        };
12384
12385        if let Some(row) = row {
12386            let destination = Point::new(row.0, 0);
12387            let autoscroll = Autoscroll::center();
12388
12389            self.unfold_ranges(&[destination..destination], false, false, cx);
12390            self.change_selections(Some(autoscroll), window, cx, |s| {
12391                s.select_ranges([destination..destination]);
12392            });
12393        }
12394    }
12395
12396    fn hunk_after_position(
12397        &mut self,
12398        snapshot: &EditorSnapshot,
12399        position: Point,
12400    ) -> Option<MultiBufferDiffHunk> {
12401        snapshot
12402            .buffer_snapshot
12403            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
12404            .find(|hunk| hunk.row_range.start.0 > position.row)
12405            .or_else(|| {
12406                snapshot
12407                    .buffer_snapshot
12408                    .diff_hunks_in_range(Point::zero()..position)
12409                    .find(|hunk| hunk.row_range.end.0 < position.row)
12410            })
12411    }
12412
12413    fn go_to_prev_hunk(
12414        &mut self,
12415        _: &GoToPreviousHunk,
12416        window: &mut Window,
12417        cx: &mut Context<Self>,
12418    ) {
12419        let snapshot = self.snapshot(window, cx);
12420        let selection = self.selections.newest::<Point>(cx);
12421        self.go_to_hunk_before_or_after_position(
12422            &snapshot,
12423            selection.head(),
12424            Direction::Prev,
12425            window,
12426            cx,
12427        );
12428    }
12429
12430    fn hunk_before_position(
12431        &mut self,
12432        snapshot: &EditorSnapshot,
12433        position: Point,
12434    ) -> Option<MultiBufferRow> {
12435        snapshot
12436            .buffer_snapshot
12437            .diff_hunk_before(position)
12438            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
12439    }
12440
12441    fn go_to_line<T: 'static>(
12442        &mut self,
12443        position: Anchor,
12444        highlight_color: Option<Hsla>,
12445        window: &mut Window,
12446        cx: &mut Context<Self>,
12447    ) {
12448        let snapshot = self.snapshot(window, cx).display_snapshot;
12449        let position = position.to_point(&snapshot.buffer_snapshot);
12450        let start = snapshot
12451            .buffer_snapshot
12452            .clip_point(Point::new(position.row, 0), Bias::Left);
12453        let end = start + Point::new(1, 0);
12454        let start = snapshot.buffer_snapshot.anchor_before(start);
12455        let end = snapshot.buffer_snapshot.anchor_before(end);
12456
12457        self.clear_row_highlights::<T>();
12458        self.highlight_rows::<T>(
12459            start..end,
12460            highlight_color
12461                .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
12462            true,
12463            cx,
12464        );
12465        self.request_autoscroll(Autoscroll::center(), cx);
12466    }
12467
12468    pub fn go_to_definition(
12469        &mut self,
12470        _: &GoToDefinition,
12471        window: &mut Window,
12472        cx: &mut Context<Self>,
12473    ) -> Task<Result<Navigated>> {
12474        let definition =
12475            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
12476        cx.spawn_in(window, async move |editor, cx| {
12477            if definition.await? == Navigated::Yes {
12478                return Ok(Navigated::Yes);
12479            }
12480            match editor.update_in(cx, |editor, window, cx| {
12481                editor.find_all_references(&FindAllReferences, window, cx)
12482            })? {
12483                Some(references) => references.await,
12484                None => Ok(Navigated::No),
12485            }
12486        })
12487    }
12488
12489    pub fn go_to_declaration(
12490        &mut self,
12491        _: &GoToDeclaration,
12492        window: &mut Window,
12493        cx: &mut Context<Self>,
12494    ) -> Task<Result<Navigated>> {
12495        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
12496    }
12497
12498    pub fn go_to_declaration_split(
12499        &mut self,
12500        _: &GoToDeclaration,
12501        window: &mut Window,
12502        cx: &mut Context<Self>,
12503    ) -> Task<Result<Navigated>> {
12504        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
12505    }
12506
12507    pub fn go_to_implementation(
12508        &mut self,
12509        _: &GoToImplementation,
12510        window: &mut Window,
12511        cx: &mut Context<Self>,
12512    ) -> Task<Result<Navigated>> {
12513        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
12514    }
12515
12516    pub fn go_to_implementation_split(
12517        &mut self,
12518        _: &GoToImplementationSplit,
12519        window: &mut Window,
12520        cx: &mut Context<Self>,
12521    ) -> Task<Result<Navigated>> {
12522        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
12523    }
12524
12525    pub fn go_to_type_definition(
12526        &mut self,
12527        _: &GoToTypeDefinition,
12528        window: &mut Window,
12529        cx: &mut Context<Self>,
12530    ) -> Task<Result<Navigated>> {
12531        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
12532    }
12533
12534    pub fn go_to_definition_split(
12535        &mut self,
12536        _: &GoToDefinitionSplit,
12537        window: &mut Window,
12538        cx: &mut Context<Self>,
12539    ) -> Task<Result<Navigated>> {
12540        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
12541    }
12542
12543    pub fn go_to_type_definition_split(
12544        &mut self,
12545        _: &GoToTypeDefinitionSplit,
12546        window: &mut Window,
12547        cx: &mut Context<Self>,
12548    ) -> Task<Result<Navigated>> {
12549        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
12550    }
12551
12552    fn go_to_definition_of_kind(
12553        &mut self,
12554        kind: GotoDefinitionKind,
12555        split: bool,
12556        window: &mut Window,
12557        cx: &mut Context<Self>,
12558    ) -> Task<Result<Navigated>> {
12559        let Some(provider) = self.semantics_provider.clone() else {
12560            return Task::ready(Ok(Navigated::No));
12561        };
12562        let head = self.selections.newest::<usize>(cx).head();
12563        let buffer = self.buffer.read(cx);
12564        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
12565            text_anchor
12566        } else {
12567            return Task::ready(Ok(Navigated::No));
12568        };
12569
12570        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
12571            return Task::ready(Ok(Navigated::No));
12572        };
12573
12574        cx.spawn_in(window, async move |editor, cx| {
12575            let definitions = definitions.await?;
12576            let navigated = editor
12577                .update_in(cx, |editor, window, cx| {
12578                    editor.navigate_to_hover_links(
12579                        Some(kind),
12580                        definitions
12581                            .into_iter()
12582                            .filter(|location| {
12583                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
12584                            })
12585                            .map(HoverLink::Text)
12586                            .collect::<Vec<_>>(),
12587                        split,
12588                        window,
12589                        cx,
12590                    )
12591                })?
12592                .await?;
12593            anyhow::Ok(navigated)
12594        })
12595    }
12596
12597    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
12598        let selection = self.selections.newest_anchor();
12599        let head = selection.head();
12600        let tail = selection.tail();
12601
12602        let Some((buffer, start_position)) =
12603            self.buffer.read(cx).text_anchor_for_position(head, cx)
12604        else {
12605            return;
12606        };
12607
12608        let end_position = if head != tail {
12609            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
12610                return;
12611            };
12612            Some(pos)
12613        } else {
12614            None
12615        };
12616
12617        let url_finder = cx.spawn_in(window, async move |editor, cx| {
12618            let url = if let Some(end_pos) = end_position {
12619                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
12620            } else {
12621                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
12622            };
12623
12624            if let Some(url) = url {
12625                editor.update(cx, |_, cx| {
12626                    cx.open_url(&url);
12627                })
12628            } else {
12629                Ok(())
12630            }
12631        });
12632
12633        url_finder.detach();
12634    }
12635
12636    pub fn open_selected_filename(
12637        &mut self,
12638        _: &OpenSelectedFilename,
12639        window: &mut Window,
12640        cx: &mut Context<Self>,
12641    ) {
12642        let Some(workspace) = self.workspace() else {
12643            return;
12644        };
12645
12646        let position = self.selections.newest_anchor().head();
12647
12648        let Some((buffer, buffer_position)) =
12649            self.buffer.read(cx).text_anchor_for_position(position, cx)
12650        else {
12651            return;
12652        };
12653
12654        let project = self.project.clone();
12655
12656        cx.spawn_in(window, async move |_, cx| {
12657            let result = find_file(&buffer, project, buffer_position, cx).await;
12658
12659            if let Some((_, path)) = result {
12660                workspace
12661                    .update_in(cx, |workspace, window, cx| {
12662                        workspace.open_resolved_path(path, window, cx)
12663                    })?
12664                    .await?;
12665            }
12666            anyhow::Ok(())
12667        })
12668        .detach();
12669    }
12670
12671    pub(crate) fn navigate_to_hover_links(
12672        &mut self,
12673        kind: Option<GotoDefinitionKind>,
12674        mut definitions: Vec<HoverLink>,
12675        split: bool,
12676        window: &mut Window,
12677        cx: &mut Context<Editor>,
12678    ) -> Task<Result<Navigated>> {
12679        // If there is one definition, just open it directly
12680        if definitions.len() == 1 {
12681            let definition = definitions.pop().unwrap();
12682
12683            enum TargetTaskResult {
12684                Location(Option<Location>),
12685                AlreadyNavigated,
12686            }
12687
12688            let target_task = match definition {
12689                HoverLink::Text(link) => {
12690                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
12691                }
12692                HoverLink::InlayHint(lsp_location, server_id) => {
12693                    let computation =
12694                        self.compute_target_location(lsp_location, server_id, window, cx);
12695                    cx.background_spawn(async move {
12696                        let location = computation.await?;
12697                        Ok(TargetTaskResult::Location(location))
12698                    })
12699                }
12700                HoverLink::Url(url) => {
12701                    cx.open_url(&url);
12702                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
12703                }
12704                HoverLink::File(path) => {
12705                    if let Some(workspace) = self.workspace() {
12706                        cx.spawn_in(window, async move |_, cx| {
12707                            workspace
12708                                .update_in(cx, |workspace, window, cx| {
12709                                    workspace.open_resolved_path(path, window, cx)
12710                                })?
12711                                .await
12712                                .map(|_| TargetTaskResult::AlreadyNavigated)
12713                        })
12714                    } else {
12715                        Task::ready(Ok(TargetTaskResult::Location(None)))
12716                    }
12717                }
12718            };
12719            cx.spawn_in(window, async move |editor, cx| {
12720                let target = match target_task.await.context("target resolution task")? {
12721                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
12722                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
12723                    TargetTaskResult::Location(Some(target)) => target,
12724                };
12725
12726                editor.update_in(cx, |editor, window, cx| {
12727                    let Some(workspace) = editor.workspace() else {
12728                        return Navigated::No;
12729                    };
12730                    let pane = workspace.read(cx).active_pane().clone();
12731
12732                    let range = target.range.to_point(target.buffer.read(cx));
12733                    let range = editor.range_for_match(&range);
12734                    let range = collapse_multiline_range(range);
12735
12736                    if !split
12737                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
12738                    {
12739                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
12740                    } else {
12741                        window.defer(cx, move |window, cx| {
12742                            let target_editor: Entity<Self> =
12743                                workspace.update(cx, |workspace, cx| {
12744                                    let pane = if split {
12745                                        workspace.adjacent_pane(window, cx)
12746                                    } else {
12747                                        workspace.active_pane().clone()
12748                                    };
12749
12750                                    workspace.open_project_item(
12751                                        pane,
12752                                        target.buffer.clone(),
12753                                        true,
12754                                        true,
12755                                        window,
12756                                        cx,
12757                                    )
12758                                });
12759                            target_editor.update(cx, |target_editor, cx| {
12760                                // When selecting a definition in a different buffer, disable the nav history
12761                                // to avoid creating a history entry at the previous cursor location.
12762                                pane.update(cx, |pane, _| pane.disable_history());
12763                                target_editor.go_to_singleton_buffer_range(range, window, cx);
12764                                pane.update(cx, |pane, _| pane.enable_history());
12765                            });
12766                        });
12767                    }
12768                    Navigated::Yes
12769                })
12770            })
12771        } else if !definitions.is_empty() {
12772            cx.spawn_in(window, async move |editor, cx| {
12773                let (title, location_tasks, workspace) = editor
12774                    .update_in(cx, |editor, window, cx| {
12775                        let tab_kind = match kind {
12776                            Some(GotoDefinitionKind::Implementation) => "Implementations",
12777                            _ => "Definitions",
12778                        };
12779                        let title = definitions
12780                            .iter()
12781                            .find_map(|definition| match definition {
12782                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
12783                                    let buffer = origin.buffer.read(cx);
12784                                    format!(
12785                                        "{} for {}",
12786                                        tab_kind,
12787                                        buffer
12788                                            .text_for_range(origin.range.clone())
12789                                            .collect::<String>()
12790                                    )
12791                                }),
12792                                HoverLink::InlayHint(_, _) => None,
12793                                HoverLink::Url(_) => None,
12794                                HoverLink::File(_) => None,
12795                            })
12796                            .unwrap_or(tab_kind.to_string());
12797                        let location_tasks = definitions
12798                            .into_iter()
12799                            .map(|definition| match definition {
12800                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
12801                                HoverLink::InlayHint(lsp_location, server_id) => editor
12802                                    .compute_target_location(lsp_location, server_id, window, cx),
12803                                HoverLink::Url(_) => Task::ready(Ok(None)),
12804                                HoverLink::File(_) => Task::ready(Ok(None)),
12805                            })
12806                            .collect::<Vec<_>>();
12807                        (title, location_tasks, editor.workspace().clone())
12808                    })
12809                    .context("location tasks preparation")?;
12810
12811                let locations = future::join_all(location_tasks)
12812                    .await
12813                    .into_iter()
12814                    .filter_map(|location| location.transpose())
12815                    .collect::<Result<_>>()
12816                    .context("location tasks")?;
12817
12818                let Some(workspace) = workspace else {
12819                    return Ok(Navigated::No);
12820                };
12821                let opened = workspace
12822                    .update_in(cx, |workspace, window, cx| {
12823                        Self::open_locations_in_multibuffer(
12824                            workspace,
12825                            locations,
12826                            title,
12827                            split,
12828                            MultibufferSelectionMode::First,
12829                            window,
12830                            cx,
12831                        )
12832                    })
12833                    .ok();
12834
12835                anyhow::Ok(Navigated::from_bool(opened.is_some()))
12836            })
12837        } else {
12838            Task::ready(Ok(Navigated::No))
12839        }
12840    }
12841
12842    fn compute_target_location(
12843        &self,
12844        lsp_location: lsp::Location,
12845        server_id: LanguageServerId,
12846        window: &mut Window,
12847        cx: &mut Context<Self>,
12848    ) -> Task<anyhow::Result<Option<Location>>> {
12849        let Some(project) = self.project.clone() else {
12850            return Task::ready(Ok(None));
12851        };
12852
12853        cx.spawn_in(window, async move |editor, cx| {
12854            let location_task = editor.update(cx, |_, cx| {
12855                project.update(cx, |project, cx| {
12856                    let language_server_name = project
12857                        .language_server_statuses(cx)
12858                        .find(|(id, _)| server_id == *id)
12859                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
12860                    language_server_name.map(|language_server_name| {
12861                        project.open_local_buffer_via_lsp(
12862                            lsp_location.uri.clone(),
12863                            server_id,
12864                            language_server_name,
12865                            cx,
12866                        )
12867                    })
12868                })
12869            })?;
12870            let location = match location_task {
12871                Some(task) => Some({
12872                    let target_buffer_handle = task.await.context("open local buffer")?;
12873                    let range = target_buffer_handle.update(cx, |target_buffer, _| {
12874                        let target_start = target_buffer
12875                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
12876                        let target_end = target_buffer
12877                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
12878                        target_buffer.anchor_after(target_start)
12879                            ..target_buffer.anchor_before(target_end)
12880                    })?;
12881                    Location {
12882                        buffer: target_buffer_handle,
12883                        range,
12884                    }
12885                }),
12886                None => None,
12887            };
12888            Ok(location)
12889        })
12890    }
12891
12892    pub fn find_all_references(
12893        &mut self,
12894        _: &FindAllReferences,
12895        window: &mut Window,
12896        cx: &mut Context<Self>,
12897    ) -> Option<Task<Result<Navigated>>> {
12898        let selection = self.selections.newest::<usize>(cx);
12899        let multi_buffer = self.buffer.read(cx);
12900        let head = selection.head();
12901
12902        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12903        let head_anchor = multi_buffer_snapshot.anchor_at(
12904            head,
12905            if head < selection.tail() {
12906                Bias::Right
12907            } else {
12908                Bias::Left
12909            },
12910        );
12911
12912        match self
12913            .find_all_references_task_sources
12914            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
12915        {
12916            Ok(_) => {
12917                log::info!(
12918                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
12919                );
12920                return None;
12921            }
12922            Err(i) => {
12923                self.find_all_references_task_sources.insert(i, head_anchor);
12924            }
12925        }
12926
12927        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
12928        let workspace = self.workspace()?;
12929        let project = workspace.read(cx).project().clone();
12930        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
12931        Some(cx.spawn_in(window, async move |editor, cx| {
12932            let _cleanup = cx.on_drop(&editor, move |editor, _| {
12933                if let Ok(i) = editor
12934                    .find_all_references_task_sources
12935                    .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
12936                {
12937                    editor.find_all_references_task_sources.remove(i);
12938                }
12939            });
12940
12941            let locations = references.await?;
12942            if locations.is_empty() {
12943                return anyhow::Ok(Navigated::No);
12944            }
12945
12946            workspace.update_in(cx, |workspace, window, cx| {
12947                let title = locations
12948                    .first()
12949                    .as_ref()
12950                    .map(|location| {
12951                        let buffer = location.buffer.read(cx);
12952                        format!(
12953                            "References to `{}`",
12954                            buffer
12955                                .text_for_range(location.range.clone())
12956                                .collect::<String>()
12957                        )
12958                    })
12959                    .unwrap();
12960                Self::open_locations_in_multibuffer(
12961                    workspace,
12962                    locations,
12963                    title,
12964                    false,
12965                    MultibufferSelectionMode::First,
12966                    window,
12967                    cx,
12968                );
12969                Navigated::Yes
12970            })
12971        }))
12972    }
12973
12974    /// Opens a multibuffer with the given project locations in it
12975    pub fn open_locations_in_multibuffer(
12976        workspace: &mut Workspace,
12977        mut locations: Vec<Location>,
12978        title: String,
12979        split: bool,
12980        multibuffer_selection_mode: MultibufferSelectionMode,
12981        window: &mut Window,
12982        cx: &mut Context<Workspace>,
12983    ) {
12984        // If there are multiple definitions, open them in a multibuffer
12985        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
12986        let mut locations = locations.into_iter().peekable();
12987        let mut ranges = Vec::new();
12988        let capability = workspace.project().read(cx).capability();
12989
12990        let excerpt_buffer = cx.new(|cx| {
12991            let mut multibuffer = MultiBuffer::new(capability);
12992            while let Some(location) = locations.next() {
12993                let buffer = location.buffer.read(cx);
12994                let mut ranges_for_buffer = Vec::new();
12995                let range = location.range.to_offset(buffer);
12996                ranges_for_buffer.push(range.clone());
12997
12998                while let Some(next_location) = locations.peek() {
12999                    if next_location.buffer == location.buffer {
13000                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
13001                        locations.next();
13002                    } else {
13003                        break;
13004                    }
13005                }
13006
13007                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
13008                ranges.extend(multibuffer.push_excerpts_with_context_lines(
13009                    location.buffer.clone(),
13010                    ranges_for_buffer,
13011                    DEFAULT_MULTIBUFFER_CONTEXT,
13012                    cx,
13013                ))
13014            }
13015
13016            multibuffer.with_title(title)
13017        });
13018
13019        let editor = cx.new(|cx| {
13020            Editor::for_multibuffer(
13021                excerpt_buffer,
13022                Some(workspace.project().clone()),
13023                window,
13024                cx,
13025            )
13026        });
13027        editor.update(cx, |editor, cx| {
13028            match multibuffer_selection_mode {
13029                MultibufferSelectionMode::First => {
13030                    if let Some(first_range) = ranges.first() {
13031                        editor.change_selections(None, window, cx, |selections| {
13032                            selections.clear_disjoint();
13033                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
13034                        });
13035                    }
13036                    editor.highlight_background::<Self>(
13037                        &ranges,
13038                        |theme| theme.editor_highlighted_line_background,
13039                        cx,
13040                    );
13041                }
13042                MultibufferSelectionMode::All => {
13043                    editor.change_selections(None, window, cx, |selections| {
13044                        selections.clear_disjoint();
13045                        selections.select_anchor_ranges(ranges);
13046                    });
13047                }
13048            }
13049            editor.register_buffers_with_language_servers(cx);
13050        });
13051
13052        let item = Box::new(editor);
13053        let item_id = item.item_id();
13054
13055        if split {
13056            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
13057        } else {
13058            if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
13059                let (preview_item_id, preview_item_idx) =
13060                    workspace.active_pane().update(cx, |pane, _| {
13061                        (pane.preview_item_id(), pane.preview_item_idx())
13062                    });
13063
13064                workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
13065
13066                if let Some(preview_item_id) = preview_item_id {
13067                    workspace.active_pane().update(cx, |pane, cx| {
13068                        pane.remove_item(preview_item_id, false, false, window, cx);
13069                    });
13070                }
13071            } else {
13072                workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
13073            }
13074        }
13075        workspace.active_pane().update(cx, |pane, cx| {
13076            pane.set_preview_item_id(Some(item_id), cx);
13077        });
13078    }
13079
13080    pub fn rename(
13081        &mut self,
13082        _: &Rename,
13083        window: &mut Window,
13084        cx: &mut Context<Self>,
13085    ) -> Option<Task<Result<()>>> {
13086        use language::ToOffset as _;
13087
13088        let provider = self.semantics_provider.clone()?;
13089        let selection = self.selections.newest_anchor().clone();
13090        let (cursor_buffer, cursor_buffer_position) = self
13091            .buffer
13092            .read(cx)
13093            .text_anchor_for_position(selection.head(), cx)?;
13094        let (tail_buffer, cursor_buffer_position_end) = self
13095            .buffer
13096            .read(cx)
13097            .text_anchor_for_position(selection.tail(), cx)?;
13098        if tail_buffer != cursor_buffer {
13099            return None;
13100        }
13101
13102        let snapshot = cursor_buffer.read(cx).snapshot();
13103        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
13104        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
13105        let prepare_rename = provider
13106            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
13107            .unwrap_or_else(|| Task::ready(Ok(None)));
13108        drop(snapshot);
13109
13110        Some(cx.spawn_in(window, async move |this, cx| {
13111            let rename_range = if let Some(range) = prepare_rename.await? {
13112                Some(range)
13113            } else {
13114                this.update(cx, |this, cx| {
13115                    let buffer = this.buffer.read(cx).snapshot(cx);
13116                    let mut buffer_highlights = this
13117                        .document_highlights_for_position(selection.head(), &buffer)
13118                        .filter(|highlight| {
13119                            highlight.start.excerpt_id == selection.head().excerpt_id
13120                                && highlight.end.excerpt_id == selection.head().excerpt_id
13121                        });
13122                    buffer_highlights
13123                        .next()
13124                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
13125                })?
13126            };
13127            if let Some(rename_range) = rename_range {
13128                this.update_in(cx, |this, window, cx| {
13129                    let snapshot = cursor_buffer.read(cx).snapshot();
13130                    let rename_buffer_range = rename_range.to_offset(&snapshot);
13131                    let cursor_offset_in_rename_range =
13132                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
13133                    let cursor_offset_in_rename_range_end =
13134                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
13135
13136                    this.take_rename(false, window, cx);
13137                    let buffer = this.buffer.read(cx).read(cx);
13138                    let cursor_offset = selection.head().to_offset(&buffer);
13139                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
13140                    let rename_end = rename_start + rename_buffer_range.len();
13141                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
13142                    let mut old_highlight_id = None;
13143                    let old_name: Arc<str> = buffer
13144                        .chunks(rename_start..rename_end, true)
13145                        .map(|chunk| {
13146                            if old_highlight_id.is_none() {
13147                                old_highlight_id = chunk.syntax_highlight_id;
13148                            }
13149                            chunk.text
13150                        })
13151                        .collect::<String>()
13152                        .into();
13153
13154                    drop(buffer);
13155
13156                    // Position the selection in the rename editor so that it matches the current selection.
13157                    this.show_local_selections = false;
13158                    let rename_editor = cx.new(|cx| {
13159                        let mut editor = Editor::single_line(window, cx);
13160                        editor.buffer.update(cx, |buffer, cx| {
13161                            buffer.edit([(0..0, old_name.clone())], None, cx)
13162                        });
13163                        let rename_selection_range = match cursor_offset_in_rename_range
13164                            .cmp(&cursor_offset_in_rename_range_end)
13165                        {
13166                            Ordering::Equal => {
13167                                editor.select_all(&SelectAll, window, cx);
13168                                return editor;
13169                            }
13170                            Ordering::Less => {
13171                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
13172                            }
13173                            Ordering::Greater => {
13174                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
13175                            }
13176                        };
13177                        if rename_selection_range.end > old_name.len() {
13178                            editor.select_all(&SelectAll, window, cx);
13179                        } else {
13180                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13181                                s.select_ranges([rename_selection_range]);
13182                            });
13183                        }
13184                        editor
13185                    });
13186                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
13187                        if e == &EditorEvent::Focused {
13188                            cx.emit(EditorEvent::FocusedIn)
13189                        }
13190                    })
13191                    .detach();
13192
13193                    let write_highlights =
13194                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
13195                    let read_highlights =
13196                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
13197                    let ranges = write_highlights
13198                        .iter()
13199                        .flat_map(|(_, ranges)| ranges.iter())
13200                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
13201                        .cloned()
13202                        .collect();
13203
13204                    this.highlight_text::<Rename>(
13205                        ranges,
13206                        HighlightStyle {
13207                            fade_out: Some(0.6),
13208                            ..Default::default()
13209                        },
13210                        cx,
13211                    );
13212                    let rename_focus_handle = rename_editor.focus_handle(cx);
13213                    window.focus(&rename_focus_handle);
13214                    let block_id = this.insert_blocks(
13215                        [BlockProperties {
13216                            style: BlockStyle::Flex,
13217                            placement: BlockPlacement::Below(range.start),
13218                            height: 1,
13219                            render: Arc::new({
13220                                let rename_editor = rename_editor.clone();
13221                                move |cx: &mut BlockContext| {
13222                                    let mut text_style = cx.editor_style.text.clone();
13223                                    if let Some(highlight_style) = old_highlight_id
13224                                        .and_then(|h| h.style(&cx.editor_style.syntax))
13225                                    {
13226                                        text_style = text_style.highlight(highlight_style);
13227                                    }
13228                                    div()
13229                                        .block_mouse_down()
13230                                        .pl(cx.anchor_x)
13231                                        .child(EditorElement::new(
13232                                            &rename_editor,
13233                                            EditorStyle {
13234                                                background: cx.theme().system().transparent,
13235                                                local_player: cx.editor_style.local_player,
13236                                                text: text_style,
13237                                                scrollbar_width: cx.editor_style.scrollbar_width,
13238                                                syntax: cx.editor_style.syntax.clone(),
13239                                                status: cx.editor_style.status.clone(),
13240                                                inlay_hints_style: HighlightStyle {
13241                                                    font_weight: Some(FontWeight::BOLD),
13242                                                    ..make_inlay_hints_style(cx.app)
13243                                                },
13244                                                inline_completion_styles: make_suggestion_styles(
13245                                                    cx.app,
13246                                                ),
13247                                                ..EditorStyle::default()
13248                                            },
13249                                        ))
13250                                        .into_any_element()
13251                                }
13252                            }),
13253                            priority: 0,
13254                        }],
13255                        Some(Autoscroll::fit()),
13256                        cx,
13257                    )[0];
13258                    this.pending_rename = Some(RenameState {
13259                        range,
13260                        old_name,
13261                        editor: rename_editor,
13262                        block_id,
13263                    });
13264                })?;
13265            }
13266
13267            Ok(())
13268        }))
13269    }
13270
13271    pub fn confirm_rename(
13272        &mut self,
13273        _: &ConfirmRename,
13274        window: &mut Window,
13275        cx: &mut Context<Self>,
13276    ) -> Option<Task<Result<()>>> {
13277        let rename = self.take_rename(false, window, cx)?;
13278        let workspace = self.workspace()?.downgrade();
13279        let (buffer, start) = self
13280            .buffer
13281            .read(cx)
13282            .text_anchor_for_position(rename.range.start, cx)?;
13283        let (end_buffer, _) = self
13284            .buffer
13285            .read(cx)
13286            .text_anchor_for_position(rename.range.end, cx)?;
13287        if buffer != end_buffer {
13288            return None;
13289        }
13290
13291        let old_name = rename.old_name;
13292        let new_name = rename.editor.read(cx).text(cx);
13293
13294        let rename = self.semantics_provider.as_ref()?.perform_rename(
13295            &buffer,
13296            start,
13297            new_name.clone(),
13298            cx,
13299        )?;
13300
13301        Some(cx.spawn_in(window, async move |editor, cx| {
13302            let project_transaction = rename.await?;
13303            Self::open_project_transaction(
13304                &editor,
13305                workspace,
13306                project_transaction,
13307                format!("Rename: {}{}", old_name, new_name),
13308                cx,
13309            )
13310            .await?;
13311
13312            editor.update(cx, |editor, cx| {
13313                editor.refresh_document_highlights(cx);
13314            })?;
13315            Ok(())
13316        }))
13317    }
13318
13319    fn take_rename(
13320        &mut self,
13321        moving_cursor: bool,
13322        window: &mut Window,
13323        cx: &mut Context<Self>,
13324    ) -> Option<RenameState> {
13325        let rename = self.pending_rename.take()?;
13326        if rename.editor.focus_handle(cx).is_focused(window) {
13327            window.focus(&self.focus_handle);
13328        }
13329
13330        self.remove_blocks(
13331            [rename.block_id].into_iter().collect(),
13332            Some(Autoscroll::fit()),
13333            cx,
13334        );
13335        self.clear_highlights::<Rename>(cx);
13336        self.show_local_selections = true;
13337
13338        if moving_cursor {
13339            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
13340                editor.selections.newest::<usize>(cx).head()
13341            });
13342
13343            // Update the selection to match the position of the selection inside
13344            // the rename editor.
13345            let snapshot = self.buffer.read(cx).read(cx);
13346            let rename_range = rename.range.to_offset(&snapshot);
13347            let cursor_in_editor = snapshot
13348                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
13349                .min(rename_range.end);
13350            drop(snapshot);
13351
13352            self.change_selections(None, window, cx, |s| {
13353                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
13354            });
13355        } else {
13356            self.refresh_document_highlights(cx);
13357        }
13358
13359        Some(rename)
13360    }
13361
13362    pub fn pending_rename(&self) -> Option<&RenameState> {
13363        self.pending_rename.as_ref()
13364    }
13365
13366    fn format(
13367        &mut self,
13368        _: &Format,
13369        window: &mut Window,
13370        cx: &mut Context<Self>,
13371    ) -> Option<Task<Result<()>>> {
13372        let project = match &self.project {
13373            Some(project) => project.clone(),
13374            None => return None,
13375        };
13376
13377        Some(self.perform_format(
13378            project,
13379            FormatTrigger::Manual,
13380            FormatTarget::Buffers,
13381            window,
13382            cx,
13383        ))
13384    }
13385
13386    fn format_selections(
13387        &mut self,
13388        _: &FormatSelections,
13389        window: &mut Window,
13390        cx: &mut Context<Self>,
13391    ) -> Option<Task<Result<()>>> {
13392        let project = match &self.project {
13393            Some(project) => project.clone(),
13394            None => return None,
13395        };
13396
13397        let ranges = self
13398            .selections
13399            .all_adjusted(cx)
13400            .into_iter()
13401            .map(|selection| selection.range())
13402            .collect_vec();
13403
13404        Some(self.perform_format(
13405            project,
13406            FormatTrigger::Manual,
13407            FormatTarget::Ranges(ranges),
13408            window,
13409            cx,
13410        ))
13411    }
13412
13413    fn perform_format(
13414        &mut self,
13415        project: Entity<Project>,
13416        trigger: FormatTrigger,
13417        target: FormatTarget,
13418        window: &mut Window,
13419        cx: &mut Context<Self>,
13420    ) -> Task<Result<()>> {
13421        let buffer = self.buffer.clone();
13422        let (buffers, target) = match target {
13423            FormatTarget::Buffers => {
13424                let mut buffers = buffer.read(cx).all_buffers();
13425                if trigger == FormatTrigger::Save {
13426                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
13427                }
13428                (buffers, LspFormatTarget::Buffers)
13429            }
13430            FormatTarget::Ranges(selection_ranges) => {
13431                let multi_buffer = buffer.read(cx);
13432                let snapshot = multi_buffer.read(cx);
13433                let mut buffers = HashSet::default();
13434                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
13435                    BTreeMap::new();
13436                for selection_range in selection_ranges {
13437                    for (buffer, buffer_range, _) in
13438                        snapshot.range_to_buffer_ranges(selection_range)
13439                    {
13440                        let buffer_id = buffer.remote_id();
13441                        let start = buffer.anchor_before(buffer_range.start);
13442                        let end = buffer.anchor_after(buffer_range.end);
13443                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
13444                        buffer_id_to_ranges
13445                            .entry(buffer_id)
13446                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
13447                            .or_insert_with(|| vec![start..end]);
13448                    }
13449                }
13450                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
13451            }
13452        };
13453
13454        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
13455        let format = project.update(cx, |project, cx| {
13456            project.format(buffers, target, true, trigger, cx)
13457        });
13458
13459        cx.spawn_in(window, async move |_, cx| {
13460            let transaction = futures::select_biased! {
13461                transaction = format.log_err().fuse() => transaction,
13462                () = timeout => {
13463                    log::warn!("timed out waiting for formatting");
13464                    None
13465                }
13466            };
13467
13468            buffer
13469                .update(cx, |buffer, cx| {
13470                    if let Some(transaction) = transaction {
13471                        if !buffer.is_singleton() {
13472                            buffer.push_transaction(&transaction.0, cx);
13473                        }
13474                    }
13475                    cx.notify();
13476                })
13477                .ok();
13478
13479            Ok(())
13480        })
13481    }
13482
13483    fn organize_imports(
13484        &mut self,
13485        _: &OrganizeImports,
13486        window: &mut Window,
13487        cx: &mut Context<Self>,
13488    ) -> Option<Task<Result<()>>> {
13489        let project = match &self.project {
13490            Some(project) => project.clone(),
13491            None => return None,
13492        };
13493        Some(self.perform_code_action_kind(
13494            project,
13495            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
13496            window,
13497            cx,
13498        ))
13499    }
13500
13501    fn perform_code_action_kind(
13502        &mut self,
13503        project: Entity<Project>,
13504        kind: CodeActionKind,
13505        window: &mut Window,
13506        cx: &mut Context<Self>,
13507    ) -> Task<Result<()>> {
13508        let buffer = self.buffer.clone();
13509        let buffers = buffer.read(cx).all_buffers();
13510        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
13511        let apply_action = project.update(cx, |project, cx| {
13512            project.apply_code_action_kind(buffers, kind, true, cx)
13513        });
13514        cx.spawn_in(window, async move |_, cx| {
13515            let transaction = futures::select_biased! {
13516                () = timeout => {
13517                    log::warn!("timed out waiting for executing code action");
13518                    None
13519                }
13520                transaction = apply_action.log_err().fuse() => transaction,
13521            };
13522            buffer
13523                .update(cx, |buffer, cx| {
13524                    // check if we need this
13525                    if let Some(transaction) = transaction {
13526                        if !buffer.is_singleton() {
13527                            buffer.push_transaction(&transaction.0, cx);
13528                        }
13529                    }
13530                    cx.notify();
13531                })
13532                .ok();
13533            Ok(())
13534        })
13535    }
13536
13537    fn restart_language_server(
13538        &mut self,
13539        _: &RestartLanguageServer,
13540        _: &mut Window,
13541        cx: &mut Context<Self>,
13542    ) {
13543        if let Some(project) = self.project.clone() {
13544            self.buffer.update(cx, |multi_buffer, cx| {
13545                project.update(cx, |project, cx| {
13546                    project.restart_language_servers_for_buffers(
13547                        multi_buffer.all_buffers().into_iter().collect(),
13548                        cx,
13549                    );
13550                });
13551            })
13552        }
13553    }
13554
13555    fn cancel_language_server_work(
13556        workspace: &mut Workspace,
13557        _: &actions::CancelLanguageServerWork,
13558        _: &mut Window,
13559        cx: &mut Context<Workspace>,
13560    ) {
13561        let project = workspace.project();
13562        let buffers = workspace
13563            .active_item(cx)
13564            .and_then(|item| item.act_as::<Editor>(cx))
13565            .map_or(HashSet::default(), |editor| {
13566                editor.read(cx).buffer.read(cx).all_buffers()
13567            });
13568        project.update(cx, |project, cx| {
13569            project.cancel_language_server_work_for_buffers(buffers, cx);
13570        });
13571    }
13572
13573    fn show_character_palette(
13574        &mut self,
13575        _: &ShowCharacterPalette,
13576        window: &mut Window,
13577        _: &mut Context<Self>,
13578    ) {
13579        window.show_character_palette();
13580    }
13581
13582    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
13583        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
13584            let buffer = self.buffer.read(cx).snapshot(cx);
13585            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
13586            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
13587            let is_valid = buffer
13588                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
13589                .any(|entry| {
13590                    entry.diagnostic.is_primary
13591                        && !entry.range.is_empty()
13592                        && entry.range.start == primary_range_start
13593                        && entry.diagnostic.message == active_diagnostics.primary_message
13594                });
13595
13596            if is_valid != active_diagnostics.is_valid {
13597                active_diagnostics.is_valid = is_valid;
13598                if is_valid {
13599                    let mut new_styles = HashMap::default();
13600                    for (block_id, diagnostic) in &active_diagnostics.blocks {
13601                        new_styles.insert(
13602                            *block_id,
13603                            diagnostic_block_renderer(diagnostic.clone(), None, true),
13604                        );
13605                    }
13606                    self.display_map.update(cx, |display_map, _cx| {
13607                        display_map.replace_blocks(new_styles);
13608                    });
13609                } else {
13610                    self.dismiss_diagnostics(cx);
13611                }
13612            }
13613        }
13614    }
13615
13616    fn activate_diagnostics(
13617        &mut self,
13618        buffer_id: BufferId,
13619        group_id: usize,
13620        window: &mut Window,
13621        cx: &mut Context<Self>,
13622    ) {
13623        self.dismiss_diagnostics(cx);
13624        let snapshot = self.snapshot(window, cx);
13625        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
13626            let buffer = self.buffer.read(cx).snapshot(cx);
13627
13628            let mut primary_range = None;
13629            let mut primary_message = None;
13630            let diagnostic_group = buffer
13631                .diagnostic_group(buffer_id, group_id)
13632                .filter_map(|entry| {
13633                    let start = entry.range.start;
13634                    let end = entry.range.end;
13635                    if snapshot.is_line_folded(MultiBufferRow(start.row))
13636                        && (start.row == end.row
13637                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
13638                    {
13639                        return None;
13640                    }
13641                    if entry.diagnostic.is_primary {
13642                        primary_range = Some(entry.range.clone());
13643                        primary_message = Some(entry.diagnostic.message.clone());
13644                    }
13645                    Some(entry)
13646                })
13647                .collect::<Vec<_>>();
13648            let primary_range = primary_range?;
13649            let primary_message = primary_message?;
13650
13651            let blocks = display_map
13652                .insert_blocks(
13653                    diagnostic_group.iter().map(|entry| {
13654                        let diagnostic = entry.diagnostic.clone();
13655                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
13656                        BlockProperties {
13657                            style: BlockStyle::Fixed,
13658                            placement: BlockPlacement::Below(
13659                                buffer.anchor_after(entry.range.start),
13660                            ),
13661                            height: message_height,
13662                            render: diagnostic_block_renderer(diagnostic, None, true),
13663                            priority: 0,
13664                        }
13665                    }),
13666                    cx,
13667                )
13668                .into_iter()
13669                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
13670                .collect();
13671
13672            Some(ActiveDiagnosticGroup {
13673                primary_range: buffer.anchor_before(primary_range.start)
13674                    ..buffer.anchor_after(primary_range.end),
13675                primary_message,
13676                group_id,
13677                blocks,
13678                is_valid: true,
13679            })
13680        });
13681    }
13682
13683    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
13684        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
13685            self.display_map.update(cx, |display_map, cx| {
13686                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
13687            });
13688            cx.notify();
13689        }
13690    }
13691
13692    /// Disable inline diagnostics rendering for this editor.
13693    pub fn disable_inline_diagnostics(&mut self) {
13694        self.inline_diagnostics_enabled = false;
13695        self.inline_diagnostics_update = Task::ready(());
13696        self.inline_diagnostics.clear();
13697    }
13698
13699    pub fn inline_diagnostics_enabled(&self) -> bool {
13700        self.inline_diagnostics_enabled
13701    }
13702
13703    pub fn show_inline_diagnostics(&self) -> bool {
13704        self.show_inline_diagnostics
13705    }
13706
13707    pub fn toggle_inline_diagnostics(
13708        &mut self,
13709        _: &ToggleInlineDiagnostics,
13710        window: &mut Window,
13711        cx: &mut Context<'_, Editor>,
13712    ) {
13713        self.show_inline_diagnostics = !self.show_inline_diagnostics;
13714        self.refresh_inline_diagnostics(false, window, cx);
13715    }
13716
13717    fn refresh_inline_diagnostics(
13718        &mut self,
13719        debounce: bool,
13720        window: &mut Window,
13721        cx: &mut Context<Self>,
13722    ) {
13723        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
13724            self.inline_diagnostics_update = Task::ready(());
13725            self.inline_diagnostics.clear();
13726            return;
13727        }
13728
13729        let debounce_ms = ProjectSettings::get_global(cx)
13730            .diagnostics
13731            .inline
13732            .update_debounce_ms;
13733        let debounce = if debounce && debounce_ms > 0 {
13734            Some(Duration::from_millis(debounce_ms))
13735        } else {
13736            None
13737        };
13738        self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
13739            if let Some(debounce) = debounce {
13740                cx.background_executor().timer(debounce).await;
13741            }
13742            let Some(snapshot) = editor
13743                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
13744                .ok()
13745            else {
13746                return;
13747            };
13748
13749            let new_inline_diagnostics = cx
13750                .background_spawn(async move {
13751                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
13752                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
13753                        let message = diagnostic_entry
13754                            .diagnostic
13755                            .message
13756                            .split_once('\n')
13757                            .map(|(line, _)| line)
13758                            .map(SharedString::new)
13759                            .unwrap_or_else(|| {
13760                                SharedString::from(diagnostic_entry.diagnostic.message)
13761                            });
13762                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
13763                        let (Ok(i) | Err(i)) = inline_diagnostics
13764                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
13765                        inline_diagnostics.insert(
13766                            i,
13767                            (
13768                                start_anchor,
13769                                InlineDiagnostic {
13770                                    message,
13771                                    group_id: diagnostic_entry.diagnostic.group_id,
13772                                    start: diagnostic_entry.range.start.to_point(&snapshot),
13773                                    is_primary: diagnostic_entry.diagnostic.is_primary,
13774                                    severity: diagnostic_entry.diagnostic.severity,
13775                                },
13776                            ),
13777                        );
13778                    }
13779                    inline_diagnostics
13780                })
13781                .await;
13782
13783            editor
13784                .update(cx, |editor, cx| {
13785                    editor.inline_diagnostics = new_inline_diagnostics;
13786                    cx.notify();
13787                })
13788                .ok();
13789        });
13790    }
13791
13792    pub fn set_selections_from_remote(
13793        &mut self,
13794        selections: Vec<Selection<Anchor>>,
13795        pending_selection: Option<Selection<Anchor>>,
13796        window: &mut Window,
13797        cx: &mut Context<Self>,
13798    ) {
13799        let old_cursor_position = self.selections.newest_anchor().head();
13800        self.selections.change_with(cx, |s| {
13801            s.select_anchors(selections);
13802            if let Some(pending_selection) = pending_selection {
13803                s.set_pending(pending_selection, SelectMode::Character);
13804            } else {
13805                s.clear_pending();
13806            }
13807        });
13808        self.selections_did_change(false, &old_cursor_position, true, window, cx);
13809    }
13810
13811    fn push_to_selection_history(&mut self) {
13812        self.selection_history.push(SelectionHistoryEntry {
13813            selections: self.selections.disjoint_anchors(),
13814            select_next_state: self.select_next_state.clone(),
13815            select_prev_state: self.select_prev_state.clone(),
13816            add_selections_state: self.add_selections_state.clone(),
13817        });
13818    }
13819
13820    pub fn transact(
13821        &mut self,
13822        window: &mut Window,
13823        cx: &mut Context<Self>,
13824        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
13825    ) -> Option<TransactionId> {
13826        self.start_transaction_at(Instant::now(), window, cx);
13827        update(self, window, cx);
13828        self.end_transaction_at(Instant::now(), cx)
13829    }
13830
13831    pub fn start_transaction_at(
13832        &mut self,
13833        now: Instant,
13834        window: &mut Window,
13835        cx: &mut Context<Self>,
13836    ) {
13837        self.end_selection(window, cx);
13838        if let Some(tx_id) = self
13839            .buffer
13840            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
13841        {
13842            self.selection_history
13843                .insert_transaction(tx_id, self.selections.disjoint_anchors());
13844            cx.emit(EditorEvent::TransactionBegun {
13845                transaction_id: tx_id,
13846            })
13847        }
13848    }
13849
13850    pub fn end_transaction_at(
13851        &mut self,
13852        now: Instant,
13853        cx: &mut Context<Self>,
13854    ) -> Option<TransactionId> {
13855        if let Some(transaction_id) = self
13856            .buffer
13857            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
13858        {
13859            if let Some((_, end_selections)) =
13860                self.selection_history.transaction_mut(transaction_id)
13861            {
13862                *end_selections = Some(self.selections.disjoint_anchors());
13863            } else {
13864                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
13865            }
13866
13867            cx.emit(EditorEvent::Edited { transaction_id });
13868            Some(transaction_id)
13869        } else {
13870            None
13871        }
13872    }
13873
13874    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
13875        if self.selection_mark_mode {
13876            self.change_selections(None, window, cx, |s| {
13877                s.move_with(|_, sel| {
13878                    sel.collapse_to(sel.head(), SelectionGoal::None);
13879                });
13880            })
13881        }
13882        self.selection_mark_mode = true;
13883        cx.notify();
13884    }
13885
13886    pub fn swap_selection_ends(
13887        &mut self,
13888        _: &actions::SwapSelectionEnds,
13889        window: &mut Window,
13890        cx: &mut Context<Self>,
13891    ) {
13892        self.change_selections(None, window, cx, |s| {
13893            s.move_with(|_, sel| {
13894                if sel.start != sel.end {
13895                    sel.reversed = !sel.reversed
13896                }
13897            });
13898        });
13899        self.request_autoscroll(Autoscroll::newest(), cx);
13900        cx.notify();
13901    }
13902
13903    pub fn toggle_fold(
13904        &mut self,
13905        _: &actions::ToggleFold,
13906        window: &mut Window,
13907        cx: &mut Context<Self>,
13908    ) {
13909        if self.is_singleton(cx) {
13910            let selection = self.selections.newest::<Point>(cx);
13911
13912            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13913            let range = if selection.is_empty() {
13914                let point = selection.head().to_display_point(&display_map);
13915                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13916                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13917                    .to_point(&display_map);
13918                start..end
13919            } else {
13920                selection.range()
13921            };
13922            if display_map.folds_in_range(range).next().is_some() {
13923                self.unfold_lines(&Default::default(), window, cx)
13924            } else {
13925                self.fold(&Default::default(), window, cx)
13926            }
13927        } else {
13928            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13929            let buffer_ids: HashSet<_> = self
13930                .selections
13931                .disjoint_anchor_ranges()
13932                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13933                .collect();
13934
13935            let should_unfold = buffer_ids
13936                .iter()
13937                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
13938
13939            for buffer_id in buffer_ids {
13940                if should_unfold {
13941                    self.unfold_buffer(buffer_id, cx);
13942                } else {
13943                    self.fold_buffer(buffer_id, cx);
13944                }
13945            }
13946        }
13947    }
13948
13949    pub fn toggle_fold_recursive(
13950        &mut self,
13951        _: &actions::ToggleFoldRecursive,
13952        window: &mut Window,
13953        cx: &mut Context<Self>,
13954    ) {
13955        let selection = self.selections.newest::<Point>(cx);
13956
13957        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13958        let range = if selection.is_empty() {
13959            let point = selection.head().to_display_point(&display_map);
13960            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13961            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13962                .to_point(&display_map);
13963            start..end
13964        } else {
13965            selection.range()
13966        };
13967        if display_map.folds_in_range(range).next().is_some() {
13968            self.unfold_recursive(&Default::default(), window, cx)
13969        } else {
13970            self.fold_recursive(&Default::default(), window, cx)
13971        }
13972    }
13973
13974    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
13975        if self.is_singleton(cx) {
13976            let mut to_fold = Vec::new();
13977            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13978            let selections = self.selections.all_adjusted(cx);
13979
13980            for selection in selections {
13981                let range = selection.range().sorted();
13982                let buffer_start_row = range.start.row;
13983
13984                if range.start.row != range.end.row {
13985                    let mut found = false;
13986                    let mut row = range.start.row;
13987                    while row <= range.end.row {
13988                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
13989                        {
13990                            found = true;
13991                            row = crease.range().end.row + 1;
13992                            to_fold.push(crease);
13993                        } else {
13994                            row += 1
13995                        }
13996                    }
13997                    if found {
13998                        continue;
13999                    }
14000                }
14001
14002                for row in (0..=range.start.row).rev() {
14003                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14004                        if crease.range().end.row >= buffer_start_row {
14005                            to_fold.push(crease);
14006                            if row <= range.start.row {
14007                                break;
14008                            }
14009                        }
14010                    }
14011                }
14012            }
14013
14014            self.fold_creases(to_fold, true, window, cx);
14015        } else {
14016            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14017            let buffer_ids = self
14018                .selections
14019                .disjoint_anchor_ranges()
14020                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14021                .collect::<HashSet<_>>();
14022            for buffer_id in buffer_ids {
14023                self.fold_buffer(buffer_id, cx);
14024            }
14025        }
14026    }
14027
14028    fn fold_at_level(
14029        &mut self,
14030        fold_at: &FoldAtLevel,
14031        window: &mut Window,
14032        cx: &mut Context<Self>,
14033    ) {
14034        if !self.buffer.read(cx).is_singleton() {
14035            return;
14036        }
14037
14038        let fold_at_level = fold_at.0;
14039        let snapshot = self.buffer.read(cx).snapshot(cx);
14040        let mut to_fold = Vec::new();
14041        let mut stack = vec![(0, snapshot.max_row().0, 1)];
14042
14043        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
14044            while start_row < end_row {
14045                match self
14046                    .snapshot(window, cx)
14047                    .crease_for_buffer_row(MultiBufferRow(start_row))
14048                {
14049                    Some(crease) => {
14050                        let nested_start_row = crease.range().start.row + 1;
14051                        let nested_end_row = crease.range().end.row;
14052
14053                        if current_level < fold_at_level {
14054                            stack.push((nested_start_row, nested_end_row, current_level + 1));
14055                        } else if current_level == fold_at_level {
14056                            to_fold.push(crease);
14057                        }
14058
14059                        start_row = nested_end_row + 1;
14060                    }
14061                    None => start_row += 1,
14062                }
14063            }
14064        }
14065
14066        self.fold_creases(to_fold, true, window, cx);
14067    }
14068
14069    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
14070        if self.buffer.read(cx).is_singleton() {
14071            let mut fold_ranges = Vec::new();
14072            let snapshot = self.buffer.read(cx).snapshot(cx);
14073
14074            for row in 0..snapshot.max_row().0 {
14075                if let Some(foldable_range) = self
14076                    .snapshot(window, cx)
14077                    .crease_for_buffer_row(MultiBufferRow(row))
14078                {
14079                    fold_ranges.push(foldable_range);
14080                }
14081            }
14082
14083            self.fold_creases(fold_ranges, true, window, cx);
14084        } else {
14085            self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
14086                editor
14087                    .update_in(cx, |editor, _, cx| {
14088                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14089                            editor.fold_buffer(buffer_id, cx);
14090                        }
14091                    })
14092                    .ok();
14093            });
14094        }
14095    }
14096
14097    pub fn fold_function_bodies(
14098        &mut self,
14099        _: &actions::FoldFunctionBodies,
14100        window: &mut Window,
14101        cx: &mut Context<Self>,
14102    ) {
14103        let snapshot = self.buffer.read(cx).snapshot(cx);
14104
14105        let ranges = snapshot
14106            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
14107            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
14108            .collect::<Vec<_>>();
14109
14110        let creases = ranges
14111            .into_iter()
14112            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
14113            .collect();
14114
14115        self.fold_creases(creases, true, window, cx);
14116    }
14117
14118    pub fn fold_recursive(
14119        &mut self,
14120        _: &actions::FoldRecursive,
14121        window: &mut Window,
14122        cx: &mut Context<Self>,
14123    ) {
14124        let mut to_fold = Vec::new();
14125        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14126        let selections = self.selections.all_adjusted(cx);
14127
14128        for selection in selections {
14129            let range = selection.range().sorted();
14130            let buffer_start_row = range.start.row;
14131
14132            if range.start.row != range.end.row {
14133                let mut found = false;
14134                for row in range.start.row..=range.end.row {
14135                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14136                        found = true;
14137                        to_fold.push(crease);
14138                    }
14139                }
14140                if found {
14141                    continue;
14142                }
14143            }
14144
14145            for row in (0..=range.start.row).rev() {
14146                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14147                    if crease.range().end.row >= buffer_start_row {
14148                        to_fold.push(crease);
14149                    } else {
14150                        break;
14151                    }
14152                }
14153            }
14154        }
14155
14156        self.fold_creases(to_fold, true, window, cx);
14157    }
14158
14159    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
14160        let buffer_row = fold_at.buffer_row;
14161        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14162
14163        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
14164            let autoscroll = self
14165                .selections
14166                .all::<Point>(cx)
14167                .iter()
14168                .any(|selection| crease.range().overlaps(&selection.range()));
14169
14170            self.fold_creases(vec![crease], autoscroll, window, cx);
14171        }
14172    }
14173
14174    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
14175        if self.is_singleton(cx) {
14176            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14177            let buffer = &display_map.buffer_snapshot;
14178            let selections = self.selections.all::<Point>(cx);
14179            let ranges = selections
14180                .iter()
14181                .map(|s| {
14182                    let range = s.display_range(&display_map).sorted();
14183                    let mut start = range.start.to_point(&display_map);
14184                    let mut end = range.end.to_point(&display_map);
14185                    start.column = 0;
14186                    end.column = buffer.line_len(MultiBufferRow(end.row));
14187                    start..end
14188                })
14189                .collect::<Vec<_>>();
14190
14191            self.unfold_ranges(&ranges, true, true, cx);
14192        } else {
14193            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14194            let buffer_ids = self
14195                .selections
14196                .disjoint_anchor_ranges()
14197                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14198                .collect::<HashSet<_>>();
14199            for buffer_id in buffer_ids {
14200                self.unfold_buffer(buffer_id, cx);
14201            }
14202        }
14203    }
14204
14205    pub fn unfold_recursive(
14206        &mut self,
14207        _: &UnfoldRecursive,
14208        _window: &mut Window,
14209        cx: &mut Context<Self>,
14210    ) {
14211        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14212        let selections = self.selections.all::<Point>(cx);
14213        let ranges = selections
14214            .iter()
14215            .map(|s| {
14216                let mut range = s.display_range(&display_map).sorted();
14217                *range.start.column_mut() = 0;
14218                *range.end.column_mut() = display_map.line_len(range.end.row());
14219                let start = range.start.to_point(&display_map);
14220                let end = range.end.to_point(&display_map);
14221                start..end
14222            })
14223            .collect::<Vec<_>>();
14224
14225        self.unfold_ranges(&ranges, true, true, cx);
14226    }
14227
14228    pub fn unfold_at(
14229        &mut self,
14230        unfold_at: &UnfoldAt,
14231        _window: &mut Window,
14232        cx: &mut Context<Self>,
14233    ) {
14234        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14235
14236        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
14237            ..Point::new(
14238                unfold_at.buffer_row.0,
14239                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
14240            );
14241
14242        let autoscroll = self
14243            .selections
14244            .all::<Point>(cx)
14245            .iter()
14246            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
14247
14248        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
14249    }
14250
14251    pub fn unfold_all(
14252        &mut self,
14253        _: &actions::UnfoldAll,
14254        _window: &mut Window,
14255        cx: &mut Context<Self>,
14256    ) {
14257        if self.buffer.read(cx).is_singleton() {
14258            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14259            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
14260        } else {
14261            self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
14262                editor
14263                    .update(cx, |editor, cx| {
14264                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14265                            editor.unfold_buffer(buffer_id, cx);
14266                        }
14267                    })
14268                    .ok();
14269            });
14270        }
14271    }
14272
14273    pub fn fold_selected_ranges(
14274        &mut self,
14275        _: &FoldSelectedRanges,
14276        window: &mut Window,
14277        cx: &mut Context<Self>,
14278    ) {
14279        let selections = self.selections.all::<Point>(cx);
14280        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14281        let line_mode = self.selections.line_mode;
14282        let ranges = selections
14283            .into_iter()
14284            .map(|s| {
14285                if line_mode {
14286                    let start = Point::new(s.start.row, 0);
14287                    let end = Point::new(
14288                        s.end.row,
14289                        display_map
14290                            .buffer_snapshot
14291                            .line_len(MultiBufferRow(s.end.row)),
14292                    );
14293                    Crease::simple(start..end, display_map.fold_placeholder.clone())
14294                } else {
14295                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
14296                }
14297            })
14298            .collect::<Vec<_>>();
14299        self.fold_creases(ranges, true, window, cx);
14300    }
14301
14302    pub fn fold_ranges<T: ToOffset + Clone>(
14303        &mut self,
14304        ranges: Vec<Range<T>>,
14305        auto_scroll: bool,
14306        window: &mut Window,
14307        cx: &mut Context<Self>,
14308    ) {
14309        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14310        let ranges = ranges
14311            .into_iter()
14312            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
14313            .collect::<Vec<_>>();
14314        self.fold_creases(ranges, auto_scroll, window, cx);
14315    }
14316
14317    pub fn fold_creases<T: ToOffset + Clone>(
14318        &mut self,
14319        creases: Vec<Crease<T>>,
14320        auto_scroll: bool,
14321        window: &mut Window,
14322        cx: &mut Context<Self>,
14323    ) {
14324        if creases.is_empty() {
14325            return;
14326        }
14327
14328        let mut buffers_affected = HashSet::default();
14329        let multi_buffer = self.buffer().read(cx);
14330        for crease in &creases {
14331            if let Some((_, buffer, _)) =
14332                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
14333            {
14334                buffers_affected.insert(buffer.read(cx).remote_id());
14335            };
14336        }
14337
14338        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
14339
14340        if auto_scroll {
14341            self.request_autoscroll(Autoscroll::fit(), cx);
14342        }
14343
14344        cx.notify();
14345
14346        if let Some(active_diagnostics) = self.active_diagnostics.take() {
14347            // Clear diagnostics block when folding a range that contains it.
14348            let snapshot = self.snapshot(window, cx);
14349            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
14350                drop(snapshot);
14351                self.active_diagnostics = Some(active_diagnostics);
14352                self.dismiss_diagnostics(cx);
14353            } else {
14354                self.active_diagnostics = Some(active_diagnostics);
14355            }
14356        }
14357
14358        self.scrollbar_marker_state.dirty = true;
14359    }
14360
14361    /// Removes any folds whose ranges intersect any of the given ranges.
14362    pub fn unfold_ranges<T: ToOffset + Clone>(
14363        &mut self,
14364        ranges: &[Range<T>],
14365        inclusive: bool,
14366        auto_scroll: bool,
14367        cx: &mut Context<Self>,
14368    ) {
14369        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
14370            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
14371        });
14372    }
14373
14374    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
14375        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
14376            return;
14377        }
14378        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
14379        self.display_map.update(cx, |display_map, cx| {
14380            display_map.fold_buffers([buffer_id], cx)
14381        });
14382        cx.emit(EditorEvent::BufferFoldToggled {
14383            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
14384            folded: true,
14385        });
14386        cx.notify();
14387    }
14388
14389    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
14390        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
14391            return;
14392        }
14393        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
14394        self.display_map.update(cx, |display_map, cx| {
14395            display_map.unfold_buffers([buffer_id], cx);
14396        });
14397        cx.emit(EditorEvent::BufferFoldToggled {
14398            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
14399            folded: false,
14400        });
14401        cx.notify();
14402    }
14403
14404    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
14405        self.display_map.read(cx).is_buffer_folded(buffer)
14406    }
14407
14408    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
14409        self.display_map.read(cx).folded_buffers()
14410    }
14411
14412    /// Removes any folds with the given ranges.
14413    pub fn remove_folds_with_type<T: ToOffset + Clone>(
14414        &mut self,
14415        ranges: &[Range<T>],
14416        type_id: TypeId,
14417        auto_scroll: bool,
14418        cx: &mut Context<Self>,
14419    ) {
14420        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
14421            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
14422        });
14423    }
14424
14425    fn remove_folds_with<T: ToOffset + Clone>(
14426        &mut self,
14427        ranges: &[Range<T>],
14428        auto_scroll: bool,
14429        cx: &mut Context<Self>,
14430        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
14431    ) {
14432        if ranges.is_empty() {
14433            return;
14434        }
14435
14436        let mut buffers_affected = HashSet::default();
14437        let multi_buffer = self.buffer().read(cx);
14438        for range in ranges {
14439            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
14440                buffers_affected.insert(buffer.read(cx).remote_id());
14441            };
14442        }
14443
14444        self.display_map.update(cx, update);
14445
14446        if auto_scroll {
14447            self.request_autoscroll(Autoscroll::fit(), cx);
14448        }
14449
14450        cx.notify();
14451        self.scrollbar_marker_state.dirty = true;
14452        self.active_indent_guides_state.dirty = true;
14453    }
14454
14455    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
14456        self.display_map.read(cx).fold_placeholder.clone()
14457    }
14458
14459    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
14460        self.buffer.update(cx, |buffer, cx| {
14461            buffer.set_all_diff_hunks_expanded(cx);
14462        });
14463    }
14464
14465    pub fn expand_all_diff_hunks(
14466        &mut self,
14467        _: &ExpandAllDiffHunks,
14468        _window: &mut Window,
14469        cx: &mut Context<Self>,
14470    ) {
14471        self.buffer.update(cx, |buffer, cx| {
14472            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
14473        });
14474    }
14475
14476    pub fn toggle_selected_diff_hunks(
14477        &mut self,
14478        _: &ToggleSelectedDiffHunks,
14479        _window: &mut Window,
14480        cx: &mut Context<Self>,
14481    ) {
14482        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
14483        self.toggle_diff_hunks_in_ranges(ranges, cx);
14484    }
14485
14486    pub fn diff_hunks_in_ranges<'a>(
14487        &'a self,
14488        ranges: &'a [Range<Anchor>],
14489        buffer: &'a MultiBufferSnapshot,
14490    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
14491        ranges.iter().flat_map(move |range| {
14492            let end_excerpt_id = range.end.excerpt_id;
14493            let range = range.to_point(buffer);
14494            let mut peek_end = range.end;
14495            if range.end.row < buffer.max_row().0 {
14496                peek_end = Point::new(range.end.row + 1, 0);
14497            }
14498            buffer
14499                .diff_hunks_in_range(range.start..peek_end)
14500                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
14501        })
14502    }
14503
14504    pub fn has_stageable_diff_hunks_in_ranges(
14505        &self,
14506        ranges: &[Range<Anchor>],
14507        snapshot: &MultiBufferSnapshot,
14508    ) -> bool {
14509        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
14510        hunks.any(|hunk| hunk.status().has_secondary_hunk())
14511    }
14512
14513    pub fn toggle_staged_selected_diff_hunks(
14514        &mut self,
14515        _: &::git::ToggleStaged,
14516        _: &mut Window,
14517        cx: &mut Context<Self>,
14518    ) {
14519        let snapshot = self.buffer.read(cx).snapshot(cx);
14520        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
14521        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
14522        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
14523    }
14524
14525    pub fn stage_and_next(
14526        &mut self,
14527        _: &::git::StageAndNext,
14528        window: &mut Window,
14529        cx: &mut Context<Self>,
14530    ) {
14531        self.do_stage_or_unstage_and_next(true, window, cx);
14532    }
14533
14534    pub fn unstage_and_next(
14535        &mut self,
14536        _: &::git::UnstageAndNext,
14537        window: &mut Window,
14538        cx: &mut Context<Self>,
14539    ) {
14540        self.do_stage_or_unstage_and_next(false, window, cx);
14541    }
14542
14543    pub fn stage_or_unstage_diff_hunks(
14544        &mut self,
14545        stage: bool,
14546        ranges: Vec<Range<Anchor>>,
14547        cx: &mut Context<Self>,
14548    ) {
14549        let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
14550        cx.spawn(async move |this, cx| {
14551            task.await?;
14552            this.update(cx, |this, cx| {
14553                let snapshot = this.buffer.read(cx).snapshot(cx);
14554                let chunk_by = this
14555                    .diff_hunks_in_ranges(&ranges, &snapshot)
14556                    .chunk_by(|hunk| hunk.buffer_id);
14557                for (buffer_id, hunks) in &chunk_by {
14558                    this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
14559                }
14560            })
14561        })
14562        .detach_and_log_err(cx);
14563    }
14564
14565    fn save_buffers_for_ranges_if_needed(
14566        &mut self,
14567        ranges: &[Range<Anchor>],
14568        cx: &mut Context<'_, Editor>,
14569    ) -> Task<Result<()>> {
14570        let multibuffer = self.buffer.read(cx);
14571        let snapshot = multibuffer.read(cx);
14572        let buffer_ids: HashSet<_> = ranges
14573            .iter()
14574            .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
14575            .collect();
14576        drop(snapshot);
14577
14578        let mut buffers = HashSet::default();
14579        for buffer_id in buffer_ids {
14580            if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
14581                let buffer = buffer_entity.read(cx);
14582                if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
14583                {
14584                    buffers.insert(buffer_entity);
14585                }
14586            }
14587        }
14588
14589        if let Some(project) = &self.project {
14590            project.update(cx, |project, cx| project.save_buffers(buffers, cx))
14591        } else {
14592            Task::ready(Ok(()))
14593        }
14594    }
14595
14596    fn do_stage_or_unstage_and_next(
14597        &mut self,
14598        stage: bool,
14599        window: &mut Window,
14600        cx: &mut Context<Self>,
14601    ) {
14602        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
14603
14604        if ranges.iter().any(|range| range.start != range.end) {
14605            self.stage_or_unstage_diff_hunks(stage, ranges, cx);
14606            return;
14607        }
14608
14609        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
14610        let snapshot = self.snapshot(window, cx);
14611        let position = self.selections.newest::<Point>(cx).head();
14612        let mut row = snapshot
14613            .buffer_snapshot
14614            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
14615            .find(|hunk| hunk.row_range.start.0 > position.row)
14616            .map(|hunk| hunk.row_range.start);
14617
14618        let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
14619        // Outside of the project diff editor, wrap around to the beginning.
14620        if !all_diff_hunks_expanded {
14621            row = row.or_else(|| {
14622                snapshot
14623                    .buffer_snapshot
14624                    .diff_hunks_in_range(Point::zero()..position)
14625                    .find(|hunk| hunk.row_range.end.0 < position.row)
14626                    .map(|hunk| hunk.row_range.start)
14627            });
14628        }
14629
14630        if let Some(row) = row {
14631            let destination = Point::new(row.0, 0);
14632            let autoscroll = Autoscroll::center();
14633
14634            self.unfold_ranges(&[destination..destination], false, false, cx);
14635            self.change_selections(Some(autoscroll), window, cx, |s| {
14636                s.select_ranges([destination..destination]);
14637            });
14638        }
14639    }
14640
14641    fn do_stage_or_unstage(
14642        &self,
14643        stage: bool,
14644        buffer_id: BufferId,
14645        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
14646        cx: &mut App,
14647    ) -> Option<()> {
14648        let project = self.project.as_ref()?;
14649        let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
14650        let diff = self.buffer.read(cx).diff_for(buffer_id)?;
14651        let buffer_snapshot = buffer.read(cx).snapshot();
14652        let file_exists = buffer_snapshot
14653            .file()
14654            .is_some_and(|file| file.disk_state().exists());
14655        diff.update(cx, |diff, cx| {
14656            diff.stage_or_unstage_hunks(
14657                stage,
14658                &hunks
14659                    .map(|hunk| buffer_diff::DiffHunk {
14660                        buffer_range: hunk.buffer_range,
14661                        diff_base_byte_range: hunk.diff_base_byte_range,
14662                        secondary_status: hunk.secondary_status,
14663                        range: Point::zero()..Point::zero(), // unused
14664                    })
14665                    .collect::<Vec<_>>(),
14666                &buffer_snapshot,
14667                file_exists,
14668                cx,
14669            )
14670        });
14671        None
14672    }
14673
14674    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
14675        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
14676        self.buffer
14677            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
14678    }
14679
14680    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
14681        self.buffer.update(cx, |buffer, cx| {
14682            let ranges = vec![Anchor::min()..Anchor::max()];
14683            if !buffer.all_diff_hunks_expanded()
14684                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
14685            {
14686                buffer.collapse_diff_hunks(ranges, cx);
14687                true
14688            } else {
14689                false
14690            }
14691        })
14692    }
14693
14694    fn toggle_diff_hunks_in_ranges(
14695        &mut self,
14696        ranges: Vec<Range<Anchor>>,
14697        cx: &mut Context<'_, Editor>,
14698    ) {
14699        self.buffer.update(cx, |buffer, cx| {
14700            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
14701            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
14702        })
14703    }
14704
14705    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
14706        self.buffer.update(cx, |buffer, cx| {
14707            let snapshot = buffer.snapshot(cx);
14708            let excerpt_id = range.end.excerpt_id;
14709            let point_range = range.to_point(&snapshot);
14710            let expand = !buffer.single_hunk_is_expanded(range, cx);
14711            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
14712        })
14713    }
14714
14715    pub(crate) fn apply_all_diff_hunks(
14716        &mut self,
14717        _: &ApplyAllDiffHunks,
14718        window: &mut Window,
14719        cx: &mut Context<Self>,
14720    ) {
14721        let buffers = self.buffer.read(cx).all_buffers();
14722        for branch_buffer in buffers {
14723            branch_buffer.update(cx, |branch_buffer, cx| {
14724                branch_buffer.merge_into_base(Vec::new(), cx);
14725            });
14726        }
14727
14728        if let Some(project) = self.project.clone() {
14729            self.save(true, project, window, cx).detach_and_log_err(cx);
14730        }
14731    }
14732
14733    pub(crate) fn apply_selected_diff_hunks(
14734        &mut self,
14735        _: &ApplyDiffHunk,
14736        window: &mut Window,
14737        cx: &mut Context<Self>,
14738    ) {
14739        let snapshot = self.snapshot(window, cx);
14740        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
14741        let mut ranges_by_buffer = HashMap::default();
14742        self.transact(window, cx, |editor, _window, cx| {
14743            for hunk in hunks {
14744                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
14745                    ranges_by_buffer
14746                        .entry(buffer.clone())
14747                        .or_insert_with(Vec::new)
14748                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
14749                }
14750            }
14751
14752            for (buffer, ranges) in ranges_by_buffer {
14753                buffer.update(cx, |buffer, cx| {
14754                    buffer.merge_into_base(ranges, cx);
14755                });
14756            }
14757        });
14758
14759        if let Some(project) = self.project.clone() {
14760            self.save(true, project, window, cx).detach_and_log_err(cx);
14761        }
14762    }
14763
14764    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
14765        if hovered != self.gutter_hovered {
14766            self.gutter_hovered = hovered;
14767            cx.notify();
14768        }
14769    }
14770
14771    pub fn insert_blocks(
14772        &mut self,
14773        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
14774        autoscroll: Option<Autoscroll>,
14775        cx: &mut Context<Self>,
14776    ) -> Vec<CustomBlockId> {
14777        let blocks = self
14778            .display_map
14779            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
14780        if let Some(autoscroll) = autoscroll {
14781            self.request_autoscroll(autoscroll, cx);
14782        }
14783        cx.notify();
14784        blocks
14785    }
14786
14787    pub fn resize_blocks(
14788        &mut self,
14789        heights: HashMap<CustomBlockId, u32>,
14790        autoscroll: Option<Autoscroll>,
14791        cx: &mut Context<Self>,
14792    ) {
14793        self.display_map
14794            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
14795        if let Some(autoscroll) = autoscroll {
14796            self.request_autoscroll(autoscroll, cx);
14797        }
14798        cx.notify();
14799    }
14800
14801    pub fn replace_blocks(
14802        &mut self,
14803        renderers: HashMap<CustomBlockId, RenderBlock>,
14804        autoscroll: Option<Autoscroll>,
14805        cx: &mut Context<Self>,
14806    ) {
14807        self.display_map
14808            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
14809        if let Some(autoscroll) = autoscroll {
14810            self.request_autoscroll(autoscroll, cx);
14811        }
14812        cx.notify();
14813    }
14814
14815    pub fn remove_blocks(
14816        &mut self,
14817        block_ids: HashSet<CustomBlockId>,
14818        autoscroll: Option<Autoscroll>,
14819        cx: &mut Context<Self>,
14820    ) {
14821        self.display_map.update(cx, |display_map, cx| {
14822            display_map.remove_blocks(block_ids, cx)
14823        });
14824        if let Some(autoscroll) = autoscroll {
14825            self.request_autoscroll(autoscroll, cx);
14826        }
14827        cx.notify();
14828    }
14829
14830    pub fn row_for_block(
14831        &self,
14832        block_id: CustomBlockId,
14833        cx: &mut Context<Self>,
14834    ) -> Option<DisplayRow> {
14835        self.display_map
14836            .update(cx, |map, cx| map.row_for_block(block_id, cx))
14837    }
14838
14839    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
14840        self.focused_block = Some(focused_block);
14841    }
14842
14843    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
14844        self.focused_block.take()
14845    }
14846
14847    pub fn insert_creases(
14848        &mut self,
14849        creases: impl IntoIterator<Item = Crease<Anchor>>,
14850        cx: &mut Context<Self>,
14851    ) -> Vec<CreaseId> {
14852        self.display_map
14853            .update(cx, |map, cx| map.insert_creases(creases, cx))
14854    }
14855
14856    pub fn remove_creases(
14857        &mut self,
14858        ids: impl IntoIterator<Item = CreaseId>,
14859        cx: &mut Context<Self>,
14860    ) {
14861        self.display_map
14862            .update(cx, |map, cx| map.remove_creases(ids, cx));
14863    }
14864
14865    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
14866        self.display_map
14867            .update(cx, |map, cx| map.snapshot(cx))
14868            .longest_row()
14869    }
14870
14871    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
14872        self.display_map
14873            .update(cx, |map, cx| map.snapshot(cx))
14874            .max_point()
14875    }
14876
14877    pub fn text(&self, cx: &App) -> String {
14878        self.buffer.read(cx).read(cx).text()
14879    }
14880
14881    pub fn is_empty(&self, cx: &App) -> bool {
14882        self.buffer.read(cx).read(cx).is_empty()
14883    }
14884
14885    pub fn text_option(&self, cx: &App) -> Option<String> {
14886        let text = self.text(cx);
14887        let text = text.trim();
14888
14889        if text.is_empty() {
14890            return None;
14891        }
14892
14893        Some(text.to_string())
14894    }
14895
14896    pub fn set_text(
14897        &mut self,
14898        text: impl Into<Arc<str>>,
14899        window: &mut Window,
14900        cx: &mut Context<Self>,
14901    ) {
14902        self.transact(window, cx, |this, _, cx| {
14903            this.buffer
14904                .read(cx)
14905                .as_singleton()
14906                .expect("you can only call set_text on editors for singleton buffers")
14907                .update(cx, |buffer, cx| buffer.set_text(text, cx));
14908        });
14909    }
14910
14911    pub fn display_text(&self, cx: &mut App) -> String {
14912        self.display_map
14913            .update(cx, |map, cx| map.snapshot(cx))
14914            .text()
14915    }
14916
14917    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
14918        let mut wrap_guides = smallvec::smallvec![];
14919
14920        if self.show_wrap_guides == Some(false) {
14921            return wrap_guides;
14922        }
14923
14924        let settings = self.buffer.read(cx).language_settings(cx);
14925        if settings.show_wrap_guides {
14926            match self.soft_wrap_mode(cx) {
14927                SoftWrap::Column(soft_wrap) => {
14928                    wrap_guides.push((soft_wrap as usize, true));
14929                }
14930                SoftWrap::Bounded(soft_wrap) => {
14931                    wrap_guides.push((soft_wrap as usize, true));
14932                }
14933                SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
14934            }
14935            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
14936        }
14937
14938        wrap_guides
14939    }
14940
14941    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
14942        let settings = self.buffer.read(cx).language_settings(cx);
14943        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
14944        match mode {
14945            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
14946                SoftWrap::None
14947            }
14948            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
14949            language_settings::SoftWrap::PreferredLineLength => {
14950                SoftWrap::Column(settings.preferred_line_length)
14951            }
14952            language_settings::SoftWrap::Bounded => {
14953                SoftWrap::Bounded(settings.preferred_line_length)
14954            }
14955        }
14956    }
14957
14958    pub fn set_soft_wrap_mode(
14959        &mut self,
14960        mode: language_settings::SoftWrap,
14961
14962        cx: &mut Context<Self>,
14963    ) {
14964        self.soft_wrap_mode_override = Some(mode);
14965        cx.notify();
14966    }
14967
14968    pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
14969        self.hard_wrap = hard_wrap;
14970        cx.notify();
14971    }
14972
14973    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
14974        self.text_style_refinement = Some(style);
14975    }
14976
14977    /// called by the Element so we know what style we were most recently rendered with.
14978    pub(crate) fn set_style(
14979        &mut self,
14980        style: EditorStyle,
14981        window: &mut Window,
14982        cx: &mut Context<Self>,
14983    ) {
14984        let rem_size = window.rem_size();
14985        self.display_map.update(cx, |map, cx| {
14986            map.set_font(
14987                style.text.font(),
14988                style.text.font_size.to_pixels(rem_size),
14989                cx,
14990            )
14991        });
14992        self.style = Some(style);
14993    }
14994
14995    pub fn style(&self) -> Option<&EditorStyle> {
14996        self.style.as_ref()
14997    }
14998
14999    // Called by the element. This method is not designed to be called outside of the editor
15000    // element's layout code because it does not notify when rewrapping is computed synchronously.
15001    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
15002        self.display_map
15003            .update(cx, |map, cx| map.set_wrap_width(width, cx))
15004    }
15005
15006    pub fn set_soft_wrap(&mut self) {
15007        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
15008    }
15009
15010    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
15011        if self.soft_wrap_mode_override.is_some() {
15012            self.soft_wrap_mode_override.take();
15013        } else {
15014            let soft_wrap = match self.soft_wrap_mode(cx) {
15015                SoftWrap::GitDiff => return,
15016                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
15017                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
15018                    language_settings::SoftWrap::None
15019                }
15020            };
15021            self.soft_wrap_mode_override = Some(soft_wrap);
15022        }
15023        cx.notify();
15024    }
15025
15026    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
15027        let Some(workspace) = self.workspace() else {
15028            return;
15029        };
15030        let fs = workspace.read(cx).app_state().fs.clone();
15031        let current_show = TabBarSettings::get_global(cx).show;
15032        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
15033            setting.show = Some(!current_show);
15034        });
15035    }
15036
15037    pub fn toggle_indent_guides(
15038        &mut self,
15039        _: &ToggleIndentGuides,
15040        _: &mut Window,
15041        cx: &mut Context<Self>,
15042    ) {
15043        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
15044            self.buffer
15045                .read(cx)
15046                .language_settings(cx)
15047                .indent_guides
15048                .enabled
15049        });
15050        self.show_indent_guides = Some(!currently_enabled);
15051        cx.notify();
15052    }
15053
15054    fn should_show_indent_guides(&self) -> Option<bool> {
15055        self.show_indent_guides
15056    }
15057
15058    pub fn toggle_line_numbers(
15059        &mut self,
15060        _: &ToggleLineNumbers,
15061        _: &mut Window,
15062        cx: &mut Context<Self>,
15063    ) {
15064        let mut editor_settings = EditorSettings::get_global(cx).clone();
15065        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
15066        EditorSettings::override_global(editor_settings, cx);
15067    }
15068
15069    pub fn line_numbers_enabled(&self, cx: &App) -> bool {
15070        if let Some(show_line_numbers) = self.show_line_numbers {
15071            return show_line_numbers;
15072        }
15073        EditorSettings::get_global(cx).gutter.line_numbers
15074    }
15075
15076    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
15077        self.use_relative_line_numbers
15078            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
15079    }
15080
15081    pub fn toggle_relative_line_numbers(
15082        &mut self,
15083        _: &ToggleRelativeLineNumbers,
15084        _: &mut Window,
15085        cx: &mut Context<Self>,
15086    ) {
15087        let is_relative = self.should_use_relative_line_numbers(cx);
15088        self.set_relative_line_number(Some(!is_relative), cx)
15089    }
15090
15091    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
15092        self.use_relative_line_numbers = is_relative;
15093        cx.notify();
15094    }
15095
15096    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
15097        self.show_gutter = show_gutter;
15098        cx.notify();
15099    }
15100
15101    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
15102        self.show_scrollbars = show_scrollbars;
15103        cx.notify();
15104    }
15105
15106    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
15107        self.show_line_numbers = Some(show_line_numbers);
15108        cx.notify();
15109    }
15110
15111    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
15112        self.show_git_diff_gutter = Some(show_git_diff_gutter);
15113        cx.notify();
15114    }
15115
15116    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
15117        self.show_code_actions = Some(show_code_actions);
15118        cx.notify();
15119    }
15120
15121    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
15122        self.show_runnables = Some(show_runnables);
15123        cx.notify();
15124    }
15125
15126    pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
15127        self.show_breakpoints = Some(show_breakpoints);
15128        cx.notify();
15129    }
15130
15131    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
15132        if self.display_map.read(cx).masked != masked {
15133            self.display_map.update(cx, |map, _| map.masked = masked);
15134        }
15135        cx.notify()
15136    }
15137
15138    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
15139        self.show_wrap_guides = Some(show_wrap_guides);
15140        cx.notify();
15141    }
15142
15143    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
15144        self.show_indent_guides = Some(show_indent_guides);
15145        cx.notify();
15146    }
15147
15148    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
15149        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
15150            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
15151                if let Some(dir) = file.abs_path(cx).parent() {
15152                    return Some(dir.to_owned());
15153                }
15154            }
15155
15156            if let Some(project_path) = buffer.read(cx).project_path(cx) {
15157                return Some(project_path.path.to_path_buf());
15158            }
15159        }
15160
15161        None
15162    }
15163
15164    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
15165        self.active_excerpt(cx)?
15166            .1
15167            .read(cx)
15168            .file()
15169            .and_then(|f| f.as_local())
15170    }
15171
15172    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15173        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15174            let buffer = buffer.read(cx);
15175            if let Some(project_path) = buffer.project_path(cx) {
15176                let project = self.project.as_ref()?.read(cx);
15177                project.absolute_path(&project_path, cx)
15178            } else {
15179                buffer
15180                    .file()
15181                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
15182            }
15183        })
15184    }
15185
15186    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15187        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15188            let project_path = buffer.read(cx).project_path(cx)?;
15189            let project = self.project.as_ref()?.read(cx);
15190            let entry = project.entry_for_path(&project_path, cx)?;
15191            let path = entry.path.to_path_buf();
15192            Some(path)
15193        })
15194    }
15195
15196    pub fn reveal_in_finder(
15197        &mut self,
15198        _: &RevealInFileManager,
15199        _window: &mut Window,
15200        cx: &mut Context<Self>,
15201    ) {
15202        if let Some(target) = self.target_file(cx) {
15203            cx.reveal_path(&target.abs_path(cx));
15204        }
15205    }
15206
15207    pub fn copy_path(
15208        &mut self,
15209        _: &zed_actions::workspace::CopyPath,
15210        _window: &mut Window,
15211        cx: &mut Context<Self>,
15212    ) {
15213        if let Some(path) = self.target_file_abs_path(cx) {
15214            if let Some(path) = path.to_str() {
15215                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
15216            }
15217        }
15218    }
15219
15220    pub fn copy_relative_path(
15221        &mut self,
15222        _: &zed_actions::workspace::CopyRelativePath,
15223        _window: &mut Window,
15224        cx: &mut Context<Self>,
15225    ) {
15226        if let Some(path) = self.target_file_path(cx) {
15227            if let Some(path) = path.to_str() {
15228                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
15229            }
15230        }
15231    }
15232
15233    pub fn project_path(&self, cx: &mut Context<Self>) -> Option<ProjectPath> {
15234        if let Some(buffer) = self.buffer.read(cx).as_singleton() {
15235            buffer.read_with(cx, |buffer, cx| buffer.project_path(cx))
15236        } else {
15237            None
15238        }
15239    }
15240
15241    pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15242        let _ = maybe!({
15243            let breakpoint_store = self.breakpoint_store.as_ref()?;
15244
15245            let Some((_, _, active_position)) =
15246                breakpoint_store.read(cx).active_position().cloned()
15247            else {
15248                self.clear_row_highlights::<DebugCurrentRowHighlight>();
15249                return None;
15250            };
15251
15252            let snapshot = self
15253                .project
15254                .as_ref()?
15255                .read(cx)
15256                .buffer_for_id(active_position.buffer_id?, cx)?
15257                .read(cx)
15258                .snapshot();
15259
15260            for (id, ExcerptRange { context, .. }) in self
15261                .buffer
15262                .read(cx)
15263                .excerpts_for_buffer(active_position.buffer_id?, cx)
15264            {
15265                if context.start.cmp(&active_position, &snapshot).is_ge()
15266                    || context.end.cmp(&active_position, &snapshot).is_lt()
15267                {
15268                    continue;
15269                }
15270                let snapshot = self.buffer.read(cx).snapshot(cx);
15271                let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
15272
15273                self.clear_row_highlights::<DebugCurrentRowHighlight>();
15274                self.go_to_line::<DebugCurrentRowHighlight>(
15275                    multibuffer_anchor,
15276                    Some(cx.theme().colors().editor_debugger_active_line_background),
15277                    window,
15278                    cx,
15279                );
15280
15281                cx.notify();
15282            }
15283
15284            Some(())
15285        });
15286    }
15287
15288    pub fn copy_file_name_without_extension(
15289        &mut self,
15290        _: &CopyFileNameWithoutExtension,
15291        _: &mut Window,
15292        cx: &mut Context<Self>,
15293    ) {
15294        if let Some(file) = self.target_file(cx) {
15295            if let Some(file_stem) = file.path().file_stem() {
15296                if let Some(name) = file_stem.to_str() {
15297                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
15298                }
15299            }
15300        }
15301    }
15302
15303    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
15304        if let Some(file) = self.target_file(cx) {
15305            if let Some(file_name) = file.path().file_name() {
15306                if let Some(name) = file_name.to_str() {
15307                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
15308                }
15309            }
15310        }
15311    }
15312
15313    pub fn toggle_git_blame(
15314        &mut self,
15315        _: &::git::Blame,
15316        window: &mut Window,
15317        cx: &mut Context<Self>,
15318    ) {
15319        self.show_git_blame_gutter = !self.show_git_blame_gutter;
15320
15321        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
15322            self.start_git_blame(true, window, cx);
15323        }
15324
15325        cx.notify();
15326    }
15327
15328    pub fn toggle_git_blame_inline(
15329        &mut self,
15330        _: &ToggleGitBlameInline,
15331        window: &mut Window,
15332        cx: &mut Context<Self>,
15333    ) {
15334        self.toggle_git_blame_inline_internal(true, window, cx);
15335        cx.notify();
15336    }
15337
15338    pub fn git_blame_inline_enabled(&self) -> bool {
15339        self.git_blame_inline_enabled
15340    }
15341
15342    pub fn toggle_selection_menu(
15343        &mut self,
15344        _: &ToggleSelectionMenu,
15345        _: &mut Window,
15346        cx: &mut Context<Self>,
15347    ) {
15348        self.show_selection_menu = self
15349            .show_selection_menu
15350            .map(|show_selections_menu| !show_selections_menu)
15351            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
15352
15353        cx.notify();
15354    }
15355
15356    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
15357        self.show_selection_menu
15358            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
15359    }
15360
15361    fn start_git_blame(
15362        &mut self,
15363        user_triggered: bool,
15364        window: &mut Window,
15365        cx: &mut Context<Self>,
15366    ) {
15367        if let Some(project) = self.project.as_ref() {
15368            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
15369                return;
15370            };
15371
15372            if buffer.read(cx).file().is_none() {
15373                return;
15374            }
15375
15376            let focused = self.focus_handle(cx).contains_focused(window, cx);
15377
15378            let project = project.clone();
15379            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
15380            self.blame_subscription =
15381                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
15382            self.blame = Some(blame);
15383        }
15384    }
15385
15386    fn toggle_git_blame_inline_internal(
15387        &mut self,
15388        user_triggered: bool,
15389        window: &mut Window,
15390        cx: &mut Context<Self>,
15391    ) {
15392        if self.git_blame_inline_enabled {
15393            self.git_blame_inline_enabled = false;
15394            self.show_git_blame_inline = false;
15395            self.show_git_blame_inline_delay_task.take();
15396        } else {
15397            self.git_blame_inline_enabled = true;
15398            self.start_git_blame_inline(user_triggered, window, cx);
15399        }
15400
15401        cx.notify();
15402    }
15403
15404    fn start_git_blame_inline(
15405        &mut self,
15406        user_triggered: bool,
15407        window: &mut Window,
15408        cx: &mut Context<Self>,
15409    ) {
15410        self.start_git_blame(user_triggered, window, cx);
15411
15412        if ProjectSettings::get_global(cx)
15413            .git
15414            .inline_blame_delay()
15415            .is_some()
15416        {
15417            self.start_inline_blame_timer(window, cx);
15418        } else {
15419            self.show_git_blame_inline = true
15420        }
15421    }
15422
15423    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
15424        self.blame.as_ref()
15425    }
15426
15427    pub fn show_git_blame_gutter(&self) -> bool {
15428        self.show_git_blame_gutter
15429    }
15430
15431    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
15432        self.show_git_blame_gutter && self.has_blame_entries(cx)
15433    }
15434
15435    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
15436        self.show_git_blame_inline
15437            && (self.focus_handle.is_focused(window)
15438                || self
15439                    .git_blame_inline_tooltip
15440                    .as_ref()
15441                    .and_then(|t| t.upgrade())
15442                    .is_some())
15443            && !self.newest_selection_head_on_empty_line(cx)
15444            && self.has_blame_entries(cx)
15445    }
15446
15447    fn has_blame_entries(&self, cx: &App) -> bool {
15448        self.blame()
15449            .map_or(false, |blame| blame.read(cx).has_generated_entries())
15450    }
15451
15452    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
15453        let cursor_anchor = self.selections.newest_anchor().head();
15454
15455        let snapshot = self.buffer.read(cx).snapshot(cx);
15456        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
15457
15458        snapshot.line_len(buffer_row) == 0
15459    }
15460
15461    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
15462        let buffer_and_selection = maybe!({
15463            let selection = self.selections.newest::<Point>(cx);
15464            let selection_range = selection.range();
15465
15466            let multi_buffer = self.buffer().read(cx);
15467            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15468            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
15469
15470            let (buffer, range, _) = if selection.reversed {
15471                buffer_ranges.first()
15472            } else {
15473                buffer_ranges.last()
15474            }?;
15475
15476            let selection = text::ToPoint::to_point(&range.start, &buffer).row
15477                ..text::ToPoint::to_point(&range.end, &buffer).row;
15478            Some((
15479                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
15480                selection,
15481            ))
15482        });
15483
15484        let Some((buffer, selection)) = buffer_and_selection else {
15485            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
15486        };
15487
15488        let Some(project) = self.project.as_ref() else {
15489            return Task::ready(Err(anyhow!("editor does not have project")));
15490        };
15491
15492        project.update(cx, |project, cx| {
15493            project.get_permalink_to_line(&buffer, selection, cx)
15494        })
15495    }
15496
15497    pub fn copy_permalink_to_line(
15498        &mut self,
15499        _: &CopyPermalinkToLine,
15500        window: &mut Window,
15501        cx: &mut Context<Self>,
15502    ) {
15503        let permalink_task = self.get_permalink_to_line(cx);
15504        let workspace = self.workspace();
15505
15506        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
15507            Ok(permalink) => {
15508                cx.update(|_, cx| {
15509                    cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
15510                })
15511                .ok();
15512            }
15513            Err(err) => {
15514                let message = format!("Failed to copy permalink: {err}");
15515
15516                Err::<(), anyhow::Error>(err).log_err();
15517
15518                if let Some(workspace) = workspace {
15519                    workspace
15520                        .update_in(cx, |workspace, _, cx| {
15521                            struct CopyPermalinkToLine;
15522
15523                            workspace.show_toast(
15524                                Toast::new(
15525                                    NotificationId::unique::<CopyPermalinkToLine>(),
15526                                    message,
15527                                ),
15528                                cx,
15529                            )
15530                        })
15531                        .ok();
15532                }
15533            }
15534        })
15535        .detach();
15536    }
15537
15538    pub fn copy_file_location(
15539        &mut self,
15540        _: &CopyFileLocation,
15541        _: &mut Window,
15542        cx: &mut Context<Self>,
15543    ) {
15544        let selection = self.selections.newest::<Point>(cx).start.row + 1;
15545        if let Some(file) = self.target_file(cx) {
15546            if let Some(path) = file.path().to_str() {
15547                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
15548            }
15549        }
15550    }
15551
15552    pub fn open_permalink_to_line(
15553        &mut self,
15554        _: &OpenPermalinkToLine,
15555        window: &mut Window,
15556        cx: &mut Context<Self>,
15557    ) {
15558        let permalink_task = self.get_permalink_to_line(cx);
15559        let workspace = self.workspace();
15560
15561        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
15562            Ok(permalink) => {
15563                cx.update(|_, cx| {
15564                    cx.open_url(permalink.as_ref());
15565                })
15566                .ok();
15567            }
15568            Err(err) => {
15569                let message = format!("Failed to open permalink: {err}");
15570
15571                Err::<(), anyhow::Error>(err).log_err();
15572
15573                if let Some(workspace) = workspace {
15574                    workspace
15575                        .update(cx, |workspace, cx| {
15576                            struct OpenPermalinkToLine;
15577
15578                            workspace.show_toast(
15579                                Toast::new(
15580                                    NotificationId::unique::<OpenPermalinkToLine>(),
15581                                    message,
15582                                ),
15583                                cx,
15584                            )
15585                        })
15586                        .ok();
15587                }
15588            }
15589        })
15590        .detach();
15591    }
15592
15593    pub fn insert_uuid_v4(
15594        &mut self,
15595        _: &InsertUuidV4,
15596        window: &mut Window,
15597        cx: &mut Context<Self>,
15598    ) {
15599        self.insert_uuid(UuidVersion::V4, window, cx);
15600    }
15601
15602    pub fn insert_uuid_v7(
15603        &mut self,
15604        _: &InsertUuidV7,
15605        window: &mut Window,
15606        cx: &mut Context<Self>,
15607    ) {
15608        self.insert_uuid(UuidVersion::V7, window, cx);
15609    }
15610
15611    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
15612        self.transact(window, cx, |this, window, cx| {
15613            let edits = this
15614                .selections
15615                .all::<Point>(cx)
15616                .into_iter()
15617                .map(|selection| {
15618                    let uuid = match version {
15619                        UuidVersion::V4 => uuid::Uuid::new_v4(),
15620                        UuidVersion::V7 => uuid::Uuid::now_v7(),
15621                    };
15622
15623                    (selection.range(), uuid.to_string())
15624                });
15625            this.edit(edits, cx);
15626            this.refresh_inline_completion(true, false, window, cx);
15627        });
15628    }
15629
15630    pub fn open_selections_in_multibuffer(
15631        &mut self,
15632        _: &OpenSelectionsInMultibuffer,
15633        window: &mut Window,
15634        cx: &mut Context<Self>,
15635    ) {
15636        let multibuffer = self.buffer.read(cx);
15637
15638        let Some(buffer) = multibuffer.as_singleton() else {
15639            return;
15640        };
15641
15642        let Some(workspace) = self.workspace() else {
15643            return;
15644        };
15645
15646        let locations = self
15647            .selections
15648            .disjoint_anchors()
15649            .iter()
15650            .map(|range| Location {
15651                buffer: buffer.clone(),
15652                range: range.start.text_anchor..range.end.text_anchor,
15653            })
15654            .collect::<Vec<_>>();
15655
15656        let title = multibuffer.title(cx).to_string();
15657
15658        cx.spawn_in(window, async move |_, cx| {
15659            workspace.update_in(cx, |workspace, window, cx| {
15660                Self::open_locations_in_multibuffer(
15661                    workspace,
15662                    locations,
15663                    format!("Selections for '{title}'"),
15664                    false,
15665                    MultibufferSelectionMode::All,
15666                    window,
15667                    cx,
15668                );
15669            })
15670        })
15671        .detach();
15672    }
15673
15674    /// Adds a row highlight for the given range. If a row has multiple highlights, the
15675    /// last highlight added will be used.
15676    ///
15677    /// If the range ends at the beginning of a line, then that line will not be highlighted.
15678    pub fn highlight_rows<T: 'static>(
15679        &mut self,
15680        range: Range<Anchor>,
15681        color: Hsla,
15682        should_autoscroll: bool,
15683        cx: &mut Context<Self>,
15684    ) {
15685        let snapshot = self.buffer().read(cx).snapshot(cx);
15686        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
15687        let ix = row_highlights.binary_search_by(|highlight| {
15688            Ordering::Equal
15689                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
15690                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
15691        });
15692
15693        if let Err(mut ix) = ix {
15694            let index = post_inc(&mut self.highlight_order);
15695
15696            // If this range intersects with the preceding highlight, then merge it with
15697            // the preceding highlight. Otherwise insert a new highlight.
15698            let mut merged = false;
15699            if ix > 0 {
15700                let prev_highlight = &mut row_highlights[ix - 1];
15701                if prev_highlight
15702                    .range
15703                    .end
15704                    .cmp(&range.start, &snapshot)
15705                    .is_ge()
15706                {
15707                    ix -= 1;
15708                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
15709                        prev_highlight.range.end = range.end;
15710                    }
15711                    merged = true;
15712                    prev_highlight.index = index;
15713                    prev_highlight.color = color;
15714                    prev_highlight.should_autoscroll = should_autoscroll;
15715                }
15716            }
15717
15718            if !merged {
15719                row_highlights.insert(
15720                    ix,
15721                    RowHighlight {
15722                        range: range.clone(),
15723                        index,
15724                        color,
15725                        should_autoscroll,
15726                    },
15727                );
15728            }
15729
15730            // If any of the following highlights intersect with this one, merge them.
15731            while let Some(next_highlight) = row_highlights.get(ix + 1) {
15732                let highlight = &row_highlights[ix];
15733                if next_highlight
15734                    .range
15735                    .start
15736                    .cmp(&highlight.range.end, &snapshot)
15737                    .is_le()
15738                {
15739                    if next_highlight
15740                        .range
15741                        .end
15742                        .cmp(&highlight.range.end, &snapshot)
15743                        .is_gt()
15744                    {
15745                        row_highlights[ix].range.end = next_highlight.range.end;
15746                    }
15747                    row_highlights.remove(ix + 1);
15748                } else {
15749                    break;
15750                }
15751            }
15752        }
15753    }
15754
15755    /// Remove any highlighted row ranges of the given type that intersect the
15756    /// given ranges.
15757    pub fn remove_highlighted_rows<T: 'static>(
15758        &mut self,
15759        ranges_to_remove: Vec<Range<Anchor>>,
15760        cx: &mut Context<Self>,
15761    ) {
15762        let snapshot = self.buffer().read(cx).snapshot(cx);
15763        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
15764        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
15765        row_highlights.retain(|highlight| {
15766            while let Some(range_to_remove) = ranges_to_remove.peek() {
15767                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
15768                    Ordering::Less | Ordering::Equal => {
15769                        ranges_to_remove.next();
15770                    }
15771                    Ordering::Greater => {
15772                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
15773                            Ordering::Less | Ordering::Equal => {
15774                                return false;
15775                            }
15776                            Ordering::Greater => break,
15777                        }
15778                    }
15779                }
15780            }
15781
15782            true
15783        })
15784    }
15785
15786    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
15787    pub fn clear_row_highlights<T: 'static>(&mut self) {
15788        self.highlighted_rows.remove(&TypeId::of::<T>());
15789    }
15790
15791    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
15792    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
15793        self.highlighted_rows
15794            .get(&TypeId::of::<T>())
15795            .map_or(&[] as &[_], |vec| vec.as_slice())
15796            .iter()
15797            .map(|highlight| (highlight.range.clone(), highlight.color))
15798    }
15799
15800    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
15801    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
15802    /// Allows to ignore certain kinds of highlights.
15803    pub fn highlighted_display_rows(
15804        &self,
15805        window: &mut Window,
15806        cx: &mut App,
15807    ) -> BTreeMap<DisplayRow, LineHighlight> {
15808        let snapshot = self.snapshot(window, cx);
15809        let mut used_highlight_orders = HashMap::default();
15810        self.highlighted_rows
15811            .iter()
15812            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
15813            .fold(
15814                BTreeMap::<DisplayRow, LineHighlight>::new(),
15815                |mut unique_rows, highlight| {
15816                    let start = highlight.range.start.to_display_point(&snapshot);
15817                    let end = highlight.range.end.to_display_point(&snapshot);
15818                    let start_row = start.row().0;
15819                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
15820                        && end.column() == 0
15821                    {
15822                        end.row().0.saturating_sub(1)
15823                    } else {
15824                        end.row().0
15825                    };
15826                    for row in start_row..=end_row {
15827                        let used_index =
15828                            used_highlight_orders.entry(row).or_insert(highlight.index);
15829                        if highlight.index >= *used_index {
15830                            *used_index = highlight.index;
15831                            unique_rows.insert(DisplayRow(row), highlight.color.into());
15832                        }
15833                    }
15834                    unique_rows
15835                },
15836            )
15837    }
15838
15839    pub fn highlighted_display_row_for_autoscroll(
15840        &self,
15841        snapshot: &DisplaySnapshot,
15842    ) -> Option<DisplayRow> {
15843        self.highlighted_rows
15844            .values()
15845            .flat_map(|highlighted_rows| highlighted_rows.iter())
15846            .filter_map(|highlight| {
15847                if highlight.should_autoscroll {
15848                    Some(highlight.range.start.to_display_point(snapshot).row())
15849                } else {
15850                    None
15851                }
15852            })
15853            .min()
15854    }
15855
15856    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
15857        self.highlight_background::<SearchWithinRange>(
15858            ranges,
15859            |colors| colors.editor_document_highlight_read_background,
15860            cx,
15861        )
15862    }
15863
15864    pub fn set_breadcrumb_header(&mut self, new_header: String) {
15865        self.breadcrumb_header = Some(new_header);
15866    }
15867
15868    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
15869        self.clear_background_highlights::<SearchWithinRange>(cx);
15870    }
15871
15872    pub fn highlight_background<T: 'static>(
15873        &mut self,
15874        ranges: &[Range<Anchor>],
15875        color_fetcher: fn(&ThemeColors) -> Hsla,
15876        cx: &mut Context<Self>,
15877    ) {
15878        self.background_highlights
15879            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
15880        self.scrollbar_marker_state.dirty = true;
15881        cx.notify();
15882    }
15883
15884    pub fn clear_background_highlights<T: 'static>(
15885        &mut self,
15886        cx: &mut Context<Self>,
15887    ) -> Option<BackgroundHighlight> {
15888        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
15889        if !text_highlights.1.is_empty() {
15890            self.scrollbar_marker_state.dirty = true;
15891            cx.notify();
15892        }
15893        Some(text_highlights)
15894    }
15895
15896    pub fn highlight_gutter<T: 'static>(
15897        &mut self,
15898        ranges: &[Range<Anchor>],
15899        color_fetcher: fn(&App) -> Hsla,
15900        cx: &mut Context<Self>,
15901    ) {
15902        self.gutter_highlights
15903            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
15904        cx.notify();
15905    }
15906
15907    pub fn clear_gutter_highlights<T: 'static>(
15908        &mut self,
15909        cx: &mut Context<Self>,
15910    ) -> Option<GutterHighlight> {
15911        cx.notify();
15912        self.gutter_highlights.remove(&TypeId::of::<T>())
15913    }
15914
15915    #[cfg(feature = "test-support")]
15916    pub fn all_text_background_highlights(
15917        &self,
15918        window: &mut Window,
15919        cx: &mut Context<Self>,
15920    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15921        let snapshot = self.snapshot(window, cx);
15922        let buffer = &snapshot.buffer_snapshot;
15923        let start = buffer.anchor_before(0);
15924        let end = buffer.anchor_after(buffer.len());
15925        let theme = cx.theme().colors();
15926        self.background_highlights_in_range(start..end, &snapshot, theme)
15927    }
15928
15929    #[cfg(feature = "test-support")]
15930    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
15931        let snapshot = self.buffer().read(cx).snapshot(cx);
15932
15933        let highlights = self
15934            .background_highlights
15935            .get(&TypeId::of::<items::BufferSearchHighlights>());
15936
15937        if let Some((_color, ranges)) = highlights {
15938            ranges
15939                .iter()
15940                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
15941                .collect_vec()
15942        } else {
15943            vec![]
15944        }
15945    }
15946
15947    fn document_highlights_for_position<'a>(
15948        &'a self,
15949        position: Anchor,
15950        buffer: &'a MultiBufferSnapshot,
15951    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
15952        let read_highlights = self
15953            .background_highlights
15954            .get(&TypeId::of::<DocumentHighlightRead>())
15955            .map(|h| &h.1);
15956        let write_highlights = self
15957            .background_highlights
15958            .get(&TypeId::of::<DocumentHighlightWrite>())
15959            .map(|h| &h.1);
15960        let left_position = position.bias_left(buffer);
15961        let right_position = position.bias_right(buffer);
15962        read_highlights
15963            .into_iter()
15964            .chain(write_highlights)
15965            .flat_map(move |ranges| {
15966                let start_ix = match ranges.binary_search_by(|probe| {
15967                    let cmp = probe.end.cmp(&left_position, buffer);
15968                    if cmp.is_ge() {
15969                        Ordering::Greater
15970                    } else {
15971                        Ordering::Less
15972                    }
15973                }) {
15974                    Ok(i) | Err(i) => i,
15975                };
15976
15977                ranges[start_ix..]
15978                    .iter()
15979                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
15980            })
15981    }
15982
15983    pub fn has_background_highlights<T: 'static>(&self) -> bool {
15984        self.background_highlights
15985            .get(&TypeId::of::<T>())
15986            .map_or(false, |(_, highlights)| !highlights.is_empty())
15987    }
15988
15989    pub fn background_highlights_in_range(
15990        &self,
15991        search_range: Range<Anchor>,
15992        display_snapshot: &DisplaySnapshot,
15993        theme: &ThemeColors,
15994    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15995        let mut results = Vec::new();
15996        for (color_fetcher, ranges) in self.background_highlights.values() {
15997            let color = color_fetcher(theme);
15998            let start_ix = match ranges.binary_search_by(|probe| {
15999                let cmp = probe
16000                    .end
16001                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16002                if cmp.is_gt() {
16003                    Ordering::Greater
16004                } else {
16005                    Ordering::Less
16006                }
16007            }) {
16008                Ok(i) | Err(i) => i,
16009            };
16010            for range in &ranges[start_ix..] {
16011                if range
16012                    .start
16013                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16014                    .is_ge()
16015                {
16016                    break;
16017                }
16018
16019                let start = range.start.to_display_point(display_snapshot);
16020                let end = range.end.to_display_point(display_snapshot);
16021                results.push((start..end, color))
16022            }
16023        }
16024        results
16025    }
16026
16027    pub fn background_highlight_row_ranges<T: 'static>(
16028        &self,
16029        search_range: Range<Anchor>,
16030        display_snapshot: &DisplaySnapshot,
16031        count: usize,
16032    ) -> Vec<RangeInclusive<DisplayPoint>> {
16033        let mut results = Vec::new();
16034        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
16035            return vec![];
16036        };
16037
16038        let start_ix = match ranges.binary_search_by(|probe| {
16039            let cmp = probe
16040                .end
16041                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16042            if cmp.is_gt() {
16043                Ordering::Greater
16044            } else {
16045                Ordering::Less
16046            }
16047        }) {
16048            Ok(i) | Err(i) => i,
16049        };
16050        let mut push_region = |start: Option<Point>, end: Option<Point>| {
16051            if let (Some(start_display), Some(end_display)) = (start, end) {
16052                results.push(
16053                    start_display.to_display_point(display_snapshot)
16054                        ..=end_display.to_display_point(display_snapshot),
16055                );
16056            }
16057        };
16058        let mut start_row: Option<Point> = None;
16059        let mut end_row: Option<Point> = None;
16060        if ranges.len() > count {
16061            return Vec::new();
16062        }
16063        for range in &ranges[start_ix..] {
16064            if range
16065                .start
16066                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16067                .is_ge()
16068            {
16069                break;
16070            }
16071            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
16072            if let Some(current_row) = &end_row {
16073                if end.row == current_row.row {
16074                    continue;
16075                }
16076            }
16077            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
16078            if start_row.is_none() {
16079                assert_eq!(end_row, None);
16080                start_row = Some(start);
16081                end_row = Some(end);
16082                continue;
16083            }
16084            if let Some(current_end) = end_row.as_mut() {
16085                if start.row > current_end.row + 1 {
16086                    push_region(start_row, end_row);
16087                    start_row = Some(start);
16088                    end_row = Some(end);
16089                } else {
16090                    // Merge two hunks.
16091                    *current_end = end;
16092                }
16093            } else {
16094                unreachable!();
16095            }
16096        }
16097        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
16098        push_region(start_row, end_row);
16099        results
16100    }
16101
16102    pub fn gutter_highlights_in_range(
16103        &self,
16104        search_range: Range<Anchor>,
16105        display_snapshot: &DisplaySnapshot,
16106        cx: &App,
16107    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16108        let mut results = Vec::new();
16109        for (color_fetcher, ranges) in self.gutter_highlights.values() {
16110            let color = color_fetcher(cx);
16111            let start_ix = match ranges.binary_search_by(|probe| {
16112                let cmp = probe
16113                    .end
16114                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16115                if cmp.is_gt() {
16116                    Ordering::Greater
16117                } else {
16118                    Ordering::Less
16119                }
16120            }) {
16121                Ok(i) | Err(i) => i,
16122            };
16123            for range in &ranges[start_ix..] {
16124                if range
16125                    .start
16126                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16127                    .is_ge()
16128                {
16129                    break;
16130                }
16131
16132                let start = range.start.to_display_point(display_snapshot);
16133                let end = range.end.to_display_point(display_snapshot);
16134                results.push((start..end, color))
16135            }
16136        }
16137        results
16138    }
16139
16140    /// Get the text ranges corresponding to the redaction query
16141    pub fn redacted_ranges(
16142        &self,
16143        search_range: Range<Anchor>,
16144        display_snapshot: &DisplaySnapshot,
16145        cx: &App,
16146    ) -> Vec<Range<DisplayPoint>> {
16147        display_snapshot
16148            .buffer_snapshot
16149            .redacted_ranges(search_range, |file| {
16150                if let Some(file) = file {
16151                    file.is_private()
16152                        && EditorSettings::get(
16153                            Some(SettingsLocation {
16154                                worktree_id: file.worktree_id(cx),
16155                                path: file.path().as_ref(),
16156                            }),
16157                            cx,
16158                        )
16159                        .redact_private_values
16160                } else {
16161                    false
16162                }
16163            })
16164            .map(|range| {
16165                range.start.to_display_point(display_snapshot)
16166                    ..range.end.to_display_point(display_snapshot)
16167            })
16168            .collect()
16169    }
16170
16171    pub fn highlight_text<T: 'static>(
16172        &mut self,
16173        ranges: Vec<Range<Anchor>>,
16174        style: HighlightStyle,
16175        cx: &mut Context<Self>,
16176    ) {
16177        self.display_map.update(cx, |map, _| {
16178            map.highlight_text(TypeId::of::<T>(), ranges, style)
16179        });
16180        cx.notify();
16181    }
16182
16183    pub(crate) fn highlight_inlays<T: 'static>(
16184        &mut self,
16185        highlights: Vec<InlayHighlight>,
16186        style: HighlightStyle,
16187        cx: &mut Context<Self>,
16188    ) {
16189        self.display_map.update(cx, |map, _| {
16190            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
16191        });
16192        cx.notify();
16193    }
16194
16195    pub fn text_highlights<'a, T: 'static>(
16196        &'a self,
16197        cx: &'a App,
16198    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
16199        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
16200    }
16201
16202    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
16203        let cleared = self
16204            .display_map
16205            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
16206        if cleared {
16207            cx.notify();
16208        }
16209    }
16210
16211    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
16212        (self.read_only(cx) || self.blink_manager.read(cx).visible())
16213            && self.focus_handle.is_focused(window)
16214    }
16215
16216    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
16217        self.show_cursor_when_unfocused = is_enabled;
16218        cx.notify();
16219    }
16220
16221    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
16222        cx.notify();
16223    }
16224
16225    fn on_buffer_event(
16226        &mut self,
16227        multibuffer: &Entity<MultiBuffer>,
16228        event: &multi_buffer::Event,
16229        window: &mut Window,
16230        cx: &mut Context<Self>,
16231    ) {
16232        match event {
16233            multi_buffer::Event::Edited {
16234                singleton_buffer_edited,
16235                edited_buffer: buffer_edited,
16236            } => {
16237                self.scrollbar_marker_state.dirty = true;
16238                self.active_indent_guides_state.dirty = true;
16239                self.refresh_active_diagnostics(cx);
16240                self.refresh_code_actions(window, cx);
16241                if self.has_active_inline_completion() {
16242                    self.update_visible_inline_completion(window, cx);
16243                }
16244                if let Some(buffer) = buffer_edited {
16245                    let buffer_id = buffer.read(cx).remote_id();
16246                    if !self.registered_buffers.contains_key(&buffer_id) {
16247                        if let Some(project) = self.project.as_ref() {
16248                            project.update(cx, |project, cx| {
16249                                self.registered_buffers.insert(
16250                                    buffer_id,
16251                                    project.register_buffer_with_language_servers(&buffer, cx),
16252                                );
16253                            })
16254                        }
16255                    }
16256                }
16257                cx.emit(EditorEvent::BufferEdited);
16258                cx.emit(SearchEvent::MatchesInvalidated);
16259                if *singleton_buffer_edited {
16260                    if let Some(project) = &self.project {
16261                        #[allow(clippy::mutable_key_type)]
16262                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
16263                            multibuffer
16264                                .all_buffers()
16265                                .into_iter()
16266                                .filter_map(|buffer| {
16267                                    buffer.update(cx, |buffer, cx| {
16268                                        let language = buffer.language()?;
16269                                        let should_discard = project.update(cx, |project, cx| {
16270                                            project.is_local()
16271                                                && !project.has_language_servers_for(buffer, cx)
16272                                        });
16273                                        should_discard.not().then_some(language.clone())
16274                                    })
16275                                })
16276                                .collect::<HashSet<_>>()
16277                        });
16278                        if !languages_affected.is_empty() {
16279                            self.refresh_inlay_hints(
16280                                InlayHintRefreshReason::BufferEdited(languages_affected),
16281                                cx,
16282                            );
16283                        }
16284                    }
16285                }
16286
16287                let Some(project) = &self.project else { return };
16288                let (telemetry, is_via_ssh) = {
16289                    let project = project.read(cx);
16290                    let telemetry = project.client().telemetry().clone();
16291                    let is_via_ssh = project.is_via_ssh();
16292                    (telemetry, is_via_ssh)
16293                };
16294                refresh_linked_ranges(self, window, cx);
16295                telemetry.log_edit_event("editor", is_via_ssh);
16296            }
16297            multi_buffer::Event::ExcerptsAdded {
16298                buffer,
16299                predecessor,
16300                excerpts,
16301            } => {
16302                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16303                let buffer_id = buffer.read(cx).remote_id();
16304                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
16305                    if let Some(project) = &self.project {
16306                        get_uncommitted_diff_for_buffer(
16307                            project,
16308                            [buffer.clone()],
16309                            self.buffer.clone(),
16310                            cx,
16311                        )
16312                        .detach();
16313                    }
16314                }
16315                cx.emit(EditorEvent::ExcerptsAdded {
16316                    buffer: buffer.clone(),
16317                    predecessor: *predecessor,
16318                    excerpts: excerpts.clone(),
16319                });
16320                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
16321            }
16322            multi_buffer::Event::ExcerptsRemoved { ids } => {
16323                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
16324                let buffer = self.buffer.read(cx);
16325                self.registered_buffers
16326                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
16327                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
16328                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
16329            }
16330            multi_buffer::Event::ExcerptsEdited {
16331                excerpt_ids,
16332                buffer_ids,
16333            } => {
16334                self.display_map.update(cx, |map, cx| {
16335                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
16336                });
16337                cx.emit(EditorEvent::ExcerptsEdited {
16338                    ids: excerpt_ids.clone(),
16339                })
16340            }
16341            multi_buffer::Event::ExcerptsExpanded { ids } => {
16342                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
16343                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
16344            }
16345            multi_buffer::Event::Reparsed(buffer_id) => {
16346                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16347                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
16348
16349                cx.emit(EditorEvent::Reparsed(*buffer_id));
16350            }
16351            multi_buffer::Event::DiffHunksToggled => {
16352                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16353            }
16354            multi_buffer::Event::LanguageChanged(buffer_id) => {
16355                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
16356                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
16357                cx.emit(EditorEvent::Reparsed(*buffer_id));
16358                cx.notify();
16359            }
16360            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
16361            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
16362            multi_buffer::Event::FileHandleChanged
16363            | multi_buffer::Event::Reloaded
16364            | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
16365            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
16366            multi_buffer::Event::DiagnosticsUpdated => {
16367                self.refresh_active_diagnostics(cx);
16368                self.refresh_inline_diagnostics(true, window, cx);
16369                self.scrollbar_marker_state.dirty = true;
16370                cx.notify();
16371            }
16372            _ => {}
16373        };
16374    }
16375
16376    fn on_display_map_changed(
16377        &mut self,
16378        _: Entity<DisplayMap>,
16379        _: &mut Window,
16380        cx: &mut Context<Self>,
16381    ) {
16382        cx.notify();
16383    }
16384
16385    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16386        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16387        self.update_edit_prediction_settings(cx);
16388        self.refresh_inline_completion(true, false, window, cx);
16389        self.refresh_inlay_hints(
16390            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
16391                self.selections.newest_anchor().head(),
16392                &self.buffer.read(cx).snapshot(cx),
16393                cx,
16394            )),
16395            cx,
16396        );
16397
16398        let old_cursor_shape = self.cursor_shape;
16399
16400        {
16401            let editor_settings = EditorSettings::get_global(cx);
16402            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
16403            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
16404            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
16405        }
16406
16407        if old_cursor_shape != self.cursor_shape {
16408            cx.emit(EditorEvent::CursorShapeChanged);
16409        }
16410
16411        let project_settings = ProjectSettings::get_global(cx);
16412        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
16413
16414        if self.mode == EditorMode::Full {
16415            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
16416            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
16417            if self.show_inline_diagnostics != show_inline_diagnostics {
16418                self.show_inline_diagnostics = show_inline_diagnostics;
16419                self.refresh_inline_diagnostics(false, window, cx);
16420            }
16421
16422            if self.git_blame_inline_enabled != inline_blame_enabled {
16423                self.toggle_git_blame_inline_internal(false, window, cx);
16424            }
16425        }
16426
16427        cx.notify();
16428    }
16429
16430    pub fn set_searchable(&mut self, searchable: bool) {
16431        self.searchable = searchable;
16432    }
16433
16434    pub fn searchable(&self) -> bool {
16435        self.searchable
16436    }
16437
16438    fn open_proposed_changes_editor(
16439        &mut self,
16440        _: &OpenProposedChangesEditor,
16441        window: &mut Window,
16442        cx: &mut Context<Self>,
16443    ) {
16444        let Some(workspace) = self.workspace() else {
16445            cx.propagate();
16446            return;
16447        };
16448
16449        let selections = self.selections.all::<usize>(cx);
16450        let multi_buffer = self.buffer.read(cx);
16451        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16452        let mut new_selections_by_buffer = HashMap::default();
16453        for selection in selections {
16454            for (buffer, range, _) in
16455                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
16456            {
16457                let mut range = range.to_point(buffer);
16458                range.start.column = 0;
16459                range.end.column = buffer.line_len(range.end.row);
16460                new_selections_by_buffer
16461                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
16462                    .or_insert(Vec::new())
16463                    .push(range)
16464            }
16465        }
16466
16467        let proposed_changes_buffers = new_selections_by_buffer
16468            .into_iter()
16469            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
16470            .collect::<Vec<_>>();
16471        let proposed_changes_editor = cx.new(|cx| {
16472            ProposedChangesEditor::new(
16473                "Proposed changes",
16474                proposed_changes_buffers,
16475                self.project.clone(),
16476                window,
16477                cx,
16478            )
16479        });
16480
16481        window.defer(cx, move |window, cx| {
16482            workspace.update(cx, |workspace, cx| {
16483                workspace.active_pane().update(cx, |pane, cx| {
16484                    pane.add_item(
16485                        Box::new(proposed_changes_editor),
16486                        true,
16487                        true,
16488                        None,
16489                        window,
16490                        cx,
16491                    );
16492                });
16493            });
16494        });
16495    }
16496
16497    pub fn open_excerpts_in_split(
16498        &mut self,
16499        _: &OpenExcerptsSplit,
16500        window: &mut Window,
16501        cx: &mut Context<Self>,
16502    ) {
16503        self.open_excerpts_common(None, true, window, cx)
16504    }
16505
16506    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
16507        self.open_excerpts_common(None, false, window, cx)
16508    }
16509
16510    fn open_excerpts_common(
16511        &mut self,
16512        jump_data: Option<JumpData>,
16513        split: bool,
16514        window: &mut Window,
16515        cx: &mut Context<Self>,
16516    ) {
16517        let Some(workspace) = self.workspace() else {
16518            cx.propagate();
16519            return;
16520        };
16521
16522        if self.buffer.read(cx).is_singleton() {
16523            cx.propagate();
16524            return;
16525        }
16526
16527        let mut new_selections_by_buffer = HashMap::default();
16528        match &jump_data {
16529            Some(JumpData::MultiBufferPoint {
16530                excerpt_id,
16531                position,
16532                anchor,
16533                line_offset_from_top,
16534            }) => {
16535                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
16536                if let Some(buffer) = multi_buffer_snapshot
16537                    .buffer_id_for_excerpt(*excerpt_id)
16538                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
16539                {
16540                    let buffer_snapshot = buffer.read(cx).snapshot();
16541                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
16542                        language::ToPoint::to_point(anchor, &buffer_snapshot)
16543                    } else {
16544                        buffer_snapshot.clip_point(*position, Bias::Left)
16545                    };
16546                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
16547                    new_selections_by_buffer.insert(
16548                        buffer,
16549                        (
16550                            vec![jump_to_offset..jump_to_offset],
16551                            Some(*line_offset_from_top),
16552                        ),
16553                    );
16554                }
16555            }
16556            Some(JumpData::MultiBufferRow {
16557                row,
16558                line_offset_from_top,
16559            }) => {
16560                let point = MultiBufferPoint::new(row.0, 0);
16561                if let Some((buffer, buffer_point, _)) =
16562                    self.buffer.read(cx).point_to_buffer_point(point, cx)
16563                {
16564                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
16565                    new_selections_by_buffer
16566                        .entry(buffer)
16567                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
16568                        .0
16569                        .push(buffer_offset..buffer_offset)
16570                }
16571            }
16572            None => {
16573                let selections = self.selections.all::<usize>(cx);
16574                let multi_buffer = self.buffer.read(cx);
16575                for selection in selections {
16576                    for (snapshot, range, _, anchor) in multi_buffer
16577                        .snapshot(cx)
16578                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
16579                    {
16580                        if let Some(anchor) = anchor {
16581                            // selection is in a deleted hunk
16582                            let Some(buffer_id) = anchor.buffer_id else {
16583                                continue;
16584                            };
16585                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
16586                                continue;
16587                            };
16588                            let offset = text::ToOffset::to_offset(
16589                                &anchor.text_anchor,
16590                                &buffer_handle.read(cx).snapshot(),
16591                            );
16592                            let range = offset..offset;
16593                            new_selections_by_buffer
16594                                .entry(buffer_handle)
16595                                .or_insert((Vec::new(), None))
16596                                .0
16597                                .push(range)
16598                        } else {
16599                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
16600                            else {
16601                                continue;
16602                            };
16603                            new_selections_by_buffer
16604                                .entry(buffer_handle)
16605                                .or_insert((Vec::new(), None))
16606                                .0
16607                                .push(range)
16608                        }
16609                    }
16610                }
16611            }
16612        }
16613
16614        if new_selections_by_buffer.is_empty() {
16615            return;
16616        }
16617
16618        // We defer the pane interaction because we ourselves are a workspace item
16619        // and activating a new item causes the pane to call a method on us reentrantly,
16620        // which panics if we're on the stack.
16621        window.defer(cx, move |window, cx| {
16622            workspace.update(cx, |workspace, cx| {
16623                let pane = if split {
16624                    workspace.adjacent_pane(window, cx)
16625                } else {
16626                    workspace.active_pane().clone()
16627                };
16628
16629                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
16630                    let editor = buffer
16631                        .read(cx)
16632                        .file()
16633                        .is_none()
16634                        .then(|| {
16635                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
16636                            // so `workspace.open_project_item` will never find them, always opening a new editor.
16637                            // Instead, we try to activate the existing editor in the pane first.
16638                            let (editor, pane_item_index) =
16639                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
16640                                    let editor = item.downcast::<Editor>()?;
16641                                    let singleton_buffer =
16642                                        editor.read(cx).buffer().read(cx).as_singleton()?;
16643                                    if singleton_buffer == buffer {
16644                                        Some((editor, i))
16645                                    } else {
16646                                        None
16647                                    }
16648                                })?;
16649                            pane.update(cx, |pane, cx| {
16650                                pane.activate_item(pane_item_index, true, true, window, cx)
16651                            });
16652                            Some(editor)
16653                        })
16654                        .flatten()
16655                        .unwrap_or_else(|| {
16656                            workspace.open_project_item::<Self>(
16657                                pane.clone(),
16658                                buffer,
16659                                true,
16660                                true,
16661                                window,
16662                                cx,
16663                            )
16664                        });
16665
16666                    editor.update(cx, |editor, cx| {
16667                        let autoscroll = match scroll_offset {
16668                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
16669                            None => Autoscroll::newest(),
16670                        };
16671                        let nav_history = editor.nav_history.take();
16672                        editor.change_selections(Some(autoscroll), window, cx, |s| {
16673                            s.select_ranges(ranges);
16674                        });
16675                        editor.nav_history = nav_history;
16676                    });
16677                }
16678            })
16679        });
16680    }
16681
16682    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
16683        let snapshot = self.buffer.read(cx).read(cx);
16684        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
16685        Some(
16686            ranges
16687                .iter()
16688                .map(move |range| {
16689                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
16690                })
16691                .collect(),
16692        )
16693    }
16694
16695    fn selection_replacement_ranges(
16696        &self,
16697        range: Range<OffsetUtf16>,
16698        cx: &mut App,
16699    ) -> Vec<Range<OffsetUtf16>> {
16700        let selections = self.selections.all::<OffsetUtf16>(cx);
16701        let newest_selection = selections
16702            .iter()
16703            .max_by_key(|selection| selection.id)
16704            .unwrap();
16705        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
16706        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
16707        let snapshot = self.buffer.read(cx).read(cx);
16708        selections
16709            .into_iter()
16710            .map(|mut selection| {
16711                selection.start.0 =
16712                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
16713                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
16714                snapshot.clip_offset_utf16(selection.start, Bias::Left)
16715                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
16716            })
16717            .collect()
16718    }
16719
16720    fn report_editor_event(
16721        &self,
16722        event_type: &'static str,
16723        file_extension: Option<String>,
16724        cx: &App,
16725    ) {
16726        if cfg!(any(test, feature = "test-support")) {
16727            return;
16728        }
16729
16730        let Some(project) = &self.project else { return };
16731
16732        // If None, we are in a file without an extension
16733        let file = self
16734            .buffer
16735            .read(cx)
16736            .as_singleton()
16737            .and_then(|b| b.read(cx).file());
16738        let file_extension = file_extension.or(file
16739            .as_ref()
16740            .and_then(|file| Path::new(file.file_name(cx)).extension())
16741            .and_then(|e| e.to_str())
16742            .map(|a| a.to_string()));
16743
16744        let vim_mode = cx
16745            .global::<SettingsStore>()
16746            .raw_user_settings()
16747            .get("vim_mode")
16748            == Some(&serde_json::Value::Bool(true));
16749
16750        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
16751        let copilot_enabled = edit_predictions_provider
16752            == language::language_settings::EditPredictionProvider::Copilot;
16753        let copilot_enabled_for_language = self
16754            .buffer
16755            .read(cx)
16756            .language_settings(cx)
16757            .show_edit_predictions;
16758
16759        let project = project.read(cx);
16760        telemetry::event!(
16761            event_type,
16762            file_extension,
16763            vim_mode,
16764            copilot_enabled,
16765            copilot_enabled_for_language,
16766            edit_predictions_provider,
16767            is_via_ssh = project.is_via_ssh(),
16768        );
16769    }
16770
16771    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
16772    /// with each line being an array of {text, highlight} objects.
16773    fn copy_highlight_json(
16774        &mut self,
16775        _: &CopyHighlightJson,
16776        window: &mut Window,
16777        cx: &mut Context<Self>,
16778    ) {
16779        #[derive(Serialize)]
16780        struct Chunk<'a> {
16781            text: String,
16782            highlight: Option<&'a str>,
16783        }
16784
16785        let snapshot = self.buffer.read(cx).snapshot(cx);
16786        let range = self
16787            .selected_text_range(false, window, cx)
16788            .and_then(|selection| {
16789                if selection.range.is_empty() {
16790                    None
16791                } else {
16792                    Some(selection.range)
16793                }
16794            })
16795            .unwrap_or_else(|| 0..snapshot.len());
16796
16797        let chunks = snapshot.chunks(range, true);
16798        let mut lines = Vec::new();
16799        let mut line: VecDeque<Chunk> = VecDeque::new();
16800
16801        let Some(style) = self.style.as_ref() else {
16802            return;
16803        };
16804
16805        for chunk in chunks {
16806            let highlight = chunk
16807                .syntax_highlight_id
16808                .and_then(|id| id.name(&style.syntax));
16809            let mut chunk_lines = chunk.text.split('\n').peekable();
16810            while let Some(text) = chunk_lines.next() {
16811                let mut merged_with_last_token = false;
16812                if let Some(last_token) = line.back_mut() {
16813                    if last_token.highlight == highlight {
16814                        last_token.text.push_str(text);
16815                        merged_with_last_token = true;
16816                    }
16817                }
16818
16819                if !merged_with_last_token {
16820                    line.push_back(Chunk {
16821                        text: text.into(),
16822                        highlight,
16823                    });
16824                }
16825
16826                if chunk_lines.peek().is_some() {
16827                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
16828                        line.pop_front();
16829                    }
16830                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
16831                        line.pop_back();
16832                    }
16833
16834                    lines.push(mem::take(&mut line));
16835                }
16836            }
16837        }
16838
16839        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
16840            return;
16841        };
16842        cx.write_to_clipboard(ClipboardItem::new_string(lines));
16843    }
16844
16845    pub fn open_context_menu(
16846        &mut self,
16847        _: &OpenContextMenu,
16848        window: &mut Window,
16849        cx: &mut Context<Self>,
16850    ) {
16851        self.request_autoscroll(Autoscroll::newest(), cx);
16852        let position = self.selections.newest_display(cx).start;
16853        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
16854    }
16855
16856    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
16857        &self.inlay_hint_cache
16858    }
16859
16860    pub fn replay_insert_event(
16861        &mut self,
16862        text: &str,
16863        relative_utf16_range: Option<Range<isize>>,
16864        window: &mut Window,
16865        cx: &mut Context<Self>,
16866    ) {
16867        if !self.input_enabled {
16868            cx.emit(EditorEvent::InputIgnored { text: text.into() });
16869            return;
16870        }
16871        if let Some(relative_utf16_range) = relative_utf16_range {
16872            let selections = self.selections.all::<OffsetUtf16>(cx);
16873            self.change_selections(None, window, cx, |s| {
16874                let new_ranges = selections.into_iter().map(|range| {
16875                    let start = OffsetUtf16(
16876                        range
16877                            .head()
16878                            .0
16879                            .saturating_add_signed(relative_utf16_range.start),
16880                    );
16881                    let end = OffsetUtf16(
16882                        range
16883                            .head()
16884                            .0
16885                            .saturating_add_signed(relative_utf16_range.end),
16886                    );
16887                    start..end
16888                });
16889                s.select_ranges(new_ranges);
16890            });
16891        }
16892
16893        self.handle_input(text, window, cx);
16894    }
16895
16896    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
16897        let Some(provider) = self.semantics_provider.as_ref() else {
16898            return false;
16899        };
16900
16901        let mut supports = false;
16902        self.buffer().update(cx, |this, cx| {
16903            this.for_each_buffer(|buffer| {
16904                supports |= provider.supports_inlay_hints(buffer, cx);
16905            });
16906        });
16907
16908        supports
16909    }
16910
16911    pub fn is_focused(&self, window: &Window) -> bool {
16912        self.focus_handle.is_focused(window)
16913    }
16914
16915    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16916        cx.emit(EditorEvent::Focused);
16917
16918        if let Some(descendant) = self
16919            .last_focused_descendant
16920            .take()
16921            .and_then(|descendant| descendant.upgrade())
16922        {
16923            window.focus(&descendant);
16924        } else {
16925            if let Some(blame) = self.blame.as_ref() {
16926                blame.update(cx, GitBlame::focus)
16927            }
16928
16929            self.blink_manager.update(cx, BlinkManager::enable);
16930            self.show_cursor_names(window, cx);
16931            self.buffer.update(cx, |buffer, cx| {
16932                buffer.finalize_last_transaction(cx);
16933                if self.leader_peer_id.is_none() {
16934                    buffer.set_active_selections(
16935                        &self.selections.disjoint_anchors(),
16936                        self.selections.line_mode,
16937                        self.cursor_shape,
16938                        cx,
16939                    );
16940                }
16941            });
16942        }
16943    }
16944
16945    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16946        cx.emit(EditorEvent::FocusedIn)
16947    }
16948
16949    fn handle_focus_out(
16950        &mut self,
16951        event: FocusOutEvent,
16952        _window: &mut Window,
16953        cx: &mut Context<Self>,
16954    ) {
16955        if event.blurred != self.focus_handle {
16956            self.last_focused_descendant = Some(event.blurred);
16957        }
16958        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
16959    }
16960
16961    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16962        self.blink_manager.update(cx, BlinkManager::disable);
16963        self.buffer
16964            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
16965
16966        if let Some(blame) = self.blame.as_ref() {
16967            blame.update(cx, GitBlame::blur)
16968        }
16969        if !self.hover_state.focused(window, cx) {
16970            hide_hover(self, cx);
16971        }
16972        if !self
16973            .context_menu
16974            .borrow()
16975            .as_ref()
16976            .is_some_and(|context_menu| context_menu.focused(window, cx))
16977        {
16978            self.hide_context_menu(window, cx);
16979        }
16980        self.discard_inline_completion(false, cx);
16981        cx.emit(EditorEvent::Blurred);
16982        cx.notify();
16983    }
16984
16985    pub fn register_action<A: Action>(
16986        &mut self,
16987        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
16988    ) -> Subscription {
16989        let id = self.next_editor_action_id.post_inc();
16990        let listener = Arc::new(listener);
16991        self.editor_actions.borrow_mut().insert(
16992            id,
16993            Box::new(move |window, _| {
16994                let listener = listener.clone();
16995                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
16996                    let action = action.downcast_ref().unwrap();
16997                    if phase == DispatchPhase::Bubble {
16998                        listener(action, window, cx)
16999                    }
17000                })
17001            }),
17002        );
17003
17004        let editor_actions = self.editor_actions.clone();
17005        Subscription::new(move || {
17006            editor_actions.borrow_mut().remove(&id);
17007        })
17008    }
17009
17010    pub fn file_header_size(&self) -> u32 {
17011        FILE_HEADER_HEIGHT
17012    }
17013
17014    pub fn restore(
17015        &mut self,
17016        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
17017        window: &mut Window,
17018        cx: &mut Context<Self>,
17019    ) {
17020        let workspace = self.workspace();
17021        let project = self.project.as_ref();
17022        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
17023            let mut tasks = Vec::new();
17024            for (buffer_id, changes) in revert_changes {
17025                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
17026                    buffer.update(cx, |buffer, cx| {
17027                        buffer.edit(
17028                            changes
17029                                .into_iter()
17030                                .map(|(range, text)| (range, text.to_string())),
17031                            None,
17032                            cx,
17033                        );
17034                    });
17035
17036                    if let Some(project) =
17037                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
17038                    {
17039                        project.update(cx, |project, cx| {
17040                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
17041                        })
17042                    }
17043                }
17044            }
17045            tasks
17046        });
17047        cx.spawn_in(window, async move |_, cx| {
17048            for (buffer, task) in save_tasks {
17049                let result = task.await;
17050                if result.is_err() {
17051                    let Some(path) = buffer
17052                        .read_with(cx, |buffer, cx| buffer.project_path(cx))
17053                        .ok()
17054                    else {
17055                        continue;
17056                    };
17057                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
17058                        let Some(task) = cx
17059                            .update_window_entity(&workspace, |workspace, window, cx| {
17060                                workspace
17061                                    .open_path_preview(path, None, false, false, false, window, cx)
17062                            })
17063                            .ok()
17064                        else {
17065                            continue;
17066                        };
17067                        task.await.log_err();
17068                    }
17069                }
17070            }
17071        })
17072        .detach();
17073        self.change_selections(None, window, cx, |selections| selections.refresh());
17074    }
17075
17076    pub fn to_pixel_point(
17077        &self,
17078        source: multi_buffer::Anchor,
17079        editor_snapshot: &EditorSnapshot,
17080        window: &mut Window,
17081    ) -> Option<gpui::Point<Pixels>> {
17082        let source_point = source.to_display_point(editor_snapshot);
17083        self.display_to_pixel_point(source_point, editor_snapshot, window)
17084    }
17085
17086    pub fn display_to_pixel_point(
17087        &self,
17088        source: DisplayPoint,
17089        editor_snapshot: &EditorSnapshot,
17090        window: &mut Window,
17091    ) -> Option<gpui::Point<Pixels>> {
17092        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
17093        let text_layout_details = self.text_layout_details(window);
17094        let scroll_top = text_layout_details
17095            .scroll_anchor
17096            .scroll_position(editor_snapshot)
17097            .y;
17098
17099        if source.row().as_f32() < scroll_top.floor() {
17100            return None;
17101        }
17102        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
17103        let source_y = line_height * (source.row().as_f32() - scroll_top);
17104        Some(gpui::Point::new(source_x, source_y))
17105    }
17106
17107    pub fn has_visible_completions_menu(&self) -> bool {
17108        !self.edit_prediction_preview_is_active()
17109            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
17110                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
17111            })
17112    }
17113
17114    pub fn register_addon<T: Addon>(&mut self, instance: T) {
17115        self.addons
17116            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
17117    }
17118
17119    pub fn unregister_addon<T: Addon>(&mut self) {
17120        self.addons.remove(&std::any::TypeId::of::<T>());
17121    }
17122
17123    pub fn addon<T: Addon>(&self) -> Option<&T> {
17124        let type_id = std::any::TypeId::of::<T>();
17125        self.addons
17126            .get(&type_id)
17127            .and_then(|item| item.to_any().downcast_ref::<T>())
17128    }
17129
17130    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
17131        let text_layout_details = self.text_layout_details(window);
17132        let style = &text_layout_details.editor_style;
17133        let font_id = window.text_system().resolve_font(&style.text.font());
17134        let font_size = style.text.font_size.to_pixels(window.rem_size());
17135        let line_height = style.text.line_height_in_pixels(window.rem_size());
17136        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
17137
17138        gpui::Size::new(em_width, line_height)
17139    }
17140
17141    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
17142        self.load_diff_task.clone()
17143    }
17144
17145    fn read_selections_from_db(
17146        &mut self,
17147        item_id: u64,
17148        workspace_id: WorkspaceId,
17149        window: &mut Window,
17150        cx: &mut Context<Editor>,
17151    ) {
17152        if !self.is_singleton(cx)
17153            || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
17154        {
17155            return;
17156        }
17157        let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
17158            return;
17159        };
17160        if selections.is_empty() {
17161            return;
17162        }
17163
17164        let snapshot = self.buffer.read(cx).snapshot(cx);
17165        self.change_selections(None, window, cx, |s| {
17166            s.select_ranges(selections.into_iter().map(|(start, end)| {
17167                snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
17168            }));
17169        });
17170    }
17171}
17172
17173fn insert_extra_newline_brackets(
17174    buffer: &MultiBufferSnapshot,
17175    range: Range<usize>,
17176    language: &language::LanguageScope,
17177) -> bool {
17178    let leading_whitespace_len = buffer
17179        .reversed_chars_at(range.start)
17180        .take_while(|c| c.is_whitespace() && *c != '\n')
17181        .map(|c| c.len_utf8())
17182        .sum::<usize>();
17183    let trailing_whitespace_len = buffer
17184        .chars_at(range.end)
17185        .take_while(|c| c.is_whitespace() && *c != '\n')
17186        .map(|c| c.len_utf8())
17187        .sum::<usize>();
17188    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
17189
17190    language.brackets().any(|(pair, enabled)| {
17191        let pair_start = pair.start.trim_end();
17192        let pair_end = pair.end.trim_start();
17193
17194        enabled
17195            && pair.newline
17196            && buffer.contains_str_at(range.end, pair_end)
17197            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
17198    })
17199}
17200
17201fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
17202    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
17203        [(buffer, range, _)] => (*buffer, range.clone()),
17204        _ => return false,
17205    };
17206    let pair = {
17207        let mut result: Option<BracketMatch> = None;
17208
17209        for pair in buffer
17210            .all_bracket_ranges(range.clone())
17211            .filter(move |pair| {
17212                pair.open_range.start <= range.start && pair.close_range.end >= range.end
17213            })
17214        {
17215            let len = pair.close_range.end - pair.open_range.start;
17216
17217            if let Some(existing) = &result {
17218                let existing_len = existing.close_range.end - existing.open_range.start;
17219                if len > existing_len {
17220                    continue;
17221                }
17222            }
17223
17224            result = Some(pair);
17225        }
17226
17227        result
17228    };
17229    let Some(pair) = pair else {
17230        return false;
17231    };
17232    pair.newline_only
17233        && buffer
17234            .chars_for_range(pair.open_range.end..range.start)
17235            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
17236            .all(|c| c.is_whitespace() && c != '\n')
17237}
17238
17239fn get_uncommitted_diff_for_buffer(
17240    project: &Entity<Project>,
17241    buffers: impl IntoIterator<Item = Entity<Buffer>>,
17242    buffer: Entity<MultiBuffer>,
17243    cx: &mut App,
17244) -> Task<()> {
17245    let mut tasks = Vec::new();
17246    project.update(cx, |project, cx| {
17247        for buffer in buffers {
17248            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
17249        }
17250    });
17251    cx.spawn(async move |cx| {
17252        let diffs = future::join_all(tasks).await;
17253        buffer
17254            .update(cx, |buffer, cx| {
17255                for diff in diffs.into_iter().flatten() {
17256                    buffer.add_diff(diff, cx);
17257                }
17258            })
17259            .ok();
17260    })
17261}
17262
17263fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
17264    let tab_size = tab_size.get() as usize;
17265    let mut width = offset;
17266
17267    for ch in text.chars() {
17268        width += if ch == '\t' {
17269            tab_size - (width % tab_size)
17270        } else {
17271            1
17272        };
17273    }
17274
17275    width - offset
17276}
17277
17278#[cfg(test)]
17279mod tests {
17280    use super::*;
17281
17282    #[test]
17283    fn test_string_size_with_expanded_tabs() {
17284        let nz = |val| NonZeroU32::new(val).unwrap();
17285        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
17286        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
17287        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
17288        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
17289        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
17290        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
17291        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
17292        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
17293    }
17294}
17295
17296/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
17297struct WordBreakingTokenizer<'a> {
17298    input: &'a str,
17299}
17300
17301impl<'a> WordBreakingTokenizer<'a> {
17302    fn new(input: &'a str) -> Self {
17303        Self { input }
17304    }
17305}
17306
17307fn is_char_ideographic(ch: char) -> bool {
17308    use unicode_script::Script::*;
17309    use unicode_script::UnicodeScript;
17310    matches!(ch.script(), Han | Tangut | Yi)
17311}
17312
17313fn is_grapheme_ideographic(text: &str) -> bool {
17314    text.chars().any(is_char_ideographic)
17315}
17316
17317fn is_grapheme_whitespace(text: &str) -> bool {
17318    text.chars().any(|x| x.is_whitespace())
17319}
17320
17321fn should_stay_with_preceding_ideograph(text: &str) -> bool {
17322    text.chars().next().map_or(false, |ch| {
17323        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
17324    })
17325}
17326
17327#[derive(PartialEq, Eq, Debug, Clone, Copy)]
17328enum WordBreakToken<'a> {
17329    Word { token: &'a str, grapheme_len: usize },
17330    InlineWhitespace { token: &'a str, grapheme_len: usize },
17331    Newline,
17332}
17333
17334impl<'a> Iterator for WordBreakingTokenizer<'a> {
17335    /// Yields a span, the count of graphemes in the token, and whether it was
17336    /// whitespace. Note that it also breaks at word boundaries.
17337    type Item = WordBreakToken<'a>;
17338
17339    fn next(&mut self) -> Option<Self::Item> {
17340        use unicode_segmentation::UnicodeSegmentation;
17341        if self.input.is_empty() {
17342            return None;
17343        }
17344
17345        let mut iter = self.input.graphemes(true).peekable();
17346        let mut offset = 0;
17347        let mut grapheme_len = 0;
17348        if let Some(first_grapheme) = iter.next() {
17349            let is_newline = first_grapheme == "\n";
17350            let is_whitespace = is_grapheme_whitespace(first_grapheme);
17351            offset += first_grapheme.len();
17352            grapheme_len += 1;
17353            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
17354                if let Some(grapheme) = iter.peek().copied() {
17355                    if should_stay_with_preceding_ideograph(grapheme) {
17356                        offset += grapheme.len();
17357                        grapheme_len += 1;
17358                    }
17359                }
17360            } else {
17361                let mut words = self.input[offset..].split_word_bound_indices().peekable();
17362                let mut next_word_bound = words.peek().copied();
17363                if next_word_bound.map_or(false, |(i, _)| i == 0) {
17364                    next_word_bound = words.next();
17365                }
17366                while let Some(grapheme) = iter.peek().copied() {
17367                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
17368                        break;
17369                    };
17370                    if is_grapheme_whitespace(grapheme) != is_whitespace
17371                        || (grapheme == "\n") != is_newline
17372                    {
17373                        break;
17374                    };
17375                    offset += grapheme.len();
17376                    grapheme_len += 1;
17377                    iter.next();
17378                }
17379            }
17380            let token = &self.input[..offset];
17381            self.input = &self.input[offset..];
17382            if token == "\n" {
17383                Some(WordBreakToken::Newline)
17384            } else if is_whitespace {
17385                Some(WordBreakToken::InlineWhitespace {
17386                    token,
17387                    grapheme_len,
17388                })
17389            } else {
17390                Some(WordBreakToken::Word {
17391                    token,
17392                    grapheme_len,
17393                })
17394            }
17395        } else {
17396            None
17397        }
17398    }
17399}
17400
17401#[test]
17402fn test_word_breaking_tokenizer() {
17403    let tests: &[(&str, &[WordBreakToken<'static>])] = &[
17404        ("", &[]),
17405        ("  ", &[whitespace("  ", 2)]),
17406        ("Ʒ", &[word("Ʒ", 1)]),
17407        ("Ǽ", &[word("Ǽ", 1)]),
17408        ("", &[word("", 1)]),
17409        ("⋑⋑", &[word("⋑⋑", 2)]),
17410        (
17411            "原理,进而",
17412            &[word("", 1), word("理,", 2), word("", 1), word("", 1)],
17413        ),
17414        (
17415            "hello world",
17416            &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
17417        ),
17418        (
17419            "hello, world",
17420            &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
17421        ),
17422        (
17423            "  hello world",
17424            &[
17425                whitespace("  ", 2),
17426                word("hello", 5),
17427                whitespace(" ", 1),
17428                word("world", 5),
17429            ],
17430        ),
17431        (
17432            "这是什么 \n 钢笔",
17433            &[
17434                word("", 1),
17435                word("", 1),
17436                word("", 1),
17437                word("", 1),
17438                whitespace(" ", 1),
17439                newline(),
17440                whitespace(" ", 1),
17441                word("", 1),
17442                word("", 1),
17443            ],
17444        ),
17445        (" mutton", &[whitespace("", 1), word("mutton", 6)]),
17446    ];
17447
17448    fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
17449        WordBreakToken::Word {
17450            token,
17451            grapheme_len,
17452        }
17453    }
17454
17455    fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
17456        WordBreakToken::InlineWhitespace {
17457            token,
17458            grapheme_len,
17459        }
17460    }
17461
17462    fn newline() -> WordBreakToken<'static> {
17463        WordBreakToken::Newline
17464    }
17465
17466    for (input, result) in tests {
17467        assert_eq!(
17468            WordBreakingTokenizer::new(input)
17469                .collect::<Vec<_>>()
17470                .as_slice(),
17471            *result,
17472        );
17473    }
17474}
17475
17476fn wrap_with_prefix(
17477    line_prefix: String,
17478    unwrapped_text: String,
17479    wrap_column: usize,
17480    tab_size: NonZeroU32,
17481    preserve_existing_whitespace: bool,
17482) -> String {
17483    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
17484    let mut wrapped_text = String::new();
17485    let mut current_line = line_prefix.clone();
17486
17487    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
17488    let mut current_line_len = line_prefix_len;
17489    let mut in_whitespace = false;
17490    for token in tokenizer {
17491        let have_preceding_whitespace = in_whitespace;
17492        match token {
17493            WordBreakToken::Word {
17494                token,
17495                grapheme_len,
17496            } => {
17497                in_whitespace = false;
17498                if current_line_len + grapheme_len > wrap_column
17499                    && current_line_len != line_prefix_len
17500                {
17501                    wrapped_text.push_str(current_line.trim_end());
17502                    wrapped_text.push('\n');
17503                    current_line.truncate(line_prefix.len());
17504                    current_line_len = line_prefix_len;
17505                }
17506                current_line.push_str(token);
17507                current_line_len += grapheme_len;
17508            }
17509            WordBreakToken::InlineWhitespace {
17510                mut token,
17511                mut grapheme_len,
17512            } => {
17513                in_whitespace = true;
17514                if have_preceding_whitespace && !preserve_existing_whitespace {
17515                    continue;
17516                }
17517                if !preserve_existing_whitespace {
17518                    token = " ";
17519                    grapheme_len = 1;
17520                }
17521                if current_line_len + grapheme_len > wrap_column {
17522                    wrapped_text.push_str(current_line.trim_end());
17523                    wrapped_text.push('\n');
17524                    current_line.truncate(line_prefix.len());
17525                    current_line_len = line_prefix_len;
17526                } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
17527                    current_line.push_str(token);
17528                    current_line_len += grapheme_len;
17529                }
17530            }
17531            WordBreakToken::Newline => {
17532                in_whitespace = true;
17533                if preserve_existing_whitespace {
17534                    wrapped_text.push_str(current_line.trim_end());
17535                    wrapped_text.push('\n');
17536                    current_line.truncate(line_prefix.len());
17537                    current_line_len = line_prefix_len;
17538                } else if have_preceding_whitespace {
17539                    continue;
17540                } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
17541                {
17542                    wrapped_text.push_str(current_line.trim_end());
17543                    wrapped_text.push('\n');
17544                    current_line.truncate(line_prefix.len());
17545                    current_line_len = line_prefix_len;
17546                } else if current_line_len != line_prefix_len {
17547                    current_line.push(' ');
17548                    current_line_len += 1;
17549                }
17550            }
17551        }
17552    }
17553
17554    if !current_line.is_empty() {
17555        wrapped_text.push_str(&current_line);
17556    }
17557    wrapped_text
17558}
17559
17560#[test]
17561fn test_wrap_with_prefix() {
17562    assert_eq!(
17563        wrap_with_prefix(
17564            "# ".to_string(),
17565            "abcdefg".to_string(),
17566            4,
17567            NonZeroU32::new(4).unwrap(),
17568            false,
17569        ),
17570        "# abcdefg"
17571    );
17572    assert_eq!(
17573        wrap_with_prefix(
17574            "".to_string(),
17575            "\thello world".to_string(),
17576            8,
17577            NonZeroU32::new(4).unwrap(),
17578            false,
17579        ),
17580        "hello\nworld"
17581    );
17582    assert_eq!(
17583        wrap_with_prefix(
17584            "// ".to_string(),
17585            "xx \nyy zz aa bb cc".to_string(),
17586            12,
17587            NonZeroU32::new(4).unwrap(),
17588            false,
17589        ),
17590        "// xx yy zz\n// aa bb cc"
17591    );
17592    assert_eq!(
17593        wrap_with_prefix(
17594            String::new(),
17595            "这是什么 \n 钢笔".to_string(),
17596            3,
17597            NonZeroU32::new(4).unwrap(),
17598            false,
17599        ),
17600        "这是什\n么 钢\n"
17601    );
17602}
17603
17604pub trait CollaborationHub {
17605    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
17606    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
17607    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
17608}
17609
17610impl CollaborationHub for Entity<Project> {
17611    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
17612        self.read(cx).collaborators()
17613    }
17614
17615    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
17616        self.read(cx).user_store().read(cx).participant_indices()
17617    }
17618
17619    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
17620        let this = self.read(cx);
17621        let user_ids = this.collaborators().values().map(|c| c.user_id);
17622        this.user_store().read_with(cx, |user_store, cx| {
17623            user_store.participant_names(user_ids, cx)
17624        })
17625    }
17626}
17627
17628pub trait SemanticsProvider {
17629    fn hover(
17630        &self,
17631        buffer: &Entity<Buffer>,
17632        position: text::Anchor,
17633        cx: &mut App,
17634    ) -> Option<Task<Vec<project::Hover>>>;
17635
17636    fn inlay_hints(
17637        &self,
17638        buffer_handle: Entity<Buffer>,
17639        range: Range<text::Anchor>,
17640        cx: &mut App,
17641    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
17642
17643    fn resolve_inlay_hint(
17644        &self,
17645        hint: InlayHint,
17646        buffer_handle: Entity<Buffer>,
17647        server_id: LanguageServerId,
17648        cx: &mut App,
17649    ) -> Option<Task<anyhow::Result<InlayHint>>>;
17650
17651    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
17652
17653    fn document_highlights(
17654        &self,
17655        buffer: &Entity<Buffer>,
17656        position: text::Anchor,
17657        cx: &mut App,
17658    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
17659
17660    fn definitions(
17661        &self,
17662        buffer: &Entity<Buffer>,
17663        position: text::Anchor,
17664        kind: GotoDefinitionKind,
17665        cx: &mut App,
17666    ) -> Option<Task<Result<Vec<LocationLink>>>>;
17667
17668    fn range_for_rename(
17669        &self,
17670        buffer: &Entity<Buffer>,
17671        position: text::Anchor,
17672        cx: &mut App,
17673    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
17674
17675    fn perform_rename(
17676        &self,
17677        buffer: &Entity<Buffer>,
17678        position: text::Anchor,
17679        new_name: String,
17680        cx: &mut App,
17681    ) -> Option<Task<Result<ProjectTransaction>>>;
17682}
17683
17684pub trait CompletionProvider {
17685    fn completions(
17686        &self,
17687        buffer: &Entity<Buffer>,
17688        buffer_position: text::Anchor,
17689        trigger: CompletionContext,
17690        window: &mut Window,
17691        cx: &mut Context<Editor>,
17692    ) -> Task<Result<Option<Vec<Completion>>>>;
17693
17694    fn resolve_completions(
17695        &self,
17696        buffer: Entity<Buffer>,
17697        completion_indices: Vec<usize>,
17698        completions: Rc<RefCell<Box<[Completion]>>>,
17699        cx: &mut Context<Editor>,
17700    ) -> Task<Result<bool>>;
17701
17702    fn apply_additional_edits_for_completion(
17703        &self,
17704        _buffer: Entity<Buffer>,
17705        _completions: Rc<RefCell<Box<[Completion]>>>,
17706        _completion_index: usize,
17707        _push_to_history: bool,
17708        _cx: &mut Context<Editor>,
17709    ) -> Task<Result<Option<language::Transaction>>> {
17710        Task::ready(Ok(None))
17711    }
17712
17713    fn is_completion_trigger(
17714        &self,
17715        buffer: &Entity<Buffer>,
17716        position: language::Anchor,
17717        text: &str,
17718        trigger_in_words: bool,
17719        cx: &mut Context<Editor>,
17720    ) -> bool;
17721
17722    fn sort_completions(&self) -> bool {
17723        true
17724    }
17725}
17726
17727pub trait CodeActionProvider {
17728    fn id(&self) -> Arc<str>;
17729
17730    fn code_actions(
17731        &self,
17732        buffer: &Entity<Buffer>,
17733        range: Range<text::Anchor>,
17734        window: &mut Window,
17735        cx: &mut App,
17736    ) -> Task<Result<Vec<CodeAction>>>;
17737
17738    fn apply_code_action(
17739        &self,
17740        buffer_handle: Entity<Buffer>,
17741        action: CodeAction,
17742        excerpt_id: ExcerptId,
17743        push_to_history: bool,
17744        window: &mut Window,
17745        cx: &mut App,
17746    ) -> Task<Result<ProjectTransaction>>;
17747}
17748
17749impl CodeActionProvider for Entity<Project> {
17750    fn id(&self) -> Arc<str> {
17751        "project".into()
17752    }
17753
17754    fn code_actions(
17755        &self,
17756        buffer: &Entity<Buffer>,
17757        range: Range<text::Anchor>,
17758        _window: &mut Window,
17759        cx: &mut App,
17760    ) -> Task<Result<Vec<CodeAction>>> {
17761        self.update(cx, |project, cx| {
17762            let code_lens = project.code_lens(buffer, range.clone(), cx);
17763            let code_actions = project.code_actions(buffer, range, None, cx);
17764            cx.background_spawn(async move {
17765                let (code_lens, code_actions) = join(code_lens, code_actions).await;
17766                Ok(code_lens
17767                    .context("code lens fetch")?
17768                    .into_iter()
17769                    .chain(code_actions.context("code action fetch")?)
17770                    .collect())
17771            })
17772        })
17773    }
17774
17775    fn apply_code_action(
17776        &self,
17777        buffer_handle: Entity<Buffer>,
17778        action: CodeAction,
17779        _excerpt_id: ExcerptId,
17780        push_to_history: bool,
17781        _window: &mut Window,
17782        cx: &mut App,
17783    ) -> Task<Result<ProjectTransaction>> {
17784        self.update(cx, |project, cx| {
17785            project.apply_code_action(buffer_handle, action, push_to_history, cx)
17786        })
17787    }
17788}
17789
17790fn snippet_completions(
17791    project: &Project,
17792    buffer: &Entity<Buffer>,
17793    buffer_position: text::Anchor,
17794    cx: &mut App,
17795) -> Task<Result<Vec<Completion>>> {
17796    let language = buffer.read(cx).language_at(buffer_position);
17797    let language_name = language.as_ref().map(|language| language.lsp_id());
17798    let snippet_store = project.snippets().read(cx);
17799    let snippets = snippet_store.snippets_for(language_name, cx);
17800
17801    if snippets.is_empty() {
17802        return Task::ready(Ok(vec![]));
17803    }
17804    let snapshot = buffer.read(cx).text_snapshot();
17805    let chars: String = snapshot
17806        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
17807        .collect();
17808
17809    let scope = language.map(|language| language.default_scope());
17810    let executor = cx.background_executor().clone();
17811
17812    cx.background_spawn(async move {
17813        let classifier = CharClassifier::new(scope).for_completion(true);
17814        let mut last_word = chars
17815            .chars()
17816            .take_while(|c| classifier.is_word(*c))
17817            .collect::<String>();
17818        last_word = last_word.chars().rev().collect();
17819
17820        if last_word.is_empty() {
17821            return Ok(vec![]);
17822        }
17823
17824        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
17825        let to_lsp = |point: &text::Anchor| {
17826            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
17827            point_to_lsp(end)
17828        };
17829        let lsp_end = to_lsp(&buffer_position);
17830
17831        let candidates = snippets
17832            .iter()
17833            .enumerate()
17834            .flat_map(|(ix, snippet)| {
17835                snippet
17836                    .prefix
17837                    .iter()
17838                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
17839            })
17840            .collect::<Vec<StringMatchCandidate>>();
17841
17842        let mut matches = fuzzy::match_strings(
17843            &candidates,
17844            &last_word,
17845            last_word.chars().any(|c| c.is_uppercase()),
17846            100,
17847            &Default::default(),
17848            executor,
17849        )
17850        .await;
17851
17852        // Remove all candidates where the query's start does not match the start of any word in the candidate
17853        if let Some(query_start) = last_word.chars().next() {
17854            matches.retain(|string_match| {
17855                split_words(&string_match.string).any(|word| {
17856                    // Check that the first codepoint of the word as lowercase matches the first
17857                    // codepoint of the query as lowercase
17858                    word.chars()
17859                        .flat_map(|codepoint| codepoint.to_lowercase())
17860                        .zip(query_start.to_lowercase())
17861                        .all(|(word_cp, query_cp)| word_cp == query_cp)
17862                })
17863            });
17864        }
17865
17866        let matched_strings = matches
17867            .into_iter()
17868            .map(|m| m.string)
17869            .collect::<HashSet<_>>();
17870
17871        let result: Vec<Completion> = snippets
17872            .into_iter()
17873            .filter_map(|snippet| {
17874                let matching_prefix = snippet
17875                    .prefix
17876                    .iter()
17877                    .find(|prefix| matched_strings.contains(*prefix))?;
17878                let start = as_offset - last_word.len();
17879                let start = snapshot.anchor_before(start);
17880                let range = start..buffer_position;
17881                let lsp_start = to_lsp(&start);
17882                let lsp_range = lsp::Range {
17883                    start: lsp_start,
17884                    end: lsp_end,
17885                };
17886                Some(Completion {
17887                    old_range: range,
17888                    new_text: snippet.body.clone(),
17889                    source: CompletionSource::Lsp {
17890                        server_id: LanguageServerId(usize::MAX),
17891                        resolved: true,
17892                        lsp_completion: Box::new(lsp::CompletionItem {
17893                            label: snippet.prefix.first().unwrap().clone(),
17894                            kind: Some(CompletionItemKind::SNIPPET),
17895                            label_details: snippet.description.as_ref().map(|description| {
17896                                lsp::CompletionItemLabelDetails {
17897                                    detail: Some(description.clone()),
17898                                    description: None,
17899                                }
17900                            }),
17901                            insert_text_format: Some(InsertTextFormat::SNIPPET),
17902                            text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
17903                                lsp::InsertReplaceEdit {
17904                                    new_text: snippet.body.clone(),
17905                                    insert: lsp_range,
17906                                    replace: lsp_range,
17907                                },
17908                            )),
17909                            filter_text: Some(snippet.body.clone()),
17910                            sort_text: Some(char::MAX.to_string()),
17911                            ..lsp::CompletionItem::default()
17912                        }),
17913                        lsp_defaults: None,
17914                    },
17915                    label: CodeLabel {
17916                        text: matching_prefix.clone(),
17917                        runs: Vec::new(),
17918                        filter_range: 0..matching_prefix.len(),
17919                    },
17920                    documentation: snippet
17921                        .description
17922                        .clone()
17923                        .map(|description| CompletionDocumentation::SingleLine(description.into())),
17924                    confirm: None,
17925                })
17926            })
17927            .collect();
17928
17929        Ok(result)
17930    })
17931}
17932
17933impl CompletionProvider for Entity<Project> {
17934    fn completions(
17935        &self,
17936        buffer: &Entity<Buffer>,
17937        buffer_position: text::Anchor,
17938        options: CompletionContext,
17939        _window: &mut Window,
17940        cx: &mut Context<Editor>,
17941    ) -> Task<Result<Option<Vec<Completion>>>> {
17942        self.update(cx, |project, cx| {
17943            let snippets = snippet_completions(project, buffer, buffer_position, cx);
17944            let project_completions = project.completions(buffer, buffer_position, options, cx);
17945            cx.background_spawn(async move {
17946                let snippets_completions = snippets.await?;
17947                match project_completions.await? {
17948                    Some(mut completions) => {
17949                        completions.extend(snippets_completions);
17950                        Ok(Some(completions))
17951                    }
17952                    None => {
17953                        if snippets_completions.is_empty() {
17954                            Ok(None)
17955                        } else {
17956                            Ok(Some(snippets_completions))
17957                        }
17958                    }
17959                }
17960            })
17961        })
17962    }
17963
17964    fn resolve_completions(
17965        &self,
17966        buffer: Entity<Buffer>,
17967        completion_indices: Vec<usize>,
17968        completions: Rc<RefCell<Box<[Completion]>>>,
17969        cx: &mut Context<Editor>,
17970    ) -> Task<Result<bool>> {
17971        self.update(cx, |project, cx| {
17972            project.lsp_store().update(cx, |lsp_store, cx| {
17973                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
17974            })
17975        })
17976    }
17977
17978    fn apply_additional_edits_for_completion(
17979        &self,
17980        buffer: Entity<Buffer>,
17981        completions: Rc<RefCell<Box<[Completion]>>>,
17982        completion_index: usize,
17983        push_to_history: bool,
17984        cx: &mut Context<Editor>,
17985    ) -> Task<Result<Option<language::Transaction>>> {
17986        self.update(cx, |project, cx| {
17987            project.lsp_store().update(cx, |lsp_store, cx| {
17988                lsp_store.apply_additional_edits_for_completion(
17989                    buffer,
17990                    completions,
17991                    completion_index,
17992                    push_to_history,
17993                    cx,
17994                )
17995            })
17996        })
17997    }
17998
17999    fn is_completion_trigger(
18000        &self,
18001        buffer: &Entity<Buffer>,
18002        position: language::Anchor,
18003        text: &str,
18004        trigger_in_words: bool,
18005        cx: &mut Context<Editor>,
18006    ) -> bool {
18007        let mut chars = text.chars();
18008        let char = if let Some(char) = chars.next() {
18009            char
18010        } else {
18011            return false;
18012        };
18013        if chars.next().is_some() {
18014            return false;
18015        }
18016
18017        let buffer = buffer.read(cx);
18018        let snapshot = buffer.snapshot();
18019        if !snapshot.settings_at(position, cx).show_completions_on_input {
18020            return false;
18021        }
18022        let classifier = snapshot.char_classifier_at(position).for_completion(true);
18023        if trigger_in_words && classifier.is_word(char) {
18024            return true;
18025        }
18026
18027        buffer.completion_triggers().contains(text)
18028    }
18029}
18030
18031impl SemanticsProvider for Entity<Project> {
18032    fn hover(
18033        &self,
18034        buffer: &Entity<Buffer>,
18035        position: text::Anchor,
18036        cx: &mut App,
18037    ) -> Option<Task<Vec<project::Hover>>> {
18038        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
18039    }
18040
18041    fn document_highlights(
18042        &self,
18043        buffer: &Entity<Buffer>,
18044        position: text::Anchor,
18045        cx: &mut App,
18046    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
18047        Some(self.update(cx, |project, cx| {
18048            project.document_highlights(buffer, position, cx)
18049        }))
18050    }
18051
18052    fn definitions(
18053        &self,
18054        buffer: &Entity<Buffer>,
18055        position: text::Anchor,
18056        kind: GotoDefinitionKind,
18057        cx: &mut App,
18058    ) -> Option<Task<Result<Vec<LocationLink>>>> {
18059        Some(self.update(cx, |project, cx| match kind {
18060            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
18061            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
18062            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
18063            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
18064        }))
18065    }
18066
18067    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
18068        // TODO: make this work for remote projects
18069        self.update(cx, |this, cx| {
18070            buffer.update(cx, |buffer, cx| {
18071                this.any_language_server_supports_inlay_hints(buffer, cx)
18072            })
18073        })
18074    }
18075
18076    fn inlay_hints(
18077        &self,
18078        buffer_handle: Entity<Buffer>,
18079        range: Range<text::Anchor>,
18080        cx: &mut App,
18081    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
18082        Some(self.update(cx, |project, cx| {
18083            project.inlay_hints(buffer_handle, range, cx)
18084        }))
18085    }
18086
18087    fn resolve_inlay_hint(
18088        &self,
18089        hint: InlayHint,
18090        buffer_handle: Entity<Buffer>,
18091        server_id: LanguageServerId,
18092        cx: &mut App,
18093    ) -> Option<Task<anyhow::Result<InlayHint>>> {
18094        Some(self.update(cx, |project, cx| {
18095            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
18096        }))
18097    }
18098
18099    fn range_for_rename(
18100        &self,
18101        buffer: &Entity<Buffer>,
18102        position: text::Anchor,
18103        cx: &mut App,
18104    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
18105        Some(self.update(cx, |project, cx| {
18106            let buffer = buffer.clone();
18107            let task = project.prepare_rename(buffer.clone(), position, cx);
18108            cx.spawn(async move |_, cx| {
18109                Ok(match task.await? {
18110                    PrepareRenameResponse::Success(range) => Some(range),
18111                    PrepareRenameResponse::InvalidPosition => None,
18112                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
18113                        // Fallback on using TreeSitter info to determine identifier range
18114                        buffer.update(cx, |buffer, _| {
18115                            let snapshot = buffer.snapshot();
18116                            let (range, kind) = snapshot.surrounding_word(position);
18117                            if kind != Some(CharKind::Word) {
18118                                return None;
18119                            }
18120                            Some(
18121                                snapshot.anchor_before(range.start)
18122                                    ..snapshot.anchor_after(range.end),
18123                            )
18124                        })?
18125                    }
18126                })
18127            })
18128        }))
18129    }
18130
18131    fn perform_rename(
18132        &self,
18133        buffer: &Entity<Buffer>,
18134        position: text::Anchor,
18135        new_name: String,
18136        cx: &mut App,
18137    ) -> Option<Task<Result<ProjectTransaction>>> {
18138        Some(self.update(cx, |project, cx| {
18139            project.perform_rename(buffer.clone(), position, new_name, cx)
18140        }))
18141    }
18142}
18143
18144fn inlay_hint_settings(
18145    location: Anchor,
18146    snapshot: &MultiBufferSnapshot,
18147    cx: &mut Context<Editor>,
18148) -> InlayHintSettings {
18149    let file = snapshot.file_at(location);
18150    let language = snapshot.language_at(location).map(|l| l.name());
18151    language_settings(language, file, cx).inlay_hints
18152}
18153
18154fn consume_contiguous_rows(
18155    contiguous_row_selections: &mut Vec<Selection<Point>>,
18156    selection: &Selection<Point>,
18157    display_map: &DisplaySnapshot,
18158    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
18159) -> (MultiBufferRow, MultiBufferRow) {
18160    contiguous_row_selections.push(selection.clone());
18161    let start_row = MultiBufferRow(selection.start.row);
18162    let mut end_row = ending_row(selection, display_map);
18163
18164    while let Some(next_selection) = selections.peek() {
18165        if next_selection.start.row <= end_row.0 {
18166            end_row = ending_row(next_selection, display_map);
18167            contiguous_row_selections.push(selections.next().unwrap().clone());
18168        } else {
18169            break;
18170        }
18171    }
18172    (start_row, end_row)
18173}
18174
18175fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
18176    if next_selection.end.column > 0 || next_selection.is_empty() {
18177        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
18178    } else {
18179        MultiBufferRow(next_selection.end.row)
18180    }
18181}
18182
18183impl EditorSnapshot {
18184    pub fn remote_selections_in_range<'a>(
18185        &'a self,
18186        range: &'a Range<Anchor>,
18187        collaboration_hub: &dyn CollaborationHub,
18188        cx: &'a App,
18189    ) -> impl 'a + Iterator<Item = RemoteSelection> {
18190        let participant_names = collaboration_hub.user_names(cx);
18191        let participant_indices = collaboration_hub.user_participant_indices(cx);
18192        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
18193        let collaborators_by_replica_id = collaborators_by_peer_id
18194            .iter()
18195            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
18196            .collect::<HashMap<_, _>>();
18197        self.buffer_snapshot
18198            .selections_in_range(range, false)
18199            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
18200                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
18201                let participant_index = participant_indices.get(&collaborator.user_id).copied();
18202                let user_name = participant_names.get(&collaborator.user_id).cloned();
18203                Some(RemoteSelection {
18204                    replica_id,
18205                    selection,
18206                    cursor_shape,
18207                    line_mode,
18208                    participant_index,
18209                    peer_id: collaborator.peer_id,
18210                    user_name,
18211                })
18212            })
18213    }
18214
18215    pub fn hunks_for_ranges(
18216        &self,
18217        ranges: impl IntoIterator<Item = Range<Point>>,
18218    ) -> Vec<MultiBufferDiffHunk> {
18219        let mut hunks = Vec::new();
18220        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
18221            HashMap::default();
18222        for query_range in ranges {
18223            let query_rows =
18224                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
18225            for hunk in self.buffer_snapshot.diff_hunks_in_range(
18226                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
18227            ) {
18228                // Include deleted hunks that are adjacent to the query range, because
18229                // otherwise they would be missed.
18230                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
18231                if hunk.status().is_deleted() {
18232                    intersects_range |= hunk.row_range.start == query_rows.end;
18233                    intersects_range |= hunk.row_range.end == query_rows.start;
18234                }
18235                if intersects_range {
18236                    if !processed_buffer_rows
18237                        .entry(hunk.buffer_id)
18238                        .or_default()
18239                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
18240                    {
18241                        continue;
18242                    }
18243                    hunks.push(hunk);
18244                }
18245            }
18246        }
18247
18248        hunks
18249    }
18250
18251    fn display_diff_hunks_for_rows<'a>(
18252        &'a self,
18253        display_rows: Range<DisplayRow>,
18254        folded_buffers: &'a HashSet<BufferId>,
18255    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
18256        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
18257        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
18258
18259        self.buffer_snapshot
18260            .diff_hunks_in_range(buffer_start..buffer_end)
18261            .filter_map(|hunk| {
18262                if folded_buffers.contains(&hunk.buffer_id) {
18263                    return None;
18264                }
18265
18266                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
18267                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
18268
18269                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
18270                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
18271
18272                let display_hunk = if hunk_display_start.column() != 0 {
18273                    DisplayDiffHunk::Folded {
18274                        display_row: hunk_display_start.row(),
18275                    }
18276                } else {
18277                    let mut end_row = hunk_display_end.row();
18278                    if hunk_display_end.column() > 0 {
18279                        end_row.0 += 1;
18280                    }
18281                    let is_created_file = hunk.is_created_file();
18282                    DisplayDiffHunk::Unfolded {
18283                        status: hunk.status(),
18284                        diff_base_byte_range: hunk.diff_base_byte_range,
18285                        display_row_range: hunk_display_start.row()..end_row,
18286                        multi_buffer_range: Anchor::range_in_buffer(
18287                            hunk.excerpt_id,
18288                            hunk.buffer_id,
18289                            hunk.buffer_range,
18290                        ),
18291                        is_created_file,
18292                    }
18293                };
18294
18295                Some(display_hunk)
18296            })
18297    }
18298
18299    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
18300        self.display_snapshot.buffer_snapshot.language_at(position)
18301    }
18302
18303    pub fn is_focused(&self) -> bool {
18304        self.is_focused
18305    }
18306
18307    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
18308        self.placeholder_text.as_ref()
18309    }
18310
18311    pub fn scroll_position(&self) -> gpui::Point<f32> {
18312        self.scroll_anchor.scroll_position(&self.display_snapshot)
18313    }
18314
18315    fn gutter_dimensions(
18316        &self,
18317        font_id: FontId,
18318        font_size: Pixels,
18319        max_line_number_width: Pixels,
18320        cx: &App,
18321    ) -> Option<GutterDimensions> {
18322        if !self.show_gutter {
18323            return None;
18324        }
18325
18326        let descent = cx.text_system().descent(font_id, font_size);
18327        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
18328        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
18329
18330        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
18331            matches!(
18332                ProjectSettings::get_global(cx).git.git_gutter,
18333                Some(GitGutterSetting::TrackedFiles)
18334            )
18335        });
18336        let gutter_settings = EditorSettings::get_global(cx).gutter;
18337        let show_line_numbers = self
18338            .show_line_numbers
18339            .unwrap_or(gutter_settings.line_numbers);
18340        let line_gutter_width = if show_line_numbers {
18341            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
18342            let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
18343            max_line_number_width.max(min_width_for_number_on_gutter)
18344        } else {
18345            0.0.into()
18346        };
18347
18348        let show_code_actions = self
18349            .show_code_actions
18350            .unwrap_or(gutter_settings.code_actions);
18351
18352        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
18353        let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
18354
18355        let git_blame_entries_width =
18356            self.git_blame_gutter_max_author_length
18357                .map(|max_author_length| {
18358                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
18359
18360                    /// The number of characters to dedicate to gaps and margins.
18361                    const SPACING_WIDTH: usize = 4;
18362
18363                    let max_char_count = max_author_length
18364                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
18365                        + ::git::SHORT_SHA_LENGTH
18366                        + MAX_RELATIVE_TIMESTAMP.len()
18367                        + SPACING_WIDTH;
18368
18369                    em_advance * max_char_count
18370                });
18371
18372        let is_singleton = self.buffer_snapshot.is_singleton();
18373
18374        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
18375        left_padding += if !is_singleton {
18376            em_width * 4.0
18377        } else if show_code_actions || show_runnables || show_breakpoints {
18378            em_width * 3.0
18379        } else if show_git_gutter && show_line_numbers {
18380            em_width * 2.0
18381        } else if show_git_gutter || show_line_numbers {
18382            em_width
18383        } else {
18384            px(0.)
18385        };
18386
18387        let shows_folds = is_singleton && gutter_settings.folds;
18388
18389        let right_padding = if shows_folds && show_line_numbers {
18390            em_width * 4.0
18391        } else if shows_folds || (!is_singleton && show_line_numbers) {
18392            em_width * 3.0
18393        } else if show_line_numbers {
18394            em_width
18395        } else {
18396            px(0.)
18397        };
18398
18399        Some(GutterDimensions {
18400            left_padding,
18401            right_padding,
18402            width: line_gutter_width + left_padding + right_padding,
18403            margin: -descent,
18404            git_blame_entries_width,
18405        })
18406    }
18407
18408    pub fn render_crease_toggle(
18409        &self,
18410        buffer_row: MultiBufferRow,
18411        row_contains_cursor: bool,
18412        editor: Entity<Editor>,
18413        window: &mut Window,
18414        cx: &mut App,
18415    ) -> Option<AnyElement> {
18416        let folded = self.is_line_folded(buffer_row);
18417        let mut is_foldable = false;
18418
18419        if let Some(crease) = self
18420            .crease_snapshot
18421            .query_row(buffer_row, &self.buffer_snapshot)
18422        {
18423            is_foldable = true;
18424            match crease {
18425                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
18426                    if let Some(render_toggle) = render_toggle {
18427                        let toggle_callback =
18428                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
18429                                if folded {
18430                                    editor.update(cx, |editor, cx| {
18431                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
18432                                    });
18433                                } else {
18434                                    editor.update(cx, |editor, cx| {
18435                                        editor.unfold_at(
18436                                            &crate::UnfoldAt { buffer_row },
18437                                            window,
18438                                            cx,
18439                                        )
18440                                    });
18441                                }
18442                            });
18443                        return Some((render_toggle)(
18444                            buffer_row,
18445                            folded,
18446                            toggle_callback,
18447                            window,
18448                            cx,
18449                        ));
18450                    }
18451                }
18452            }
18453        }
18454
18455        is_foldable |= self.starts_indent(buffer_row);
18456
18457        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
18458            Some(
18459                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
18460                    .toggle_state(folded)
18461                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
18462                        if folded {
18463                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
18464                        } else {
18465                            this.fold_at(&FoldAt { buffer_row }, window, cx);
18466                        }
18467                    }))
18468                    .into_any_element(),
18469            )
18470        } else {
18471            None
18472        }
18473    }
18474
18475    pub fn render_crease_trailer(
18476        &self,
18477        buffer_row: MultiBufferRow,
18478        window: &mut Window,
18479        cx: &mut App,
18480    ) -> Option<AnyElement> {
18481        let folded = self.is_line_folded(buffer_row);
18482        if let Crease::Inline { render_trailer, .. } = self
18483            .crease_snapshot
18484            .query_row(buffer_row, &self.buffer_snapshot)?
18485        {
18486            let render_trailer = render_trailer.as_ref()?;
18487            Some(render_trailer(buffer_row, folded, window, cx))
18488        } else {
18489            None
18490        }
18491    }
18492}
18493
18494impl Deref for EditorSnapshot {
18495    type Target = DisplaySnapshot;
18496
18497    fn deref(&self) -> &Self::Target {
18498        &self.display_snapshot
18499    }
18500}
18501
18502#[derive(Clone, Debug, PartialEq, Eq)]
18503pub enum EditorEvent {
18504    InputIgnored {
18505        text: Arc<str>,
18506    },
18507    InputHandled {
18508        utf16_range_to_replace: Option<Range<isize>>,
18509        text: Arc<str>,
18510    },
18511    ExcerptsAdded {
18512        buffer: Entity<Buffer>,
18513        predecessor: ExcerptId,
18514        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
18515    },
18516    ExcerptsRemoved {
18517        ids: Vec<ExcerptId>,
18518    },
18519    BufferFoldToggled {
18520        ids: Vec<ExcerptId>,
18521        folded: bool,
18522    },
18523    ExcerptsEdited {
18524        ids: Vec<ExcerptId>,
18525    },
18526    ExcerptsExpanded {
18527        ids: Vec<ExcerptId>,
18528    },
18529    BufferEdited,
18530    Edited {
18531        transaction_id: clock::Lamport,
18532    },
18533    Reparsed(BufferId),
18534    Focused,
18535    FocusedIn,
18536    Blurred,
18537    DirtyChanged,
18538    Saved,
18539    TitleChanged,
18540    DiffBaseChanged,
18541    SelectionsChanged {
18542        local: bool,
18543    },
18544    ScrollPositionChanged {
18545        local: bool,
18546        autoscroll: bool,
18547    },
18548    Closed,
18549    TransactionUndone {
18550        transaction_id: clock::Lamport,
18551    },
18552    TransactionBegun {
18553        transaction_id: clock::Lamport,
18554    },
18555    Reloaded,
18556    CursorShapeChanged,
18557}
18558
18559impl EventEmitter<EditorEvent> for Editor {}
18560
18561impl Focusable for Editor {
18562    fn focus_handle(&self, _cx: &App) -> FocusHandle {
18563        self.focus_handle.clone()
18564    }
18565}
18566
18567impl Render for Editor {
18568    fn render(&mut self, _: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
18569        let settings = ThemeSettings::get_global(cx);
18570
18571        let mut text_style = match self.mode {
18572            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
18573                color: cx.theme().colors().editor_foreground,
18574                font_family: settings.ui_font.family.clone(),
18575                font_features: settings.ui_font.features.clone(),
18576                font_fallbacks: settings.ui_font.fallbacks.clone(),
18577                font_size: rems(0.875).into(),
18578                font_weight: settings.ui_font.weight,
18579                line_height: relative(settings.buffer_line_height.value()),
18580                ..Default::default()
18581            },
18582            EditorMode::Full => TextStyle {
18583                color: cx.theme().colors().editor_foreground,
18584                font_family: settings.buffer_font.family.clone(),
18585                font_features: settings.buffer_font.features.clone(),
18586                font_fallbacks: settings.buffer_font.fallbacks.clone(),
18587                font_size: settings.buffer_font_size(cx).into(),
18588                font_weight: settings.buffer_font.weight,
18589                line_height: relative(settings.buffer_line_height.value()),
18590                ..Default::default()
18591            },
18592        };
18593        if let Some(text_style_refinement) = &self.text_style_refinement {
18594            text_style.refine(text_style_refinement)
18595        }
18596
18597        let background = match self.mode {
18598            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
18599            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
18600            EditorMode::Full => cx.theme().colors().editor_background,
18601        };
18602
18603        EditorElement::new(
18604            &cx.entity(),
18605            EditorStyle {
18606                background,
18607                local_player: cx.theme().players().local(),
18608                text: text_style,
18609                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
18610                syntax: cx.theme().syntax().clone(),
18611                status: cx.theme().status().clone(),
18612                inlay_hints_style: make_inlay_hints_style(cx),
18613                inline_completion_styles: make_suggestion_styles(cx),
18614                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
18615            },
18616        )
18617    }
18618}
18619
18620impl EntityInputHandler for Editor {
18621    fn text_for_range(
18622        &mut self,
18623        range_utf16: Range<usize>,
18624        adjusted_range: &mut Option<Range<usize>>,
18625        _: &mut Window,
18626        cx: &mut Context<Self>,
18627    ) -> Option<String> {
18628        let snapshot = self.buffer.read(cx).read(cx);
18629        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
18630        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
18631        if (start.0..end.0) != range_utf16 {
18632            adjusted_range.replace(start.0..end.0);
18633        }
18634        Some(snapshot.text_for_range(start..end).collect())
18635    }
18636
18637    fn selected_text_range(
18638        &mut self,
18639        ignore_disabled_input: bool,
18640        _: &mut Window,
18641        cx: &mut Context<Self>,
18642    ) -> Option<UTF16Selection> {
18643        // Prevent the IME menu from appearing when holding down an alphabetic key
18644        // while input is disabled.
18645        if !ignore_disabled_input && !self.input_enabled {
18646            return None;
18647        }
18648
18649        let selection = self.selections.newest::<OffsetUtf16>(cx);
18650        let range = selection.range();
18651
18652        Some(UTF16Selection {
18653            range: range.start.0..range.end.0,
18654            reversed: selection.reversed,
18655        })
18656    }
18657
18658    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
18659        let snapshot = self.buffer.read(cx).read(cx);
18660        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
18661        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
18662    }
18663
18664    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
18665        self.clear_highlights::<InputComposition>(cx);
18666        self.ime_transaction.take();
18667    }
18668
18669    fn replace_text_in_range(
18670        &mut self,
18671        range_utf16: Option<Range<usize>>,
18672        text: &str,
18673        window: &mut Window,
18674        cx: &mut Context<Self>,
18675    ) {
18676        if !self.input_enabled {
18677            cx.emit(EditorEvent::InputIgnored { text: text.into() });
18678            return;
18679        }
18680
18681        self.transact(window, cx, |this, window, cx| {
18682            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
18683                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
18684                Some(this.selection_replacement_ranges(range_utf16, cx))
18685            } else {
18686                this.marked_text_ranges(cx)
18687            };
18688
18689            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
18690                let newest_selection_id = this.selections.newest_anchor().id;
18691                this.selections
18692                    .all::<OffsetUtf16>(cx)
18693                    .iter()
18694                    .zip(ranges_to_replace.iter())
18695                    .find_map(|(selection, range)| {
18696                        if selection.id == newest_selection_id {
18697                            Some(
18698                                (range.start.0 as isize - selection.head().0 as isize)
18699                                    ..(range.end.0 as isize - selection.head().0 as isize),
18700                            )
18701                        } else {
18702                            None
18703                        }
18704                    })
18705            });
18706
18707            cx.emit(EditorEvent::InputHandled {
18708                utf16_range_to_replace: range_to_replace,
18709                text: text.into(),
18710            });
18711
18712            if let Some(new_selected_ranges) = new_selected_ranges {
18713                this.change_selections(None, window, cx, |selections| {
18714                    selections.select_ranges(new_selected_ranges)
18715                });
18716                this.backspace(&Default::default(), window, cx);
18717            }
18718
18719            this.handle_input(text, window, cx);
18720        });
18721
18722        if let Some(transaction) = self.ime_transaction {
18723            self.buffer.update(cx, |buffer, cx| {
18724                buffer.group_until_transaction(transaction, cx);
18725            });
18726        }
18727
18728        self.unmark_text(window, cx);
18729    }
18730
18731    fn replace_and_mark_text_in_range(
18732        &mut self,
18733        range_utf16: Option<Range<usize>>,
18734        text: &str,
18735        new_selected_range_utf16: Option<Range<usize>>,
18736        window: &mut Window,
18737        cx: &mut Context<Self>,
18738    ) {
18739        if !self.input_enabled {
18740            return;
18741        }
18742
18743        let transaction = self.transact(window, cx, |this, window, cx| {
18744            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
18745                let snapshot = this.buffer.read(cx).read(cx);
18746                if let Some(relative_range_utf16) = range_utf16.as_ref() {
18747                    for marked_range in &mut marked_ranges {
18748                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
18749                        marked_range.start.0 += relative_range_utf16.start;
18750                        marked_range.start =
18751                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
18752                        marked_range.end =
18753                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
18754                    }
18755                }
18756                Some(marked_ranges)
18757            } else if let Some(range_utf16) = range_utf16 {
18758                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
18759                Some(this.selection_replacement_ranges(range_utf16, cx))
18760            } else {
18761                None
18762            };
18763
18764            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
18765                let newest_selection_id = this.selections.newest_anchor().id;
18766                this.selections
18767                    .all::<OffsetUtf16>(cx)
18768                    .iter()
18769                    .zip(ranges_to_replace.iter())
18770                    .find_map(|(selection, range)| {
18771                        if selection.id == newest_selection_id {
18772                            Some(
18773                                (range.start.0 as isize - selection.head().0 as isize)
18774                                    ..(range.end.0 as isize - selection.head().0 as isize),
18775                            )
18776                        } else {
18777                            None
18778                        }
18779                    })
18780            });
18781
18782            cx.emit(EditorEvent::InputHandled {
18783                utf16_range_to_replace: range_to_replace,
18784                text: text.into(),
18785            });
18786
18787            if let Some(ranges) = ranges_to_replace {
18788                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
18789            }
18790
18791            let marked_ranges = {
18792                let snapshot = this.buffer.read(cx).read(cx);
18793                this.selections
18794                    .disjoint_anchors()
18795                    .iter()
18796                    .map(|selection| {
18797                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
18798                    })
18799                    .collect::<Vec<_>>()
18800            };
18801
18802            if text.is_empty() {
18803                this.unmark_text(window, cx);
18804            } else {
18805                this.highlight_text::<InputComposition>(
18806                    marked_ranges.clone(),
18807                    HighlightStyle {
18808                        underline: Some(UnderlineStyle {
18809                            thickness: px(1.),
18810                            color: None,
18811                            wavy: false,
18812                        }),
18813                        ..Default::default()
18814                    },
18815                    cx,
18816                );
18817            }
18818
18819            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
18820            let use_autoclose = this.use_autoclose;
18821            let use_auto_surround = this.use_auto_surround;
18822            this.set_use_autoclose(false);
18823            this.set_use_auto_surround(false);
18824            this.handle_input(text, window, cx);
18825            this.set_use_autoclose(use_autoclose);
18826            this.set_use_auto_surround(use_auto_surround);
18827
18828            if let Some(new_selected_range) = new_selected_range_utf16 {
18829                let snapshot = this.buffer.read(cx).read(cx);
18830                let new_selected_ranges = marked_ranges
18831                    .into_iter()
18832                    .map(|marked_range| {
18833                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
18834                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
18835                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
18836                        snapshot.clip_offset_utf16(new_start, Bias::Left)
18837                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
18838                    })
18839                    .collect::<Vec<_>>();
18840
18841                drop(snapshot);
18842                this.change_selections(None, window, cx, |selections| {
18843                    selections.select_ranges(new_selected_ranges)
18844                });
18845            }
18846        });
18847
18848        self.ime_transaction = self.ime_transaction.or(transaction);
18849        if let Some(transaction) = self.ime_transaction {
18850            self.buffer.update(cx, |buffer, cx| {
18851                buffer.group_until_transaction(transaction, cx);
18852            });
18853        }
18854
18855        if self.text_highlights::<InputComposition>(cx).is_none() {
18856            self.ime_transaction.take();
18857        }
18858    }
18859
18860    fn bounds_for_range(
18861        &mut self,
18862        range_utf16: Range<usize>,
18863        element_bounds: gpui::Bounds<Pixels>,
18864        window: &mut Window,
18865        cx: &mut Context<Self>,
18866    ) -> Option<gpui::Bounds<Pixels>> {
18867        let text_layout_details = self.text_layout_details(window);
18868        let gpui::Size {
18869            width: em_width,
18870            height: line_height,
18871        } = self.character_size(window);
18872
18873        let snapshot = self.snapshot(window, cx);
18874        let scroll_position = snapshot.scroll_position();
18875        let scroll_left = scroll_position.x * em_width;
18876
18877        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
18878        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
18879            + self.gutter_dimensions.width
18880            + self.gutter_dimensions.margin;
18881        let y = line_height * (start.row().as_f32() - scroll_position.y);
18882
18883        Some(Bounds {
18884            origin: element_bounds.origin + point(x, y),
18885            size: size(em_width, line_height),
18886        })
18887    }
18888
18889    fn character_index_for_point(
18890        &mut self,
18891        point: gpui::Point<Pixels>,
18892        _window: &mut Window,
18893        _cx: &mut Context<Self>,
18894    ) -> Option<usize> {
18895        let position_map = self.last_position_map.as_ref()?;
18896        if !position_map.text_hitbox.contains(&point) {
18897            return None;
18898        }
18899        let display_point = position_map.point_for_position(point).previous_valid;
18900        let anchor = position_map
18901            .snapshot
18902            .display_point_to_anchor(display_point, Bias::Left);
18903        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
18904        Some(utf16_offset.0)
18905    }
18906}
18907
18908trait SelectionExt {
18909    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
18910    fn spanned_rows(
18911        &self,
18912        include_end_if_at_line_start: bool,
18913        map: &DisplaySnapshot,
18914    ) -> Range<MultiBufferRow>;
18915}
18916
18917impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
18918    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
18919        let start = self
18920            .start
18921            .to_point(&map.buffer_snapshot)
18922            .to_display_point(map);
18923        let end = self
18924            .end
18925            .to_point(&map.buffer_snapshot)
18926            .to_display_point(map);
18927        if self.reversed {
18928            end..start
18929        } else {
18930            start..end
18931        }
18932    }
18933
18934    fn spanned_rows(
18935        &self,
18936        include_end_if_at_line_start: bool,
18937        map: &DisplaySnapshot,
18938    ) -> Range<MultiBufferRow> {
18939        let start = self.start.to_point(&map.buffer_snapshot);
18940        let mut end = self.end.to_point(&map.buffer_snapshot);
18941        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
18942            end.row -= 1;
18943        }
18944
18945        let buffer_start = map.prev_line_boundary(start).0;
18946        let buffer_end = map.next_line_boundary(end).0;
18947        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
18948    }
18949}
18950
18951impl<T: InvalidationRegion> InvalidationStack<T> {
18952    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
18953    where
18954        S: Clone + ToOffset,
18955    {
18956        while let Some(region) = self.last() {
18957            let all_selections_inside_invalidation_ranges =
18958                if selections.len() == region.ranges().len() {
18959                    selections
18960                        .iter()
18961                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
18962                        .all(|(selection, invalidation_range)| {
18963                            let head = selection.head().to_offset(buffer);
18964                            invalidation_range.start <= head && invalidation_range.end >= head
18965                        })
18966                } else {
18967                    false
18968                };
18969
18970            if all_selections_inside_invalidation_ranges {
18971                break;
18972            } else {
18973                self.pop();
18974            }
18975        }
18976    }
18977}
18978
18979impl<T> Default for InvalidationStack<T> {
18980    fn default() -> Self {
18981        Self(Default::default())
18982    }
18983}
18984
18985impl<T> Deref for InvalidationStack<T> {
18986    type Target = Vec<T>;
18987
18988    fn deref(&self) -> &Self::Target {
18989        &self.0
18990    }
18991}
18992
18993impl<T> DerefMut for InvalidationStack<T> {
18994    fn deref_mut(&mut self) -> &mut Self::Target {
18995        &mut self.0
18996    }
18997}
18998
18999impl InvalidationRegion for SnippetState {
19000    fn ranges(&self) -> &[Range<Anchor>] {
19001        &self.ranges[self.active_index]
19002    }
19003}
19004
19005pub fn diagnostic_block_renderer(
19006    diagnostic: Diagnostic,
19007    max_message_rows: Option<u8>,
19008    allow_closing: bool,
19009) -> RenderBlock {
19010    let (text_without_backticks, code_ranges) =
19011        highlight_diagnostic_message(&diagnostic, max_message_rows);
19012
19013    Arc::new(move |cx: &mut BlockContext| {
19014        let group_id: SharedString = cx.block_id.to_string().into();
19015
19016        let mut text_style = cx.window.text_style().clone();
19017        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
19018        let theme_settings = ThemeSettings::get_global(cx);
19019        text_style.font_family = theme_settings.buffer_font.family.clone();
19020        text_style.font_style = theme_settings.buffer_font.style;
19021        text_style.font_features = theme_settings.buffer_font.features.clone();
19022        text_style.font_weight = theme_settings.buffer_font.weight;
19023
19024        let multi_line_diagnostic = diagnostic.message.contains('\n');
19025
19026        let buttons = |diagnostic: &Diagnostic| {
19027            if multi_line_diagnostic {
19028                v_flex()
19029            } else {
19030                h_flex()
19031            }
19032            .when(allow_closing, |div| {
19033                div.children(diagnostic.is_primary.then(|| {
19034                    IconButton::new("close-block", IconName::XCircle)
19035                        .icon_color(Color::Muted)
19036                        .size(ButtonSize::Compact)
19037                        .style(ButtonStyle::Transparent)
19038                        .visible_on_hover(group_id.clone())
19039                        .on_click(move |_click, window, cx| {
19040                            window.dispatch_action(Box::new(Cancel), cx)
19041                        })
19042                        .tooltip(|window, cx| {
19043                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
19044                        })
19045                }))
19046            })
19047            .child(
19048                IconButton::new("copy-block", IconName::Copy)
19049                    .icon_color(Color::Muted)
19050                    .size(ButtonSize::Compact)
19051                    .style(ButtonStyle::Transparent)
19052                    .visible_on_hover(group_id.clone())
19053                    .on_click({
19054                        let message = diagnostic.message.clone();
19055                        move |_click, _, cx| {
19056                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
19057                        }
19058                    })
19059                    .tooltip(Tooltip::text("Copy diagnostic message")),
19060            )
19061        };
19062
19063        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
19064            AvailableSpace::min_size(),
19065            cx.window,
19066            cx.app,
19067        );
19068
19069        h_flex()
19070            .id(cx.block_id)
19071            .group(group_id.clone())
19072            .relative()
19073            .size_full()
19074            .block_mouse_down()
19075            .pl(cx.gutter_dimensions.width)
19076            .w(cx.max_width - cx.gutter_dimensions.full_width())
19077            .child(
19078                div()
19079                    .flex()
19080                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
19081                    .flex_shrink(),
19082            )
19083            .child(buttons(&diagnostic))
19084            .child(div().flex().flex_shrink_0().child(
19085                StyledText::new(text_without_backticks.clone()).with_default_highlights(
19086                    &text_style,
19087                    code_ranges.iter().map(|range| {
19088                        (
19089                            range.clone(),
19090                            HighlightStyle {
19091                                font_weight: Some(FontWeight::BOLD),
19092                                ..Default::default()
19093                            },
19094                        )
19095                    }),
19096                ),
19097            ))
19098            .into_any_element()
19099    })
19100}
19101
19102fn inline_completion_edit_text(
19103    current_snapshot: &BufferSnapshot,
19104    edits: &[(Range<Anchor>, String)],
19105    edit_preview: &EditPreview,
19106    include_deletions: bool,
19107    cx: &App,
19108) -> HighlightedText {
19109    let edits = edits
19110        .iter()
19111        .map(|(anchor, text)| {
19112            (
19113                anchor.start.text_anchor..anchor.end.text_anchor,
19114                text.clone(),
19115            )
19116        })
19117        .collect::<Vec<_>>();
19118
19119    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
19120}
19121
19122pub fn highlight_diagnostic_message(
19123    diagnostic: &Diagnostic,
19124    mut max_message_rows: Option<u8>,
19125) -> (SharedString, Vec<Range<usize>>) {
19126    let mut text_without_backticks = String::new();
19127    let mut code_ranges = Vec::new();
19128
19129    if let Some(source) = &diagnostic.source {
19130        text_without_backticks.push_str(source);
19131        code_ranges.push(0..source.len());
19132        text_without_backticks.push_str(": ");
19133    }
19134
19135    let mut prev_offset = 0;
19136    let mut in_code_block = false;
19137    let has_row_limit = max_message_rows.is_some();
19138    let mut newline_indices = diagnostic
19139        .message
19140        .match_indices('\n')
19141        .filter(|_| has_row_limit)
19142        .map(|(ix, _)| ix)
19143        .fuse()
19144        .peekable();
19145
19146    for (quote_ix, _) in diagnostic
19147        .message
19148        .match_indices('`')
19149        .chain([(diagnostic.message.len(), "")])
19150    {
19151        let mut first_newline_ix = None;
19152        let mut last_newline_ix = None;
19153        while let Some(newline_ix) = newline_indices.peek() {
19154            if *newline_ix < quote_ix {
19155                if first_newline_ix.is_none() {
19156                    first_newline_ix = Some(*newline_ix);
19157                }
19158                last_newline_ix = Some(*newline_ix);
19159
19160                if let Some(rows_left) = &mut max_message_rows {
19161                    if *rows_left == 0 {
19162                        break;
19163                    } else {
19164                        *rows_left -= 1;
19165                    }
19166                }
19167                let _ = newline_indices.next();
19168            } else {
19169                break;
19170            }
19171        }
19172        let prev_len = text_without_backticks.len();
19173        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
19174        text_without_backticks.push_str(new_text);
19175        if in_code_block {
19176            code_ranges.push(prev_len..text_without_backticks.len());
19177        }
19178        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
19179        in_code_block = !in_code_block;
19180        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
19181            text_without_backticks.push_str("...");
19182            break;
19183        }
19184    }
19185
19186    (text_without_backticks.into(), code_ranges)
19187}
19188
19189fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
19190    match severity {
19191        DiagnosticSeverity::ERROR => colors.error,
19192        DiagnosticSeverity::WARNING => colors.warning,
19193        DiagnosticSeverity::INFORMATION => colors.info,
19194        DiagnosticSeverity::HINT => colors.info,
19195        _ => colors.ignored,
19196    }
19197}
19198
19199pub fn styled_runs_for_code_label<'a>(
19200    label: &'a CodeLabel,
19201    syntax_theme: &'a theme::SyntaxTheme,
19202) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
19203    let fade_out = HighlightStyle {
19204        fade_out: Some(0.35),
19205        ..Default::default()
19206    };
19207
19208    let mut prev_end = label.filter_range.end;
19209    label
19210        .runs
19211        .iter()
19212        .enumerate()
19213        .flat_map(move |(ix, (range, highlight_id))| {
19214            let style = if let Some(style) = highlight_id.style(syntax_theme) {
19215                style
19216            } else {
19217                return Default::default();
19218            };
19219            let mut muted_style = style;
19220            muted_style.highlight(fade_out);
19221
19222            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
19223            if range.start >= label.filter_range.end {
19224                if range.start > prev_end {
19225                    runs.push((prev_end..range.start, fade_out));
19226                }
19227                runs.push((range.clone(), muted_style));
19228            } else if range.end <= label.filter_range.end {
19229                runs.push((range.clone(), style));
19230            } else {
19231                runs.push((range.start..label.filter_range.end, style));
19232                runs.push((label.filter_range.end..range.end, muted_style));
19233            }
19234            prev_end = cmp::max(prev_end, range.end);
19235
19236            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
19237                runs.push((prev_end..label.text.len(), fade_out));
19238            }
19239
19240            runs
19241        })
19242}
19243
19244pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
19245    let mut prev_index = 0;
19246    let mut prev_codepoint: Option<char> = None;
19247    text.char_indices()
19248        .chain([(text.len(), '\0')])
19249        .filter_map(move |(index, codepoint)| {
19250            let prev_codepoint = prev_codepoint.replace(codepoint)?;
19251            let is_boundary = index == text.len()
19252                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
19253                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
19254            if is_boundary {
19255                let chunk = &text[prev_index..index];
19256                prev_index = index;
19257                Some(chunk)
19258            } else {
19259                None
19260            }
19261        })
19262}
19263
19264pub trait RangeToAnchorExt: Sized {
19265    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
19266
19267    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
19268        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
19269        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
19270    }
19271}
19272
19273impl<T: ToOffset> RangeToAnchorExt for Range<T> {
19274    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
19275        let start_offset = self.start.to_offset(snapshot);
19276        let end_offset = self.end.to_offset(snapshot);
19277        if start_offset == end_offset {
19278            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
19279        } else {
19280            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
19281        }
19282    }
19283}
19284
19285pub trait RowExt {
19286    fn as_f32(&self) -> f32;
19287
19288    fn next_row(&self) -> Self;
19289
19290    fn previous_row(&self) -> Self;
19291
19292    fn minus(&self, other: Self) -> u32;
19293}
19294
19295impl RowExt for DisplayRow {
19296    fn as_f32(&self) -> f32 {
19297        self.0 as f32
19298    }
19299
19300    fn next_row(&self) -> Self {
19301        Self(self.0 + 1)
19302    }
19303
19304    fn previous_row(&self) -> Self {
19305        Self(self.0.saturating_sub(1))
19306    }
19307
19308    fn minus(&self, other: Self) -> u32 {
19309        self.0 - other.0
19310    }
19311}
19312
19313impl RowExt for MultiBufferRow {
19314    fn as_f32(&self) -> f32 {
19315        self.0 as f32
19316    }
19317
19318    fn next_row(&self) -> Self {
19319        Self(self.0 + 1)
19320    }
19321
19322    fn previous_row(&self) -> Self {
19323        Self(self.0.saturating_sub(1))
19324    }
19325
19326    fn minus(&self, other: Self) -> u32 {
19327        self.0 - other.0
19328    }
19329}
19330
19331trait RowRangeExt {
19332    type Row;
19333
19334    fn len(&self) -> usize;
19335
19336    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
19337}
19338
19339impl RowRangeExt for Range<MultiBufferRow> {
19340    type Row = MultiBufferRow;
19341
19342    fn len(&self) -> usize {
19343        (self.end.0 - self.start.0) as usize
19344    }
19345
19346    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
19347        (self.start.0..self.end.0).map(MultiBufferRow)
19348    }
19349}
19350
19351impl RowRangeExt for Range<DisplayRow> {
19352    type Row = DisplayRow;
19353
19354    fn len(&self) -> usize {
19355        (self.end.0 - self.start.0) as usize
19356    }
19357
19358    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
19359        (self.start.0..self.end.0).map(DisplayRow)
19360    }
19361}
19362
19363/// If select range has more than one line, we
19364/// just point the cursor to range.start.
19365fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
19366    if range.start.row == range.end.row {
19367        range
19368    } else {
19369        range.start..range.start
19370    }
19371}
19372pub struct KillRing(ClipboardItem);
19373impl Global for KillRing {}
19374
19375const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
19376
19377struct BreakpointPromptEditor {
19378    pub(crate) prompt: Entity<Editor>,
19379    editor: WeakEntity<Editor>,
19380    breakpoint_anchor: Anchor,
19381    kind: BreakpointKind,
19382    block_ids: HashSet<CustomBlockId>,
19383    gutter_dimensions: Arc<Mutex<GutterDimensions>>,
19384    _subscriptions: Vec<Subscription>,
19385}
19386
19387impl BreakpointPromptEditor {
19388    const MAX_LINES: u8 = 4;
19389
19390    fn new(
19391        editor: WeakEntity<Editor>,
19392        breakpoint_anchor: Anchor,
19393        kind: BreakpointKind,
19394        window: &mut Window,
19395        cx: &mut Context<Self>,
19396    ) -> Self {
19397        let buffer = cx.new(|cx| {
19398            Buffer::local(
19399                kind.log_message()
19400                    .map(|msg| msg.to_string())
19401                    .unwrap_or_default(),
19402                cx,
19403            )
19404        });
19405        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
19406
19407        let prompt = cx.new(|cx| {
19408            let mut prompt = Editor::new(
19409                EditorMode::AutoHeight {
19410                    max_lines: Self::MAX_LINES as usize,
19411                },
19412                buffer,
19413                None,
19414                window,
19415                cx,
19416            );
19417            prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
19418            prompt.set_show_cursor_when_unfocused(false, cx);
19419            prompt.set_placeholder_text(
19420                "Message to log when breakpoint is hit. Expressions within {} are interpolated.",
19421                cx,
19422            );
19423
19424            prompt
19425        });
19426
19427        Self {
19428            prompt,
19429            editor,
19430            breakpoint_anchor,
19431            kind,
19432            gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
19433            block_ids: Default::default(),
19434            _subscriptions: vec![],
19435        }
19436    }
19437
19438    pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
19439        self.block_ids.extend(block_ids)
19440    }
19441
19442    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
19443        if let Some(editor) = self.editor.upgrade() {
19444            let log_message = self
19445                .prompt
19446                .read(cx)
19447                .buffer
19448                .read(cx)
19449                .as_singleton()
19450                .expect("A multi buffer in breakpoint prompt isn't possible")
19451                .read(cx)
19452                .as_rope()
19453                .to_string();
19454
19455            editor.update(cx, |editor, cx| {
19456                editor.edit_breakpoint_at_anchor(
19457                    self.breakpoint_anchor,
19458                    self.kind.clone(),
19459                    BreakpointEditAction::EditLogMessage(log_message.into()),
19460                    cx,
19461                );
19462
19463                editor.remove_blocks(self.block_ids.clone(), None, cx);
19464                cx.focus_self(window);
19465            });
19466        }
19467    }
19468
19469    fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
19470        self.editor
19471            .update(cx, |editor, cx| {
19472                editor.remove_blocks(self.block_ids.clone(), None, cx);
19473                window.focus(&editor.focus_handle);
19474            })
19475            .log_err();
19476    }
19477
19478    fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
19479        let settings = ThemeSettings::get_global(cx);
19480        let text_style = TextStyle {
19481            color: if self.prompt.read(cx).read_only(cx) {
19482                cx.theme().colors().text_disabled
19483            } else {
19484                cx.theme().colors().text
19485            },
19486            font_family: settings.buffer_font.family.clone(),
19487            font_fallbacks: settings.buffer_font.fallbacks.clone(),
19488            font_size: settings.buffer_font_size(cx).into(),
19489            font_weight: settings.buffer_font.weight,
19490            line_height: relative(settings.buffer_line_height.value()),
19491            ..Default::default()
19492        };
19493        EditorElement::new(
19494            &self.prompt,
19495            EditorStyle {
19496                background: cx.theme().colors().editor_background,
19497                local_player: cx.theme().players().local(),
19498                text: text_style,
19499                ..Default::default()
19500            },
19501        )
19502    }
19503}
19504
19505impl Render for BreakpointPromptEditor {
19506    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19507        let gutter_dimensions = *self.gutter_dimensions.lock();
19508        h_flex()
19509            .key_context("Editor")
19510            .bg(cx.theme().colors().editor_background)
19511            .border_y_1()
19512            .border_color(cx.theme().status().info_border)
19513            .size_full()
19514            .py(window.line_height() / 2.5)
19515            .on_action(cx.listener(Self::confirm))
19516            .on_action(cx.listener(Self::cancel))
19517            .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
19518            .child(div().flex_1().child(self.render_prompt_editor(cx)))
19519    }
19520}
19521
19522impl Focusable for BreakpointPromptEditor {
19523    fn focus_handle(&self, cx: &App) -> FocusHandle {
19524        self.prompt.focus_handle(cx)
19525    }
19526}
19527
19528fn all_edits_insertions_or_deletions(
19529    edits: &Vec<(Range<Anchor>, String)>,
19530    snapshot: &MultiBufferSnapshot,
19531) -> bool {
19532    let mut all_insertions = true;
19533    let mut all_deletions = true;
19534
19535    for (range, new_text) in edits.iter() {
19536        let range_is_empty = range.to_offset(&snapshot).is_empty();
19537        let text_is_empty = new_text.is_empty();
19538
19539        if range_is_empty != text_is_empty {
19540            if range_is_empty {
19541                all_deletions = false;
19542            } else {
19543                all_insertions = false;
19544            }
19545        } else {
19546            return false;
19547        }
19548
19549        if !all_insertions && !all_deletions {
19550            return false;
19551        }
19552    }
19553    all_insertions || all_deletions
19554}
19555
19556struct MissingEditPredictionKeybindingTooltip;
19557
19558impl Render for MissingEditPredictionKeybindingTooltip {
19559    fn render(&mut self, window: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
19560        ui::tooltip_container(window, cx, |container, _, cx| {
19561            container
19562                .flex_shrink_0()
19563                .max_w_80()
19564                .min_h(rems_from_px(124.))
19565                .justify_between()
19566                .child(
19567                    v_flex()
19568                        .flex_1()
19569                        .text_ui_sm(cx)
19570                        .child(Label::new("Conflict with Accept Keybinding"))
19571                        .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
19572                )
19573                .child(
19574                    h_flex()
19575                        .pb_1()
19576                        .gap_1()
19577                        .items_end()
19578                        .w_full()
19579                        .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
19580                            window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
19581                        }))
19582                        .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
19583                            cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
19584                        })),
19585                )
19586        })
19587    }
19588}
19589
19590#[derive(Debug, Clone, Copy, PartialEq)]
19591pub struct LineHighlight {
19592    pub background: Background,
19593    pub border: Option<gpui::Hsla>,
19594}
19595
19596impl From<Hsla> for LineHighlight {
19597    fn from(hsla: Hsla) -> Self {
19598        Self {
19599            background: hsla.into(),
19600            border: None,
19601        }
19602    }
19603}
19604
19605impl From<Background> for LineHighlight {
19606    fn from(background: Background) -> Self {
19607        Self {
19608            background,
19609            border: None,
19610        }
19611    }
19612}